Reputation: 39
import numpy as np
import math as m
from matplotlib import pyplot as plt
#Q1
def bm(s,n):
np.random.seed(222)
dw = np.random.normal(0,1,size=(s,n))*m.sqrt(1/n)
w = np.cumsum(dw, axis=1)
a = np.mean(w, axis=0)
b = np.std(w, axis=0)
plt.plot(np.arange(n),w[:10:,:].T)
plt.plot(np.arange(n),a.T)
plt.plot(np.arange(n),b.T)
plt.show()
bm(1000,600)
This code creates Brownian Motions generated from random standard normal distributions. Every graph needs to start at 0, so I need to append 0 to the beginning of each graph. How can I do this?
Upvotes: 1
Views: 83
Reputation: 69242
In general, you can use numpy.concatenate to append arrays.
But in this specific case, I'd just do
dw[:, 0] = 0.0
after you create dw
.
Upvotes: 1
Reputation: 114518
You can always subtract off the first delta:
w = np.cumsum(dw, axis=1) - dw[:, :1]
The elements of w
are normally given by
dw[:, :1]
dw[:, :1] + dw[:, 1:2]
dw[:, :1] + dw[:, 1:2] + dw[:, 2:3]
...
Clearly removing dw[:, :1]
offsets the sum by the first element. The difference between dw[:, 0]
and dw[:, :1]
is that the latter preserves the shape for proper broadcasting, as if you did dw[:, 0][:, None]
. If you insist on removing the last element rather than the first, you can do
w = np.empty_like(dw)
np.cumsum(dw[:, :-1], axis=1, out=w[:, 1:])
w[:, 0] = 0
You can actually prepend a zero in a couple of different ways. A concatenation is one way:
np.concatenate((np.zeros((dw.shape[0], 1)), np.cumsum(dw, axis=1)), axis=1)
A potentially better way, hinted above, might be to pre-allocate the output buffer:
w = np.empty((dw.shape[0], dw.shape[1] + 1))
np.cumsum(dw, axis=1, out=w[:, 1:])
w[:, 0] = 0
Upvotes: 1