Using Monte Carlo method to calculate pi-based on Python and R language
Recently follow Mooc a Python class and started learning Python. At the same time, bought the probability theory and mathematical statistics, ready to self-study statistics. (because of being despised is not a statistical major but want to do data analysis)
What's interesting is that there's a piece of what in the book. Calculate pi, which is a stochastic simulation method, also known as Monte Carlo method. What the needle is too difficult for me, for a moment I did not think how to use computer simulation of the process.
In the Python class, the teacher also mentioned using the stochastic simulation method, which is Monte Carlo method (Montecarlo), simulated thousands of experiments with a computer and calculated the approximate value of pi. Good coincidence.
Take the Python class method to approximate the PI, respectively, with Python and r implementation.
As for the experiment, the teacher's ppt.
I'm using Python 3.
Python code:
From random import randomfrom math import sqrtfrom time import Clockdarts=2**22hist=0clock () for I in Range (1,darts): x , Y=random (), random () dist=sqrt (x**2+y**2) if dist<=1.0: hist=hist+1pi=4* (hist/darts) print (' pi is% S '%pi) print (' Elaspe is%ss '%clock ())
Python Run Result:
Pi is 3.143444061279297elaspe is 85.991785
R Code:
#蒙特卡洛方法求pihist <-0darts <-2^22start <-proc.time () for (I in 1:darts) { x <-runif (1); y <-runif (1)
if (sqrt (x^2+y^2) >1) next hist=hist+1}pi <-4*hist/dartsproc.time ()-startprint (Paste0 (' pi is ', pi))
R Run Result:
> proc.time ()-start user system elapsed 31.537 2.477 34.153 > Print (paste0 (' pi is ', pi)) [1] "PI is 3.14076137542725 "
Summary: R and Python are very useful, next step is to try to use Python to write a small reptile program.
Calculation of-python and R language by Monte Carlo method