Python Basics Advanced (iv) the math library and random libraries and instances of the Python language

Source: Internet
Author: User
Tags random seed value of pi

Tuples and lists are not saved in the process of writing, next time fill it up. It's awkward and the hands are so bad.

A computer is a deterministic device and cannot produce a true random number. (using the Seed function, the values are the same two times)

The random number generated by the computer is a pseudo-random sequence produced by the seed. The same random seed produces the same pseudo-random sequence.

Calculation of π

Pi is an irrational number, and there is no precise formula to calculate the π value, and π can only be calculated using approximate algorithms.

The internationally recognized π value calculation is based on the Monte Carlo method.

To put it simply, Monte Carlo is a method of solving problems by using random experiments.

  

The IPO of the π calculation problem is as follows:

Input: Number of throw points

Processing: For each scatter point, calculate the distance from the point to the center of the circle, judging by the distance that the point is inside or outside the round. Counts the number of points within a circle.

Output: π value

#pi.py fromRandomImportRandom fromMathImportsqrt fromTimeImportClockdarts= 1200hits=0clock () forIinchRange (1, DARTS): x, y=random (), random () Dist= sqrt (x**2 + y**2)    ifDist <= 1.0: Hits= hits + 1Pi= 4 * (hits/DARTS)Print("The value of pi is%s"%pi)Print("program run time is%-5.5SS"% Clock ())

The power of this method can be further explored.

Python Basics Advanced (iv) the math library and random libraries and instances of the Python language

Related Article

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.