How to calculate pi using python?
How to calculate pi in python:
There is no precise calculation formula for pi, so its approximate value can only be calculated in an approximate way.
We use the Monte Carlo method. The idea is very simple. Randomly throw a large number of points in the graph below and calculate the number of points falling within the 1/4 circle.
In order to get the pi value, based on the idea, we know that we need to reference the random, math and time databases. The specific code is as follows:
# pi.py from random import random from math import sqrt from time import clock DARTS = 1200 hits = 0 clock() if dist <= 1.0: hits = hits + 1 pi = 4 * (hits/DARTS) print("Pi的值是 %s" % pi) print("程序运行时间是 %-5.5ss" % clock())
Recommended tutorial: "python》
The above is the detailed content of How to calculate pi using python?. For more information, please follow other related articles on the PHP Chinese website!