[PYTHON] I tried to estimate the pi stochastically

It is a story that I tried to estimate the pi stochastically (strictly speaking, Monte Carlo method) using Python's standard library random. (Expected reading time: 4 minutes)

Way of thinking

Imagine the xy coordinates. pi1.png

Draw a circle with radius r (let's call it C) centered on the origin O and a square with a side of 2r (let's call it S). pi2.png

Randomly keep hitting dots in S. pi3.png

When you hit enough points to fill the inside of S, you can say "the number of points in S: the number of points in C ≒ the area of S: the area of C". pi4.png

If the number of points in S is "s_dot_num" and the number of points in C is "c_dot_num",

(c_dot_num) / (s_dot_num) = Area of C / Area of S = (π * r squared) / (2r) squared  = π / 4

Because it becomes

π = 4 * (c_dot_num) / (s_dot_num)

I was able to define. After that, if you can find c_dot_num and s_dot_num respectively, you can estimate the value of π. (The value of r doesn't seem to matter)

code

This time I wrote it in Python.

estimate_pi.py


#Dots are randomly placed in a square with a side length of 1 to estimate the pi.
import random

def estimate_pi(n):
    c_dot_num = 0
    s_dot_num = 0
    for _ in range(n):
        x = random.uniform(0, 1)
        y = random.uniform(0, 1)
        distance = x**2 + y**2
        if distance <= 1:
            c_dot_num += 1
        s_dot_num += 1
    pi = 4 * c_dot_num / s_dot_num
    return pi

if __name__ == '__main__':
    print('When there are 100 dots, the pi is{}'.format(estimate_pi(100)))
    print('When there are 1000 dots, the pi is{}'.format(estimate_pi(1000)))
    print('When there are 10000 dots, the pi is{}'.format(estimate_pi(10000)))
    print('When there are 100000 dots, the pi is{}'.format(estimate_pi(100000)))

※image pi5.png

Execution result

First time r1.png Second time r2.png Third time r3.png

It is about 3.141. As the number of trials n (= the number of times to hit the dot) is increased, the accuracy increases.

Summary

This time, I tried to estimate the pi using random numbers. Academically, the method of estimating some value using random numbers is called the "Monte Carlo method".

The code itself is not difficult at all, but when I first learned about it, I was excited to say, "Is there such an approach!", So as a memorandum.

Recommended Posts

I tried to estimate the pi stochastically
I tried to estimate the interval.
I tried to move the ball
I tried to summarize the umask command
I tried to recognize the wake word
I tried to summarize the graphical modeling.
I tried to touch the COTOHA API
I tried to paste
I tried web scraping to analyze the lyrics.
I tried to optimize while drying the laundry
I tried to save the data with discord
I tried to find 100 million digits of pi
I tried to touch the API of ebay
Qiita Job I tried to analyze the job offer
LeetCode I tried to summarize the simple ones
I tried to implement the traveling salesman problem
I tried to predict the price of ETF
I tried to vectorize the lyrics of Hinatazaka46!
I tried to estimate the similarity of the question intent using gensim's Doc2Vec
(Python) I tried to analyze 1 million hands ~ I tried to estimate the number of AA ~
I tried to learn the sin function with chainer
I tried to graph the packages installed in Python
I tried to learn PredNet
I tried to detect the iris from the camera image
I tried to summarize the basic form of GPLVM
I tried to touch the CSV file with Python
I tried to predict the J-League match (data analysis)
I tried to organize SVM.
I talked to Raspberry Pi
I tried to implement PCANet
I tried to approximate the sin function using chainer
I tried the changefinder library!
I tried to put pytest into the actual battle
[Python] I tried to graph the top 10 eyeshadow rankings
I tried to reintroduce Linux
I tried to visualize the spacha information of VTuber
I tried to introduce Pylint
I tried to erase the negative part of Meros
I tried to solve the problem with Python Vol.1
I tried to summarize SparseMatrix
I tried to simulate the dollar cost averaging method
I tried to redo the non-negative matrix factorization (NMF)
I tried to touch jupyter
I tried to implement StarGAN (1)
I tried to identify the language using CNN + Melspectogram
I tried to notify the honeypot report on LINE
I tried to complement the knowledge graph using OpenKE
I tried to classify the voices of voice actors
I tried to compress the image using machine learning
I tried to summarize the string operations of Python
When I tried to do socket communication with Raspberry Pi, the protocol was different
I tried to find the entropy of the image with python
I tried to find out the outline about Big Gorilla
I tried to introduce the block diagram generation tool blockdiag
I tried porting the code written for TensorFlow to Theano
[Horse Racing] I tried to quantify the strength of racehorses
I tried to simulate how the infection spreads with Python
I tried to get the location information of Odakyu Bus
I tried to find the average of the sequence with TensorFlow
I tried to notify the train delay information with LINE Notify
I tried to summarize the code often used in Pandas