Calculation of-python and R language by Monte Carlo method

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.