#Monte Carlo method to find pi using Python

at first

In this article This is an article that explains the program to find the pi using the Monte Carlo method written in the midnight tension as it is by watching Lambda's Video. Don't expect too much because it's midnight tension!

The code is terrible

import matplotlib.pyplot as plt
import random

Xlist=[]
Ylist=[]
Number_list=[]
pi=0
pi_list=[]

for i in range(15000):
    Xlist.append(random.uniform(0,1))
    Ylist.append(random.uniform(0,1))
    if (i+1)%10 == 0:
        Number_list.append(i+1)
        pi_list.append((pi/(i+1))*4)
    if Xlist[i]**2+Ylist[i]**2 <= 1 and (i+1)%10 == 0:
        Number_list.append(i+1)
        pi_list.append((pi/(i+1))*4)
        pi+=1
    elif Xlist[i]**2+Ylist[i]**2 <= 1:
        pi+=1

print((pi/(i+1))*4)
plt.plot(Number_list,pi_list)
plt.show()

1.png What this is not dirty It works, but the same process is written many times and it's awkward, so I rewrote it in the morning.

import matplotlib.pyplot as plt
import random

Xlist=[]
Ylist=[]
Number_list=[]
pi=0
pi_list=[]

for i in range(15000):
    Xlist.append(random.uniform(0,1))
    Ylist.append(random.uniform(0,1))
    if (i+1)%10 == 0:
        Number_list.append(i+1)
        pi_list.append((pi/(i+1))*4)
    if Xlist[i]**2+Ylist[i]**2 <= 1:
        pi+=1

print((pi/(i+1))*4)
plt.plot(Number_list,pi_list)
plt.show()

It's a little better. Let's explain the code line by line.

import matplotlib.pyplot as plt
import random

In the first line, a library called ** matplotlib **, which is convenient for drawing graphs, is available under the name ** plt **. The second line imports a library that can generate a random value called ** random **.

Xlist=[]
Ylist=[]
Number_list=[]
pi=0
pi_list=[]

Here, the variables necessary for calculating various pis are declared. The coordinates of randomly generated points are stored in ** Xlist and Ylist **, and it is determined whether or not the points are inside the circle in a later calculation. ** Number_list ** creates the arithmetic progression required for graph creation. Actually, it is faster to make arithmetic progression first using numpy, but this time it was troublesome to find out the method, so I passed it (Saborima). ** pi ** is used to save the total number of points plotted inside the circle, and ** pi_list ** is used to save the calculated pi in list format.

for i in range(15000):
    Xlist.append(random.uniform(0,1))
    Ylist.append(random.uniform(0,1))
    if (i+1)%10 == 0:
        Number_list.append(i+1)
        pi_list.append((pi/(i+1))*4)
    if Xlist[i]**2+Ylist[i]**2 <= 1:
        pi+=1

Here, the for statement is used to repeat the following process 15,000 times (humans will die). Use the ramdom module to store the coordinates of points in ** Xlist and Ylist **. For convenience of explanation, I will explain the block of ** if Xlist [i] ** 2 + Ylist [i] ** 2 <= 1: **. I won't explain the annoying explanation here, x^2+y^2=r^2 For the time being, if the numbers stored at the end of Xlist and Ylist are squared and added, and the radius is less than the square, you can see that there is a point in the circle. The above if statement expresses this as a mathematical formula. Since this if statement shows that the point is inside the circle, add 1 to pi. Finally, about the block of ** if (i + 1)% 10 == 0: **. Here, the pi is calculated once every ten times and stored in pi_list, and then the number is added to make Number_list an arithmetic progression.

plt.plot(Number_list,pi_list) plt.show() This is a program that only creates graphs, so I will not explain it (cut out).

At the end

I don't think you need it, but I made it PDF and summarized the contents of this time. The program history is surprisingly short, so feel free to let us know in the comments if you make a mistake! !! Please leave a comment if you like.

Recommended Posts

#Monte Carlo method to find pi using Python
Simulate Monte Carlo method in Python
Sprinkle rice grains to find the circumference (Monte Carlo method)
Finding pi with a three-line function [Python / Monte Carlo method]
Monte Carlo method
Try implementing the Monte Carlo method in Python
Calculation of the shortest path using the Monte Carlo method
Output to "7-segment LED" using python on Raspberry Pi 3!
Post to Twitter using Python
Start to Selenium using python
Let's find pi in Python
How to install python using anaconda
Estimating π by Monte Carlo method
python beginners tried to find out
[Raspberry Pi] Changed Python default to Python3
(Python) Expected value ・ I tried to understand Monte Carlo sampling carefully
Find the ratio of the area of Lake Biwa by the Monte Carlo method
From Python to using MeCab (and CaboCha)
Method to build Python environment in Xcode 6
[Introduction to Udemy Python3 + Application] 25. Dictionary-type method
Introduction to Discrete Event Simulation Using Python # 1
[Introduction to Udemy Python3 + Application] 13. Character method
Detect "brightness" using python on Raspberry Pi 3!
Log in to Slack using requests in Python
Try to operate Excel using Python (Xlwings)
Run servomotor on Raspberry Pi 3 using python
Dump BigQuery tables to GCS using Python
Introduction to Discrete Event Simulation Using Python # 2
Detect temperature using python on Raspberry Pi 3!
[Introduction to Udemy Python3 + Application] 29. Set method
[Circuit x Python] How to find the transfer function of a circuit using Lcapy
Dominion compression play analyzed by Monte Carlo method
Procedure to use TeamGant's WEB API (using python)
Detect slide switches using python on Raspberry Pi 3!
Introducing 4 ways to monitor Python applications using Prometheus
How to use Raspberry Pi pie camera Python
I want to email from Gmail using Python.
I tried to find 100 million digits of pi
Minimal implementation to do Union Find in Python
To dynamically replace the next method in python
Detect magnet switches using python on Raspberry Pi 3!
PRML Chapter 11 Markov Chain Monte Carlo Python Implementation
Sound the buzzer using python on Raspberry Pi 3!
Convert STL to Voxel mesh using Python VTK
Find the geometric mean of n! Using Python
[Introduction to Algorithm] Find the shortest path [Python3]
Connect your Raspberry Pi to your smartphone using Blynk
Connect to MySQL with Python on Raspberry Pi
Start using Python
Scraping using Python
Johnson method (python)
[Python] Semi-Lagrange method
"Backport" to python 2
The first Markov chain Monte Carlo method by PyStan
From setting up Raspberry Pi to installing Python environment
[python] Method to darken RGB value in hexadecimal notation
How to set up a Python environment using pyenv
Speed comparison of each language by Monte Carlo method
(Python) Try to develop a web application using Django
How to auto-submit Microsoft Forms using python (Mac version)
Push notifications from Python to Android using Google's API