Home > Backend Development > Python Tutorial > How to enter π in python

How to enter π in python

爱喝马黛茶的安东尼
Release: 2019-10-25 17:57:18
Original
42184 people have browsed it

How to enter π in python

π in python is the math.pi variable. It is included in the standard library, and before you try to calculate it yourself, you should first import the math library and call the math.pi method.

Related recommendations: "Python Basic Tutorial"

Let us look at a very straightforward method of calculating Pi. Taking Python 2.7 as an example, the code is as follows:

import sys
import math
  
defmain(argv):  
    if len(argv) !=1:
        sys.exit(&#39;Usage: calc_pi.py <n>&#39;)  
    print&#39;\nComputing Pi v.01\n&#39;
      
    a=1.0
    b=1.0/math.sqrt(2)
    t=1.0/4.0
    p=1.0
          
    for i in range(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:])
Copy after login

The above is the detailed content of How to enter π in 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