# A Random Walk & Monte Carlo Simulation || Python Tutorial || Learn Python Programming

**Views:**258870|**Rating:4.91| View Time:7:54Minutes|Likes:6818|Dislikes:127**

A random walk is a process where each step is chosen randomly. This technique has many applications. In this video we solve a random walk puzzle using Monte Carlo simulations and the random module in Python.

➢➢➢➢➢➢➢➢➢➢

To learn Python, you can watch our playlist from the beginning:

➢➢➢➢➢➢➢➢➢➢

We recommend:

Python Cookbook, Third edition from O’Reilly

The Mythical Man Month – Essays on Software Engineering & Project Management

Shop Amazon Used Textbooks – Save up to 90%

➢➢➢➢➢➢➢➢➢➢

Subscribe to Socratica:

To support more videos from Socratica, visit

Socratica Patreon

Socratica Paypal

We also accept Bitcoin! 🙂

Our address is: 1EttYyGwJmpy9bLY2UcmEqMJuBfaZ1HdG9

➢➢➢➢➢➢➢➢➢➢

Python instructor: Ulka Simone Mohanty

Written & Produced by Michael Harrison

FX by Andriy Kostyuk

variety is the spice of life and walking is good exercise if you combine these two things you get a random walk as the name suggests and a random walk your directions chosen at random each step along the way today we will use Python to solve a random walk puzzles using Monte Carlo simulations this concludes my gamble on will preamble suppose you live in a city where the streets are arranged in a perfect grid you decide to go for a walk at each intersection you choose your next direction random your four choices are north south east or west and backtracking is permitted once you're finished with your wallet you check to see how far away you are from where you began if you are more than four blocks away you will pay for a transport back home otherwise it will just plop what is the longest random walk you can take so that on average you will end up four blocks of viewers from home we will begin by writing a function to simulate a random walk of n blocks we will write this function twice the first version will be clear simple and straightforward in the second version we will use some Python shortcuts to cut the length of the function in half to begin import the random module we will call our function random walk and the input n will be the number of blocks to walk write a short doc string describing the purpose of this function your position in the grid will have an x and y coordinate initially x equals 0 and y equals 0 we will now take the random walk to do this we will use a for loop with n steps to pick a random step we will use the choice function we will choose from a list of the four possible directions north south east or west if the random step is north then increase the y-coordinate by one if itself decrease the y-coordinate by one if it's east increase the x coordinate and now the only remaining alternative is whisk so for the final else block decrease the x-coordinate by one at this point the walk is over so we return the coordinates of the tuple to test this function let's take 25 random walks each 10 blocks long for each walk we will display the coordinates and the distance from home the distance from home is the sum of the absolute values of the x and y coordinates this is because the sign is for directions not distance for example suppose you ended up at x equals negative 10 or x equals 10 in both cases you are 10 blocks from home the sign only indicates if you are east or west from your starting position now run everything looks to be in order before solving the puzzle let's write a second version of this function that is more compact we will call this function random walk 2 we will perform our cell and programmers duty and write a docstring as before let's initialize x and y in python this can be done in one line this assigns the first zero to X and the second zero to Y once more we will use a for loop to simulate the n blocks previously we randomly chose a letter and then use the letter to update the x and y coordinates this time we will randomly choose a pair of numbers DX and dy which will contain the values we will add or subtract from x and y we use DX and dy as abbreviations for difference in X and difference in Y now we randomly choose a direction if north is chosen the x-coordinate does not change but the y-coordinate increases by one if South is chosen X is again unchanged and Y decreases by one for east x increases by one and Y is unchanged and finally for West we subtract one from X and leave Y unchanged we now use DX and dy to update X&Y x plus equals DX is shorthand for x equals x plus DX we update Y the same way and finally return x & y let's now test this function to see if it behaves as expected like before we will take 25 random walks each walk will be for ten blocks and we will print the final coordinates along with the distance from home run no errors and no surprises let's now return to the original puzzle what's the longest random walk you can take so that on average you will end up four blocks or fewer from home in other words there is less than a 50% chance you'll pay for transport home this can be solved mathematically but instead we will use the Monte Carlo method this technique is named after the city of Monte Carlos a gambling town on the Mediterranean Sea you will never find a more wretched hive of scum and villainy here instead of solving the problem mathematically we will conduct thousands of random trials and compute the percentage of random walks that end in a short walk home to get an accurate number we will take 10,000 random walks for each walk size let's estimate the probability you will walk home for walks of length 1 to 30 blocks don't forget the range function stops before the final number let's create a counter called no transport to keep track of the number of random walks at end for blocks or fewer from home let's now begin our Monte Carlo loop of 10,000 samples first get a random walk of length walk length next compute the distance from home if the distance is less than or equal to 4 increment the no transport counter we can now compute the percent of random walk that ended with a walk home it's just the fraction of the 10,000 random walks which required no transport and finally print out the results for this walk size run fascinating the longest walk with a greater than fifty percent chance of walking home is a walk of size 22 blocks let's run this simulation one more time and to increase our confidence let's use 20,000 random walks to estimate the probability there you have it we get the same answer by the way your numbers will be slightly different from beads that's because Monte Carlo methods use random samples and different simulations should give slightly different results observe that walks with an even number of blocks leave you closer to home that walks one block shorter in general even walk them closer to home than odd walk I encourage you to discuss and analyze this phenomenon in the comments below random walks are a fascinating subject they are used to model many different problems from the motion of molecules in a fluid to the movements of stuff markings as a challenge try to find the longest random walk which will on average we do less than five blocks from home and as a courtesy please consider subscribing to Socratic ax the more support we have the less random our relief schedule will be

Hmm, the talking while programming had such great timing.

eh?

How much is the chance you can learn so much in any 10-min-long video from Youtube? 100% if you just watch Socratica's channel.

Matrix kind of woman hat's off to your tutorial

for me it just shows

Walk size = 1 / % of no transport = 0.01

30 times

:

Some of the comments say, "Gamble amble preamble," but I hear, "Gambol on the preamble". Which is right?

Socratica, you're amazing. Just believe in that. You've been a great source of knowledge to many I included.

Sorry why is the upper limit 31 blocks?

I have a customer in Monte Carlo.

Every time I leave the highway and see the city from above I think «You will never find a more wretched hive of scum» like you say in 5:05

"Monte Carlo: A sunny place for shady people". – Somerset Maugham

Awesome!!. Thanks.

I don't understand what she did. But the video seemed professional.

Artistic work . … great teaching thanks

10 is the longest walk.

I want her voice on my maps aplication

Really nice and useful.You are my favourite robot now .

I can tell by watching the gamble amble preamble that Socratica is human. The vein on her forearm fills slowly while she delivers her intro. AI doesn't have veins.

She is the the Iron Lady!

Better than alexa or siri

do you apply: np.random.seet(1) ???

why is this so edgy

The micro-country of Monaco is the safest place in Europe, not a haven of scum and villainy.

CUTE!!!

I can't believe that I am watching this. I just finished a class using Monte carlo. I am a bone fide nerd.

This actress rocks. Hilarious script, great job keeping a straight face.

Skynet Lady told me to subscribe :O

Suberb explanation.

Can you make a full course on Machine Learning and AI from scratch, to advanced with few project, so that a lot of other people will benefited from it. There are also some other video on the said above, but your video is stand alone. I really appreciate you for doing hard work for us. Thank You.

glad that I found this.

What makes a simulation "Monte Carlo" be just a regular simulation. I thought MC would be more involved but send pretty straight forward. Thanks

Walk size of 5 or less:

Walk size = 31 / % of no transport= 51.854

Anyone else get this rough answer too?

fall in love just after seeing this video…

Am I in love with… a machine?

Gggg

Doesn't this have to do with e since it's a distribution of data with random?

xD

Gamble amble preamble… you have officially made my day.

Holy shit!! this is genius!!!

5:30, so the choice of walk_length in range 1 to 31 is randomly chosen? what happens if you increase the max walk length, does it change the outcome at all?