The Python Game Book

code games. learn Python.

User Tools

Site Tools


Sidebar

Github:

en:glossary:p:pi

Pi

you get an very good value of πPi by importing the math module.

import math
radius = input("Please enter the radius of a circle:")
circumference = 2 * radius * math.pi
area = radius * radius * math.pi
print "pi is %.8f" % math.pi # trimmed to 8 digits 
print "Circumference of circle with radius %.2f is %.4f ( 2 * r * pi)" % (radius, circumference)
print "Area of circle with radius %.2f is %.4f ( r * r * pi)" % (radius, area)

You can also calculate pi without the math module by using this script to calculate pi with the help of a Mandelbrot set

def pi(err, abs=abs):
    'Approximation of pi +/- err using the Mandelbrot set'
    n = 0
    z = c = complex(-0.75, err)
    while abs(z) < 2.0:
            n += 1
            z = z * z + c
    return n * err

if __name__ == '__main__':
    for i in range(1, 8):
        err_bound = 10 ** (-i)
        print(pi(err_bound), 'within', err_bound)
sources:

en/glossary/p/pi.txt · Last modified: 2020/05/13 06:58 by horst