-6

I am trying to write a code for random walk, and in the direction part, I met this problem. I want the direction to be any degrees, what I do is try to use py.arrange to generate as many numbers as possible between -1 and 1. I want to ask is there any better solutions to go through all the numbers between -1 and 1? Thanks!

Here is my code:

def fill_walk(self):
    while len(self.x_values)<self.num_points:
        x_direction=choice(np.arange(-1,1,0.00001))
        x_distance=(int(1))
        x_step=x_direction*x_distance

        y_direction=choice(np.arange(-1,1,0.00001))
        y_distance=(int(1))
        y_step=y_direction*y_distance
martineau
  • 119,623
  • 25
  • 170
  • 301
Dave
  • 7
  • 1
    Isn't a random walk associated with random? – meow Jan 07 '18 at 18:20
  • 3
    There is an infinite number of numbers between `-1` and `1`. Constrained to floating point numbers: there is a *very, very large* number of numbers between `-1` and `1`. Do you really need all of them? – Jongware Jan 07 '18 at 18:21
  • 1
    What do you mean by "all numbers between -1 and 1"? If mean integer, it is zero, if it is not integer, then it is not a finite set of numbers. – Mr. T Jan 07 '18 at 18:22
  • why do you need a range of numbers between `-1` and `1` for a random walk? – nog642 Jan 07 '18 at 18:24
  • 4
    Use [`random.uniform(-1, 1)`](https://docs.python.org/3/library/random.html#random.uniform) – Patrick Haugh Jan 07 '18 at 18:37
  • the documentation on `np.arange` tells you `When using a non-integer step, such as 0.1, the results will often not be consistent. It is better to use linspace for these cases.`(https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.arange.html) - surely a thing to be useful for random steps without bias introduced by `np.arrange()`. `random.random()*2-1` would give you values you need without creating huge numbers of numbers beforehand - not sure how its optimized unter the hood. - nevermind @PatrickHaugh `random.uniform(-1,1)` is even nicer... – Patrick Artner Jan 07 '18 at 18:42

1 Answers1

0

Well, since you asked for "a better solution": the random walks do not have to be simulated (even though this might be cool). You can get the matlab code of the original publication on Leo Gradys website, this might helt implementing something similar in python.

If you just want the random numbers, I'd refer to the comment of Patrick Haugh and use random.uniform(-1, 1).

OBu
  • 4,977
  • 3
  • 29
  • 45