In order to learn the basics of Monte Carlo I calculated pi with it. I also wrote an explanation of the reasoning behind the code.
Down here you can see the circle with random points that I simulated in my code.
""" This programme calculates pi with Monte Carlo Given a square and a circle inside it. We have Area_of_the_square = LENGTH ** 2 Area_of_the_circle = radius ** 2 * pi => (LENGTH ** 2) / 4 * pi The circle is obviously smaller than the square. We have the equation: Area_of_the_square * number_less_than_one == Area_of_the_circle This programme is going to put a big number of points inside the square (I suggest TIMES_TO_REPEAT = 10**5). It will then count how many of them are inside the circle, number_less_than_one = points_inside_the_circle / total_points After doing some simple math with this formula: Area_of_the_square * number_less_than_one == Area_of_the_circle we get that pi = number_less_than_one * 4 NOTE: This method is deadly slow and quite complicated, I made this programme just in order to learn. """ import random TIMES_TO_REPEAT = 10**5 LENGTH = 10**5 CENTER = [LENGTH/2,LENGTH/2] def in_circle(point): x = point y = point center_x = CENTER center_y = CENTER radius = LENGTH/2 return (x - center_x)**2 + (y - center_y)**2 < radius**2 count = inside_count = 0 for i in range(TIMES_TO_REPEAT): point = random.randint(1,LENGTH),random.randint(1,LENGTH) if in_circle(point): inside_count += 1 count += 1 pi = (inside_count / count) * 4 print(pi)