Home >Backend Development >Python Tutorial >How to call pi in python
pi is π, a truly magical number followed by countless people. I'm not quite sure what's so fascinating about an irrational number that repeats itself forever.
In my opinion, I am happy to calculate π, that is, to calculate the value of π. Because π is an irrational number, it is infinite. (Recommended learning: Python video tutorial)
This means that any calculation of π is only an approximation. If you calculate 100 digits, I can calculate 101 digits and be more precise. So far, some have singled out supercomputers to try to calculate the most accurate π. Some extreme values include calculating 500 million digits of pi. You can even find a text file online containing 10 billion digits of π (be careful! This file may take a while to download, and it won't open with your usual Notepad application.). For me, how to calculate π with a few lines of simple Python is what interests me.
π in python is the math.pi variable. It is included in the standard library, and you should import the math library before trying to calculate it yourself.
Let's look at a very straightforward method of calculating Pi. As usual, I'll be using Python 2.7, the same ideas and code may apply to different versions. Most of the algorithms we will use are taken from and implemented on the Pi WikiPedia page. Let's take a look at the following code:
import sys import math defmain(argv): iflen(argv) !=1: sys.exit('Usage: calc_pi.py <n>') print'\nComputing Pi v.01\n' a=1.0 b=1.0/math.sqrt(2) t=1.0/4.0 p=1.0 foriinrange(int(sys.argv[1])): at=(a+b)/2 bt=math.sqrt(a*b) tt=t-p*(a-at)**2 pt=2*p a=at;b=bt;t=tt;p=pt my_pi=(a+b)**2/(4*t) accuracy=100*(math.pi-my_pi)/my_pi print"Pi is approximately: "+str(my_pi) print"Accuracy with math.pi: "+str(accuracy) if__name__=="__main__": main(sys.argv[1:])
This is a very simple script that you can download, run, modify, and share with others as you like.
For more Python related technical articles, please visit the Python Tutorial column to learn!
The above is the detailed content of How to call pi in python. For more information, please follow other related articles on the PHP Chinese website!