Python random generator not so random?
Question: Is the python random generator considered "good"? As in, does it simulate
randomness very well? I made a small program which simulates a person starting
at (0, 0) and taking a random step either east, west, north and south. As you
run simulations with larger and larger number of steps, you would expect the
final position of the person to be closer and closer to the origin. However,
as I increased the number of steps in my simulation, the final position was
getting farther and farther away from the origin. The program I used is here:

    
    
    import random
    
    def walk():
        north = 0
        east = 0
        for i in range(10000):
            direction = random.randint(0, 100)
        if direction <= 25:
            north = north + 1
        elif direction > 25 and direction <= 50:
            north = north - 1
        elif direction > 50 and direction <= 75:
            east = east + 1
        else:
            east = east - 1
    return north, east
    
    
    
    def main():
        for i in range(500):
            north, east = walk()
            print("NE : ", north, east)
    
    
    main()        
    


Answer: > As you run simulations with larger and larger number of steps, you would
> expect the final position of the person to be closer and closer to the
> origin.

This simply is not true. Imagine you start at (0,0). You take one step east,
taking you to (1,0). Now, in order to get closer to the origin, you need to
take a step west. Taking a step in any other direction will take you further
from the origin. So, you have a 1/4 chance of going closer to the origin and a
3/4 chance of going further away from the origin. This is true no matter where
you are; more often than not, a step will take you further from the origin.
Thus, your simulation is behaving as expected; the longer you go, the further
from the origin you get.

* * *

To see why this is true; consider a one-dimensional walk, where you can step
left or right. If you take ten steps, the expected value is 50:50 left and
right; 5 left and 5 right, taking you back to the origin. Of course, you might
end up with 60:40 or 70:30, leaving you one or two steps away from the origin.
It is a small sample size, after all. If you take 1000 steps, you might end up
with something like 520 left to 480 right, pretty close to that 50:50 ratio.
If you take 10000 steps, you'll be even closer to the 50:50 ratio, perhaps
with something like 5050:4950.

However, there is something very important to note; as your sample size gets
larger, the _proportion_ of left to right steps is closer to 50:50, but the
absolute _difference_ in number between left and right steps gets _larger_. In
that last case, you have a 50.5:49.5 ratio, but you're _fifty_ steps away from
the origin, compared to your one step away from the origin in the case where
you have a 60:40 ratio with ten steps.

