Homework Assignment 2
DUE Tuesday12th November 23:59pm
Note: late submission awarded mark of zero. Please submit your attempt using Canvas. Submit only a single source file named as follows hw1_initial_surname.cs (e.g. my submission would be “hw1_r_humphries.cs”). Please make sure that your name and student number are commented at the top of the file. Canvas will refuse to accept submissions after the deadline.
Numerical simulation of Brownian motion
Implement the following methods as part of a class called BrownianMotion:
public bool outputToFile(string filename, double[] data);
This function writes the contents of the array of numbers of size n, referred to by data, into a text file named filename. The file is to be a csv file.
public void generateWalk(double[] data, int n, double T, double sigma);
This function generates a Brownian motion consisting of n steps as time t goes from 0 to T > 0, with 𝜎 = sigma, as follows:
• DefineΔ= 𝜎√𝑇 and𝛿𝑡= 𝑇 𝑛𝑛
• Make a Bernoulli trail as follows:
𝑋 = { Δ 𝑤𝑖𝑡h 𝑝𝑟𝑜𝑏𝑎𝑏𝑖𝑙𝑖𝑡𝑦 1/2
−Δ 𝑤𝑖𝑡h 𝑝𝑟𝑜𝑏𝑎𝑏𝑖𝑙𝑖𝑡𝑦 1/2
• Cumulatively create a random walk beginning at zero such that:
a. data[0] = 0
b. data[1] = data[0] + 𝑋
c. data[2] = data[1] + 𝑋
d. . . .
e. data[n-1] = data[n-2] + 𝑋
public void ensembledata(double[] data, int nperwalk, int nens, double T, double sigma);
Create nens random walks (using generateWalk) with nperwalk steps per walk from time 0 to T > 0 with 𝜎 = sigma. Store the last position attained by each walk into the array data (i.e. the last position of the first walk is stored the 0th position of data, the last position of the second walk is stored in the 1st position of data etc.)
public bool meanvar(double[] data, ref double mean, ref double var);
Calculate the mean and variance of the array of doubles referred to by data (of length size) and return the values by passing the variables mean and sigma as references.
To test your code, in your main method accomplish the following tasks,
• Generate one random walk with n = 1000, T = 10, 𝜎 = 1, and store the walk in an array, then output the array to a file.
• Generate 1000 random walks each with n = 1000, T = 10, 𝜎 = 1, and record the last position of each of these walks in an array. Calculate the mean and variance of this data and output it to console, then output the array to a file.
• Repeat the previous task but changing 𝜎 = 2,3,4,…,9 and without writing to file.
Check the random walk generated by generateWalk(data, 1000, 10, 1) by importing the data into excel and making a plot.