I know what you mean, just was doing some monte carlo modeling earlier today for the probability if someone would call a rideshare given they’re walking more than 4 blocks away from “home”.
In C that’s a few hundred lines of code.
Python…
# coding: utf-8
"""
Models a person going 'x' blocks from home and probability of a rideshare being called.
"""
from random import choice as choose
DIRECTIONS = {
"North": (0, 1),
"South": (0, -1),
"East": (1, 0),
"West": (-1, 0),
}
def rand_walk(iterations):
"""
Random walking on a grid with reverse paths allowed
"""
grid_x, grid_y = 0, 0
for _ in range(iterations):
(grid_dx, grid_dy) = choose([
DIRECTIONS['North'],
DIRECTIONS['South'],
DIRECTIONS['East'],
DIRECTIONS['West']
])
grid_x += grid_dx
grid_y += grid_dy
return (grid_x, grid_y)
def model(num_of_walks, max_blocks):
"""
Calculate model
"""
for walk_len in range(1, max_blocks):
no_transport = 0
for _ in range(num_of_walks):
(grid_x, grid_y) = rand_walk(walk_len)
distance = abs(grid_x) + abs(grid_y)
if distance <= 4:
no_transport += 1
no_transport_percentage = float(no_transport) / num_of_walks
print("Walk size = ", walk_len,
" / % of no transport = ", 100 * no_transport_percentage)
def main():
"""
Do the things
"""
for _ in range(25):
walk = rand_walk(10)
print(walk, "Distance from home = ", abs(walk[0]) + abs(walk[1]))
for walks in (100, 10000):
model(num_of_walks=walks, max_blocks=31)
if __name__ == '__main__':
main()
# vim: set sts=4 ts=4 et number list:
Less than 70 but that’s also with comments for help(), readability, and prep as an importable module (ie ready to be published via pip). Plus one can add in a quick genetic algorithm and randomizer in about another 10 lines.
The really fun part for this greybeard is the rand_walk function can be used in game development.