Home  >  Article  >  Backend Development  >  How to calculate pi using python?

How to calculate pi using python?

coldplay.xixi
coldplay.xixiOriginal
2020-06-10 17:55:556419browse

How to calculate pi using python?

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.

How to calculate pi using python?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn