0

This is probably a really stupid question, but I just can't seem to work out how to do it for some reason. I've created a function for a random walk here which just uses the numpy binomial function with one trial (ie if it's under 0.5 it's -1, over it's +1. However this obviously makes the first value of the function either -1 or +1, whereas I want it to be zero. How can I change this?

import numpy as np
import matplotlib.pyplot as plt

def random_walk(N,d):
    walk = d*np.cumsum(2*np.random.binomial(1,.5,N-1)-1)
    return walk

plt.plot(np.arange(1,250),random_walk(250,1))
plt.show()

Again, it's probably really simple and I'm being really stupid, but I'd really appreciate the help!

T. L
  • 103
  • 2
  • 8
  • 1
    `np.arange(0,249)` instead of `np.arange(1,250)`, the first parameter of the function `plot` is the axis. – silgon Nov 23 '18 at 13:22
  • I mean the y-axis though, not the x-axis. This just makes the coordinate (0,-1) or (0,1), I want it to be (0,0). I realise I need to change it to np,arange(0,250) for that to work but I'm not sure how to set the initial value of the function. – T. L Nov 23 '18 at 13:26
  • sorry, I misread, I posted an answer with a little modification in your code. I hope this is what you wanted. You should just start your distribution at zero, because it's your starting point. – silgon Nov 23 '18 at 13:35

1 Answers1

0

Little tweak to your code. Hopefully this is what you're looking for.

import numpy as np
import matplotlib.pyplot as plt

def random_walk(N,d):
    walk = np.concatenate(([0],np.cumsum(2*np.random.binomial(1,.5,N-1)-1)))
    return walk

plt.plot(np.arange(0,250),random_walk(250,1))
plt.show()
silgon
  • 6,890
  • 7
  • 46
  • 67
  • Be carefull on how you plot, you can plot just with `plt.plot(random_walk(250,1))` since you don't care about the x axis. – silgon Nov 23 '18 at 13:37