This Python code simulates a credit default swap by generating default times for 1 million bonds using hazard rates, calculating the payoff and premium payments, and determining the CDS spread needed to equate average payoffs to average premiums. It then prints the resulting CDS spread and premium, along with the time taken to run the simulation.
C++ question 6 || solution of Programming Problem Topics MixeR
Write a program to create an array of 10 elements, initialize each element a random value (1 to 50). Print the array values. Then, Reverse the values stored in array. Output the final array values.
Lightning Talk on Software Transactional Memory in Scala. The Actors Pattern has gotten a lot of attention in the Scala ecosphere, but STM of often a good first solution for solving concurrency problems. It's odd that it hasn't had as much attention in the Scala world, so this talk aims to show how easy it is to use, and compare it to typical lock-based synchronization by showing how easy it is to make errors with lock-based synchronization
C++ question 6 || solution of Programming Problem Topics MixeR
Write a program to create an array of 10 elements, initialize each element a random value (1 to 50). Print the array values. Then, Reverse the values stored in array. Output the final array values.
Lightning Talk on Software Transactional Memory in Scala. The Actors Pattern has gotten a lot of attention in the Scala ecosphere, but STM of often a good first solution for solving concurrency problems. It's odd that it hasn't had as much attention in the Scala world, so this talk aims to show how easy it is to use, and compare it to typical lock-based synchronization by showing how easy it is to make errors with lock-based synchronization
JavaScript Advanced - Useful methods to power up your codeLaurence Svekis ✔
Get this Course
https://www.udemy.com/javascript-course-plus/?couponCode=SLIDESHARE
Useful methods and JavaScript code snippets power up your code and make even more happen with it.
This course is perfect for anyone who has fundamental JavaScript experience and wants to move to the next level. Use and apply more advanced code, and do more with JavaScript.
Everything you need to learn more about JavaScript
Source code is included
60+ page Downloadable PDF guide with resources and code snippets
3 Challenges to get you coding try the code
demonstrating useful JavaScript methods that can power up your code and make even more happen with it.
Course lessons will cover
JavaScript Number Methods
JavaScript String Methods
JavaScript Math - including math random
DOMContentLoaded - DOM ready when the document has loaded.
JavaScript Date - Date methods and how to get set and use date.
JavaScript parse and stringify - strings to objects back to strings
JavaScript LocalStorage - store variables in the user browser
JavaScript getBoundingClientRect() - get the dimensions of an element
JavaScript Timers setTimeout() setInterval() requestAnimationFrame() - Run code when you want too
encodeURIComponent - encoding made easy
Regex - so powerful use it to get values from your string
prototype - extend JavaScript objects with customized powers
Try and catch - perfect for error and testing
Fetch xHR requests - bring content in from servers
and more
No libraries, no shortcuts just learning JavaScript making it DYNAMIC and INTERACTIVE web application.
Step by step learning with all steps included.
Being a slow interpreter, Python may drive a system to deliver utmost speed if some guidelines are followed. The key is to treat programming languages as syntactic sugar to the machine code. It expedites the workflow of timing, iterative design, automatic testing, optimization, and realize an HPC system balancing the time to market and quality of code.
Speed is the king. 10x productive developers change business. So does 10x faster code. Python is 100x slower than C++ but it only matters when you really use Python to implement number-crunching algorithms. We should not do that, and instead go directly with C++ for speed. It calls for strict disciplines of software engineering and code quality, but it should be noted that here the quality is defined by the runtime and the time to market.
The presentation focuses on the Python side of the development workflow. It is made possible by confining C++ in architecture defined by the Python code, which realizes most of the software engineering. The room for writing fast C++ code is provided by pybind11 and careful design of typed data objects. The data objects hold memory buffers exposed to Python as numpy ndarrays for direct access for speed.
Write a java program to randomly generate the following sets of data.pdfarshin9
Write a java program to randomly generate the following sets of data:
1.) 10 numbers
2.) 1,000 numbers
3.) 100,000 numbers
4.) 1,000,000 numbers
5.) 10,000,000 numbers
Your program must sort the above sets of numbers using the following algorithms:
1.) Insertion Sort
2.) Merge Sort
3.) Quick Sort
4.) Heap Sort
Print out the time each algorithm takes to sort the above numbers
Solution
import java.util.Random;
public class Sort {
private int[] array;
private int size ;
public Sort(int n){
array = new int[n];
size = n;
Random rand = new Random();
for (int i = 0 ; i < n ; i++ ) {
array[i] = rand.nextInt(100000) ;
}
}
public void print(){
for (int i = 0; i < size ; i++ ) {
System.out.print(array[i] + \" \");
}
System.out.println(\"\");
}
void insertion_sort()
{
for (int i=1; i=0 && array[j] > key)
{
array[j+1] = array[j];
j = j-1;
}
array[j+1] = key;
}
}
void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int [n1];
int R[] = new int [n2];
/*Copy data to temp arrays*/
for (int i=0; i Array to be sorted,
low --> Starting index,
high --> Ending index */
void quick_sort(int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[pi] is
now at right place */
int pi = partition(array, low, high);
// Recursively sort elements before
// partition and after partition
quick_sort(low, pi-1);
quick_sort(pi+1, high);
}
}
public void heap_sort()
{
int n = array.length;
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(array, n, i);
// One by one extract an element from heap
for (int i=n-1; i>=0; i--)
{
// Move current root to end
int temp = array[0];
array[0] = array[i];
array[i] = temp;
// call max heapify on the reduced heap
heapify(array, i, 0);
}
}
// To heapify a subtree rooted with node i which is
// an index in arr[]. n is size of heap
void heapify(int arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2*i + 1; // left = 2*i + 1
int r = 2*i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// If largest is not root
if (largest != i)
{
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
public static void main(String[] args) {
Sort sort1 = new Sort(10);
long start = System.currentTimeMillis();
sort1.insertion_sort();
long time = System.currentTimeMillis() - start;
//sort1.print();
System.out.println(\"insertion_sort for 10 numbers take \" + time + \" ms \");
sort1 = new Sort(10);
start = System.currentTimeMillis();
sort1.merge_sort(0,9);
time = System.currentTimeMillis() - start;
//sort1.print();
System.out.println(\"merge_sort for 10 numbers take \" + time + \" ms \");
sort1 = new Sort(10);
start = System.currentTimeMillis();
sort1.quick_sor.
I have written the code but cannot complete the assignment please help.pdfshreeaadithyaacellso
I have written the code but cannot complete the assignment please help me to complete.
Please don't just copy other s answers as your own.
// Insertion sort
/*
#include <ctime>
#include <iostream>
using namespace std;
void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
// Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current
position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
int main() {
int n;
cout << "Enter the size of the array: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int num = sizeof(arr) / sizeof(arr[0]);
clock_t start, end;
double timetaken;
start = clock();
insertionSort(arr, num);
end = clock();
cout << "Sorted array: \n";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
timetaken = ((double) (end - start)) / CLOCKS_PER_SEC;
cout << "Time taken : " << fixed << timetaken << "s" << endl;
return 0;
}
*/
// Shell Sort
/*
#include <ctime>
#include <iostream>
using namespace std;
int shellSort(int arr[], int n) {
for (int gap = n/2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i += 1) {
int temp = arr[i];
int j;
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
arr[j] = arr[j - gap];
arr[j] = temp;
}
}
return 0;
}
void printArray(int arr[], int n) {
for (int i=0; i<n; i++)
cout << arr[i] << " ";
}
int main() {
int n;
cout << "Enter the size of the array: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int num = sizeof(arr) / sizeof(arr[0]);
clock_t start, end;
double timetaken;
start = clock();
shellSort(arr, num);
end = clock();
cout << "\nArray after sorting: \n";
printArray(arr, n);
cout << endl;
timetaken = (double)(end - start) / CLOCKS_PER_SEC;
cout << "Time taken : " << fixed << timetaken << "s" << endl;
return 0;
}
*/
// MergeSort
/*
#include <ctime>
#include <iostream>
using namespace std;
void merge(int arr[], int l, int m, int r) {
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r) {
if (l < r) {
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
int main() {
int n;
cout << "Enter the size of the array: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int arr_size = sizeof(arr) / sizeof(arr[0]);
clock_t start;
clock_t end;
double timetaken;
start = clock();
mergeSort(arr, 0, arr_size - 1);
end = clock();
timetaken = (double)(end - start) / CLOCKS_PER_SEC;
.
Please observe the the code and validations of user inputs.import .pdfapexjaipur
Please observe the the code and validations of user inputs.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Random;
public class SlotMachineSimulation
{
public static void main(String[]args) throws FileNotFoundException
{
//Open File
File file = new File(\"input.txt\");
int choice;
//Open File to write on
PrintWriter outputFile = new PrintWriter(\"output.txt\");
// Create a Scanner object for keyboard input.
Scanner keyboard=new Scanner(System.in);
// Create a Scanner object for input File data.
Scanner inputFile = new Scanner(file);
Scanner readFile=new Scanner(file);
//Declaring Variables
int fr1,fr2,fr3;
String fruit;
int num;
int select;
int amountBet;
int won,lost = 0;
String decision;
int total=0;
System.out.println(\"Welcome to Guanyu Tian\'s Slot Machine!\");
int n = inputFile.nextInt();
do{
System.out.println(\"You inserted \" + n + \" into the slot machine!\" );
System.out.println(\"You currently have \" + n + \", you can bet the multiple of $10.\");
System.out.println(\"If you enter 1, you will bet $10\ If you enter 2, you will bet $20, etc.\");
do{
//ask user to insert the bet amount
System.out.println(\"Please enter how much do you want to bet this time: \");
num=keyboard.nextInt();
if(num<1 || num>(n/10))
{
amountBet=num*10;
System.out.printf(\"Sorry, you don\'t have $\"+amountBet+\" now\\t\");
System.out.println(\"You can only bet less than the amount of money you have.\");
System.out.println(\"You currently have $\"+n+\", You can the multiple of $10.\");
System.out.println(\"If you enter 1, you will bet $10\ If you enter 2, you will bet $20, etc.\");
//System.exit(0);
}
}while(1>num || (n/10)6 ){
System.out.println(\"Invalid selection. You must enter a number between 1 and 6 inclusive\");
//System.exit(0);
}
} while(select<1 || select >6);
//Generating a random fruit
Random randNum=new Random();
fr1 = randNum.nextInt(6)+1;
fr2 = randNum.nextInt(6)+1;
fr3 = randNum.nextInt(6)+1;
if(select == fr1&&select==fr2&&select==fr3){
System.out.println(fr1+\" \"+fr2+\" \"+fr3);
won = amountBet *3;
total=n+won;
System.out.println(\"You have won 3 times bet amount.\"+won);
System.out.println(\"Your current balance.\"+total);
outputFile.println(\"You have won 3 times bet amount.\"+won);
outputFile.println(n);
}
else if(select==fr1&&select==fr2||select==fr2&&select==fr3||select==fr3&&select==fr1){
System.out.println(fr1+\" \"+fr2+\" \"+fr3);
won= amountBet *2;
total=n+won;
System.out.println(\"You have won 2 times bet amount.\"+won);
System.out.println(\"Your current balance.\"+total);
outputFile.println(\"You have won 2 times bet amount.\"+won);
outputFile.println(n);
}
else if(select == fr1||select == fr2||select == fr3){
System.out.println(fr1+\" \"+fr2+\" \"+fr3);
won= amountBet ;
total=n+won;
System.out.println(\"You have won 1 times bet amount.\"+won);
System.out.println(\"Your current balance.\"+total);
outputFile.println(\"You have won 1 times bet amount.
Hybrid quantum classical neural networks with pytorch and qiskitVijayananda Mohire
We explore how a classical neural network can be partially quantized to create a hybrid quantum-classical neural network, that seeks to classify images of two types of hand drawn digits (0 or 1) from MNIST dataset
Write a program that obtains the execution time of selection sort, bu.pdfarri2009av
Write a java program called Question39 that does the following: Gets input for temperature
Utilizing a branching statement: If temperature is 76-100, call method outputHot passing the
temperature input as an argument. If temperature is 0-39, call method outputCold passing the
temperature input as an argument. If temperature is 40 to 75, call method outputJustRight
passing the temperature input as an argument. If temperature is outside these ranges, output
“Temperature outside range” to the screen. Be precise, import modules, include comments,
prologue, etc. as needed.
Solution
Question39.java
import java.util.Scanner;
public class Question39 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println(\"Enter temperature: \");
int temp = scan.nextInt();
if(temp >=76 && temp <=100){
outputHot(temp);
}
else if(temp >=0 && temp <=39){
outputCold(temp);
}
else if(temp >=40 && temp <=75){
outputJustRight(temp);
}
else{
System.out.println(\"Temperature outside range\");
}
}
public static void outputHot(int temp){
System.out.println(\"Temperature \"+temp+\" Hot \");
}
public static void outputCold(int temp){
System.out.println(\"Temperature \"+temp+\" Cold \");
}
public static void outputJustRight(int temp){
System.out.println(\"Temperature \"+temp+\" Just Right \");
}
}
Output:
Enter temperature:
45
Temperature 45 Just Right.
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docxSALU18
error 2.pdf
10/13/16, 6(46 PM01_error
Page 1 of 5http://localhost:8888/nbconvert/html/group/01_error.ipynb?download=false
In [ ]: %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import sys
Error Definitions
Following is an example for the concept of absolute error, relative error and decimal precision:
We shall test the approximation to common mathematical constant, . Compute the absolute and relative
errors along with the decimal precision if we take the approximate value of .
In [ ]: # We can use the formulas you derieved above to calculate the actual n
umbers
absolute_error = np.abs(np.exp(1) - 2.718)
relative_error = absolute_error/np.exp(1)
print "The absolute error is "+str(absolute_error)
print "The relative error is "+str(relative_error)
Machine epsilon is a very important concept in floating point error. The value, even though miniscule, can
easily compund over a period to cause huge problems.
Below we see a problem demonstating how easily machine error can creep into a simple piece of code:
In [ ]: a = 4.0/3.0
b = a - 1.0
c = 3*b
eps = 1 - c
print 'Value of a is ' +str(a)
print 'Value of b is ' +str(b)
print 'Value of c is ' +str(c)
print 'Value of epsilon is ' +str(eps)
Ideally eps should be 0, but instead we see the machine epsilon and while the value is small it can lead to
issues.
e
e = 2.718
10/13/16, 6(46 PM01_error
Page 2 of 5http://localhost:8888/nbconvert/html/group/01_error.ipynb?download=false
In [ ]: print "The progression of error:"
for i in range(1,20):
print str(abs((10**i)*c - (10**i)))
The largest floating point number
The formula for obtaining the number is shown below, instead of calculating the value we can use the
system library to find this value.
In [ ]: maximum = (2.0-eps)*2.0**1023
print sys.float_info.max
print 'Value of maximum is ' +str(maximum)
The smallest floating point number
The formula for obtaining the number is shown below. Similarly the value can be found using the system
library to find this value.
In [ ]: minimum = eps*2.0**(-1022)
print sys.float_info.min
print sys.float_info.min*sys.float_info.epsilon
print 'Value of minimum is ' +str(minimum)
As we try to compute a number bigger than the aforementioned, largest floating point number we see weird
errors. The computer assigns infinity to these values.
In [ ]: overflow = maximum*10.0
print 'Value of overflow is ' +str(overflow)
As we try to compute a number smaller than the aforementioned smallest floating point number we see that
the computer assigns it the value 0. We actually lose precision in this case.
10/13/16, 6(46 PM01_error
Page 3 of 5http://localhost:8888/nbconvert/html/group/01_error.ipynb?download=false
In [1]: underflow = minimum/2.0
print 'Value of underflow is ' +str(underflow)
Truncation error is a very common form of error you will keep seing in the area of Numerical
Analysis/Computing.
Here we will look at the classic Calculus example of the approximation near 0. We c ...
JavaScript Advanced - Useful methods to power up your codeLaurence Svekis ✔
Get this Course
https://www.udemy.com/javascript-course-plus/?couponCode=SLIDESHARE
Useful methods and JavaScript code snippets power up your code and make even more happen with it.
This course is perfect for anyone who has fundamental JavaScript experience and wants to move to the next level. Use and apply more advanced code, and do more with JavaScript.
Everything you need to learn more about JavaScript
Source code is included
60+ page Downloadable PDF guide with resources and code snippets
3 Challenges to get you coding try the code
demonstrating useful JavaScript methods that can power up your code and make even more happen with it.
Course lessons will cover
JavaScript Number Methods
JavaScript String Methods
JavaScript Math - including math random
DOMContentLoaded - DOM ready when the document has loaded.
JavaScript Date - Date methods and how to get set and use date.
JavaScript parse and stringify - strings to objects back to strings
JavaScript LocalStorage - store variables in the user browser
JavaScript getBoundingClientRect() - get the dimensions of an element
JavaScript Timers setTimeout() setInterval() requestAnimationFrame() - Run code when you want too
encodeURIComponent - encoding made easy
Regex - so powerful use it to get values from your string
prototype - extend JavaScript objects with customized powers
Try and catch - perfect for error and testing
Fetch xHR requests - bring content in from servers
and more
No libraries, no shortcuts just learning JavaScript making it DYNAMIC and INTERACTIVE web application.
Step by step learning with all steps included.
Being a slow interpreter, Python may drive a system to deliver utmost speed if some guidelines are followed. The key is to treat programming languages as syntactic sugar to the machine code. It expedites the workflow of timing, iterative design, automatic testing, optimization, and realize an HPC system balancing the time to market and quality of code.
Speed is the king. 10x productive developers change business. So does 10x faster code. Python is 100x slower than C++ but it only matters when you really use Python to implement number-crunching algorithms. We should not do that, and instead go directly with C++ for speed. It calls for strict disciplines of software engineering and code quality, but it should be noted that here the quality is defined by the runtime and the time to market.
The presentation focuses on the Python side of the development workflow. It is made possible by confining C++ in architecture defined by the Python code, which realizes most of the software engineering. The room for writing fast C++ code is provided by pybind11 and careful design of typed data objects. The data objects hold memory buffers exposed to Python as numpy ndarrays for direct access for speed.
Write a java program to randomly generate the following sets of data.pdfarshin9
Write a java program to randomly generate the following sets of data:
1.) 10 numbers
2.) 1,000 numbers
3.) 100,000 numbers
4.) 1,000,000 numbers
5.) 10,000,000 numbers
Your program must sort the above sets of numbers using the following algorithms:
1.) Insertion Sort
2.) Merge Sort
3.) Quick Sort
4.) Heap Sort
Print out the time each algorithm takes to sort the above numbers
Solution
import java.util.Random;
public class Sort {
private int[] array;
private int size ;
public Sort(int n){
array = new int[n];
size = n;
Random rand = new Random();
for (int i = 0 ; i < n ; i++ ) {
array[i] = rand.nextInt(100000) ;
}
}
public void print(){
for (int i = 0; i < size ; i++ ) {
System.out.print(array[i] + \" \");
}
System.out.println(\"\");
}
void insertion_sort()
{
for (int i=1; i=0 && array[j] > key)
{
array[j+1] = array[j];
j = j-1;
}
array[j+1] = key;
}
}
void merge(int arr[], int l, int m, int r)
{
// Find sizes of two subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;
/* Create temp arrays */
int L[] = new int [n1];
int R[] = new int [n2];
/*Copy data to temp arrays*/
for (int i=0; i Array to be sorted,
low --> Starting index,
high --> Ending index */
void quick_sort(int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[pi] is
now at right place */
int pi = partition(array, low, high);
// Recursively sort elements before
// partition and after partition
quick_sort(low, pi-1);
quick_sort(pi+1, high);
}
}
public void heap_sort()
{
int n = array.length;
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(array, n, i);
// One by one extract an element from heap
for (int i=n-1; i>=0; i--)
{
// Move current root to end
int temp = array[0];
array[0] = array[i];
array[i] = temp;
// call max heapify on the reduced heap
heapify(array, i, 0);
}
}
// To heapify a subtree rooted with node i which is
// an index in arr[]. n is size of heap
void heapify(int arr[], int n, int i)
{
int largest = i; // Initialize largest as root
int l = 2*i + 1; // left = 2*i + 1
int r = 2*i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// If largest is not root
if (largest != i)
{
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
public static void main(String[] args) {
Sort sort1 = new Sort(10);
long start = System.currentTimeMillis();
sort1.insertion_sort();
long time = System.currentTimeMillis() - start;
//sort1.print();
System.out.println(\"insertion_sort for 10 numbers take \" + time + \" ms \");
sort1 = new Sort(10);
start = System.currentTimeMillis();
sort1.merge_sort(0,9);
time = System.currentTimeMillis() - start;
//sort1.print();
System.out.println(\"merge_sort for 10 numbers take \" + time + \" ms \");
sort1 = new Sort(10);
start = System.currentTimeMillis();
sort1.quick_sor.
I have written the code but cannot complete the assignment please help.pdfshreeaadithyaacellso
I have written the code but cannot complete the assignment please help me to complete.
Please don't just copy other s answers as your own.
// Insertion sort
/*
#include <ctime>
#include <iostream>
using namespace std;
void insertionSort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
// Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current
position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
int main() {
int n;
cout << "Enter the size of the array: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int num = sizeof(arr) / sizeof(arr[0]);
clock_t start, end;
double timetaken;
start = clock();
insertionSort(arr, num);
end = clock();
cout << "Sorted array: \n";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
timetaken = ((double) (end - start)) / CLOCKS_PER_SEC;
cout << "Time taken : " << fixed << timetaken << "s" << endl;
return 0;
}
*/
// Shell Sort
/*
#include <ctime>
#include <iostream>
using namespace std;
int shellSort(int arr[], int n) {
for (int gap = n/2; gap > 0; gap /= 2) {
for (int i = gap; i < n; i += 1) {
int temp = arr[i];
int j;
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
arr[j] = arr[j - gap];
arr[j] = temp;
}
}
return 0;
}
void printArray(int arr[], int n) {
for (int i=0; i<n; i++)
cout << arr[i] << " ";
}
int main() {
int n;
cout << "Enter the size of the array: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int num = sizeof(arr) / sizeof(arr[0]);
clock_t start, end;
double timetaken;
start = clock();
shellSort(arr, num);
end = clock();
cout << "\nArray after sorting: \n";
printArray(arr, n);
cout << endl;
timetaken = (double)(end - start) / CLOCKS_PER_SEC;
cout << "Time taken : " << fixed << timetaken << "s" << endl;
return 0;
}
*/
// MergeSort
/*
#include <ctime>
#include <iostream>
using namespace std;
void merge(int arr[], int l, int m, int r) {
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
i = 0;
j = 0;
k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r) {
if (l < r) {
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
int main() {
int n;
cout << "Enter the size of the array: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
int arr_size = sizeof(arr) / sizeof(arr[0]);
clock_t start;
clock_t end;
double timetaken;
start = clock();
mergeSort(arr, 0, arr_size - 1);
end = clock();
timetaken = (double)(end - start) / CLOCKS_PER_SEC;
.
Please observe the the code and validations of user inputs.import .pdfapexjaipur
Please observe the the code and validations of user inputs.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Random;
public class SlotMachineSimulation
{
public static void main(String[]args) throws FileNotFoundException
{
//Open File
File file = new File(\"input.txt\");
int choice;
//Open File to write on
PrintWriter outputFile = new PrintWriter(\"output.txt\");
// Create a Scanner object for keyboard input.
Scanner keyboard=new Scanner(System.in);
// Create a Scanner object for input File data.
Scanner inputFile = new Scanner(file);
Scanner readFile=new Scanner(file);
//Declaring Variables
int fr1,fr2,fr3;
String fruit;
int num;
int select;
int amountBet;
int won,lost = 0;
String decision;
int total=0;
System.out.println(\"Welcome to Guanyu Tian\'s Slot Machine!\");
int n = inputFile.nextInt();
do{
System.out.println(\"You inserted \" + n + \" into the slot machine!\" );
System.out.println(\"You currently have \" + n + \", you can bet the multiple of $10.\");
System.out.println(\"If you enter 1, you will bet $10\ If you enter 2, you will bet $20, etc.\");
do{
//ask user to insert the bet amount
System.out.println(\"Please enter how much do you want to bet this time: \");
num=keyboard.nextInt();
if(num<1 || num>(n/10))
{
amountBet=num*10;
System.out.printf(\"Sorry, you don\'t have $\"+amountBet+\" now\\t\");
System.out.println(\"You can only bet less than the amount of money you have.\");
System.out.println(\"You currently have $\"+n+\", You can the multiple of $10.\");
System.out.println(\"If you enter 1, you will bet $10\ If you enter 2, you will bet $20, etc.\");
//System.exit(0);
}
}while(1>num || (n/10)6 ){
System.out.println(\"Invalid selection. You must enter a number between 1 and 6 inclusive\");
//System.exit(0);
}
} while(select<1 || select >6);
//Generating a random fruit
Random randNum=new Random();
fr1 = randNum.nextInt(6)+1;
fr2 = randNum.nextInt(6)+1;
fr3 = randNum.nextInt(6)+1;
if(select == fr1&&select==fr2&&select==fr3){
System.out.println(fr1+\" \"+fr2+\" \"+fr3);
won = amountBet *3;
total=n+won;
System.out.println(\"You have won 3 times bet amount.\"+won);
System.out.println(\"Your current balance.\"+total);
outputFile.println(\"You have won 3 times bet amount.\"+won);
outputFile.println(n);
}
else if(select==fr1&&select==fr2||select==fr2&&select==fr3||select==fr3&&select==fr1){
System.out.println(fr1+\" \"+fr2+\" \"+fr3);
won= amountBet *2;
total=n+won;
System.out.println(\"You have won 2 times bet amount.\"+won);
System.out.println(\"Your current balance.\"+total);
outputFile.println(\"You have won 2 times bet amount.\"+won);
outputFile.println(n);
}
else if(select == fr1||select == fr2||select == fr3){
System.out.println(fr1+\" \"+fr2+\" \"+fr3);
won= amountBet ;
total=n+won;
System.out.println(\"You have won 1 times bet amount.\"+won);
System.out.println(\"Your current balance.\"+total);
outputFile.println(\"You have won 1 times bet amount.
Hybrid quantum classical neural networks with pytorch and qiskitVijayananda Mohire
We explore how a classical neural network can be partially quantized to create a hybrid quantum-classical neural network, that seeks to classify images of two types of hand drawn digits (0 or 1) from MNIST dataset
Write a program that obtains the execution time of selection sort, bu.pdfarri2009av
Write a java program called Question39 that does the following: Gets input for temperature
Utilizing a branching statement: If temperature is 76-100, call method outputHot passing the
temperature input as an argument. If temperature is 0-39, call method outputCold passing the
temperature input as an argument. If temperature is 40 to 75, call method outputJustRight
passing the temperature input as an argument. If temperature is outside these ranges, output
“Temperature outside range” to the screen. Be precise, import modules, include comments,
prologue, etc. as needed.
Solution
Question39.java
import java.util.Scanner;
public class Question39 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println(\"Enter temperature: \");
int temp = scan.nextInt();
if(temp >=76 && temp <=100){
outputHot(temp);
}
else if(temp >=0 && temp <=39){
outputCold(temp);
}
else if(temp >=40 && temp <=75){
outputJustRight(temp);
}
else{
System.out.println(\"Temperature outside range\");
}
}
public static void outputHot(int temp){
System.out.println(\"Temperature \"+temp+\" Hot \");
}
public static void outputCold(int temp){
System.out.println(\"Temperature \"+temp+\" Cold \");
}
public static void outputJustRight(int temp){
System.out.println(\"Temperature \"+temp+\" Just Right \");
}
}
Output:
Enter temperature:
45
Temperature 45 Just Right.
error 2.pdf101316, 6(46 PM01_errorPage 1 of 5http.docxSALU18
error 2.pdf
10/13/16, 6(46 PM01_error
Page 1 of 5http://localhost:8888/nbconvert/html/group/01_error.ipynb?download=false
In [ ]: %matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import sys
Error Definitions
Following is an example for the concept of absolute error, relative error and decimal precision:
We shall test the approximation to common mathematical constant, . Compute the absolute and relative
errors along with the decimal precision if we take the approximate value of .
In [ ]: # We can use the formulas you derieved above to calculate the actual n
umbers
absolute_error = np.abs(np.exp(1) - 2.718)
relative_error = absolute_error/np.exp(1)
print "The absolute error is "+str(absolute_error)
print "The relative error is "+str(relative_error)
Machine epsilon is a very important concept in floating point error. The value, even though miniscule, can
easily compund over a period to cause huge problems.
Below we see a problem demonstating how easily machine error can creep into a simple piece of code:
In [ ]: a = 4.0/3.0
b = a - 1.0
c = 3*b
eps = 1 - c
print 'Value of a is ' +str(a)
print 'Value of b is ' +str(b)
print 'Value of c is ' +str(c)
print 'Value of epsilon is ' +str(eps)
Ideally eps should be 0, but instead we see the machine epsilon and while the value is small it can lead to
issues.
e
e = 2.718
10/13/16, 6(46 PM01_error
Page 2 of 5http://localhost:8888/nbconvert/html/group/01_error.ipynb?download=false
In [ ]: print "The progression of error:"
for i in range(1,20):
print str(abs((10**i)*c - (10**i)))
The largest floating point number
The formula for obtaining the number is shown below, instead of calculating the value we can use the
system library to find this value.
In [ ]: maximum = (2.0-eps)*2.0**1023
print sys.float_info.max
print 'Value of maximum is ' +str(maximum)
The smallest floating point number
The formula for obtaining the number is shown below. Similarly the value can be found using the system
library to find this value.
In [ ]: minimum = eps*2.0**(-1022)
print sys.float_info.min
print sys.float_info.min*sys.float_info.epsilon
print 'Value of minimum is ' +str(minimum)
As we try to compute a number bigger than the aforementioned, largest floating point number we see weird
errors. The computer assigns infinity to these values.
In [ ]: overflow = maximum*10.0
print 'Value of overflow is ' +str(overflow)
As we try to compute a number smaller than the aforementioned smallest floating point number we see that
the computer assigns it the value 0. We actually lose precision in this case.
10/13/16, 6(46 PM01_error
Page 3 of 5http://localhost:8888/nbconvert/html/group/01_error.ipynb?download=false
In [1]: underflow = minimum/2.0
print 'Value of underflow is ' +str(underflow)
Truncation error is a very common form of error you will keep seing in the area of Numerical
Analysis/Computing.
Here we will look at the classic Calculus example of the approximation near 0. We c ...
Router Queue Simulation in C++ in MMNN and MM1 conditions
PYTHON_CDS_SPREAD_CALCULATIOn
1. '''
Created on Jan 25, 2016
@author: HTQ
'''
from math import sqrt
from random import gauss
from numpy import ones, random,exp,average,maximum, zeros, array, log, minimum
import time
StartTime=time.clock()
interest_rate=0.05
hazard_rate=0.007
recovery_rate=0.10
time_to_maturity = 10
Traj = 1000000
notional = 1000000
DefaultTime=-log(random.random_sample((Traj,)))/hazard_rate
IFdefault=DefaultTime<time_to_maturity
Payoff=notional*(1-recovery_rate)*exp(-interest_rate*DefaultTime)*IFdefault
Premiumpaytime=minimum(time_to_maturity,DefaultTime)
payment=notional*0.0001* (1-exp(-interest_rate*Premiumpaytime))/interest_rate
CDS_Spread=average(Payoff)/average(payment)
CDS_Premium=CDS_Spread*notional*0.0001
print(CDS_Spread)
print(CDS_Premium)
EndTime=time.clock()
print('It took following seconds to run the program')
print(EndTime-StartTime )