Let's find pi in Python

If you just want to use pi

import math
print(math.py)

That's fine, but I'd like to see how I'm looking for 3.14. Therefore, I would like to find the pi with a stochastic model.

Dot the appropriate place in the first quadrant

First, set a random number from 0 to 1 for each of the x and y coordinates and hit a point.

import random
x, y = random.random(), random.random()

Check if x ^ 2 + y ^ 2 is within 1

If the number of squares of x and y and the sum of them is less than 1, the point is inside a circle with a radius of 1.

number = x ** 2 + y ** 2 #Inside the circle if this is within 1

See the approximate value over and over again

Repeat this many times, and if the number of repetitions is the denominator and the number of times within 1 x 4 (assuming that the same result is obtained in all quadrants) is the numerator, the pi is calculated. Let's try it about 1000 times.

import random

incount = 0

def GenerateRandom():
  x, y = random.random(), random.random()
  number = x ** 2 + y ** 2
  return number

iteration = 1000

for ite in range(iteration):
  check = GenerateRandom()
  if (check < 1):
    incount += 1

quadrant = 4 #All quadrants

print(incount * quadrant / iteration)
3.2

Well, it's subtle. It seems that the number was small, so let's try it 10 million times.

#It takes about 5 seconds
3.141382

Is it good?

Try to visualize

I wasn't really impressed when the numbers came out, so let's visualize it with matplotlib.

First 1000 times version

import random
import matplotlib.pyplot as plt

def GenerateRandom():
  x, y = random.random(), random.random()
  number = x ** 2 + y ** 2
  return [number, x, y]

iteration = 1000

for ite in range(iteration):
  check = GenerateRandom()
  if (check[0] < 1):
    plt.scatter(check[1], check[2], c = 'red', s = 10)
  else:
    plt.scatter(check[1], check[2], c='blue', s = 10)

plt.title('Monte Carlo Method')
plt.xlabel("x")
plt.ylabel("y")
plt.show()

Wait about 10 seconds ...

スクリーンショット 2020-08-17 13.46.37.png

It's not easy to understand, so let's try the version 10 million times.

import random
import matplotlib.pyplot as plt

def GenerateRandom():
  x, y = random.random(), random.random()
  number = x ** 2 + y ** 2
  return [number, x, y]

iteration = 10000000

for ite in range(iteration):
  check = GenerateRandom()
  if (check[0] < 1):
    plt.scatter(check[1], check[2], c = 'red', s = 10)
  else:
    plt.scatter(check[1], check[2], c='blue', s = 10)

plt.title('Monte Carlo Method')
plt.xlabel("x")
plt.ylabel("y")
plt.show()

Once you've done this, take a walk away from your computer. By the time you come back, the process should be finished.

スクリーンショット 2020-08-17 13.47.54.png

It is easier to understand if the graph is made square, but you can see that it is distributed in a beautiful arc.


Calculating this doesn't mean anything is born, but if you're interested, I'd appreciate it if you could give it a try.

reference

Information Processing Society of Japan

Recommended Posts

Let's find pi in Python
List find in Python
Find the difference in Python
Find permutations / combinations in Python
Let's run "python -m antigravity" in python
Let's try Fizz Buzz in Python
Let's see using input in python
Quadtree in Python --2
Python in optimization
CURL in python
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
Find files like find on linux in Python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Find and check inverse matrix in Python
FizzBuzz in Python
Find (deterministic finite) Cartesian automata in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Reflection in Python
Constant in python
Let's make a combination calculation in Python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
#Monte Carlo method to find pi using Python
Let's parse the git commit log in Python!
Let's find "T" in your work with us! !! !!
Minimal implementation to do Union Find in Python
Let's judge emotions using Emotion API in Python
Find the divisor of the value entered in python
Find prime numbers in Python as short as possible
Let's make some notification processing samples in Python
Find the solution of the nth-order equation in python
[Python] Find the transposed matrix in a comprehension
python xlwings: Find the cell in the last row