Home > Backend Development > Python Tutorial > How to calculate pi using python?

How to calculate pi using python?

coldplay.xixi
Release: 2020-06-10 17:55:55
Original
6622 people have browsed it

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())
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template