1
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?

1
  • Conventionally, pyplot is imported as plt rather than pt. Commented Oct 12, 2020 at 15:59

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

4 Comments

@user14369387. What does that mean?
I am trying to map this function so that it takes each x and turns these into e to the power (a+(b times x)), how can I do it?
I upvoted your answer afterwards :) and yes i just deleted it
1

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.

1 Comment

Took me a second to realize that that won't alter the distribution of steps. Just the initial value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.