# -*- coding: utf-8 -*- """ Created on Sat Dec 12 19:03:48 2020 @author: neil """ # calculating pi, # To illustrate basic python loops, # The greeks used inscribed and circumscribed polygons to estimate pi to a couple of decimal places # With the computer, we can approximate pi by inscribing ever increasing polygons # (the greeks had difficulty with the sheer number of calculations, we let the computer do it) # the key, as Archimedes realized, was that using Pythagoras's theorm, he derived a recursive # formula for the side length of a regular polygon, based on the side length of a n/2 polygon: # Sn = sqrt( 1/2 - sqrt( (1/2)**2 - (Sm/2)**2 ) ) # where Sn is the side length of an n-sided polygon, and Sm is the side length of an (n/2) polygon # this is a messy formula, which meant the greeks couldn't get much accuracy calculating by hand # below we use this formula (slighly rearranged to reduce subtraction errors) # import extra 'modules', this is typical if you want to do anything fancy # we don't need it much here, but we will import 'numpy' as our basic fancy math resource import numpy as np # the initial part of any program usually is where you put any variables etc, that # need to be set, or are likely to be changed by the user # since we are going to iterate to find pi, set a max number of iterations maxiter = 30 # start with an inscribed square (a 4-gon), since we know the edge length si = np.sqrt(2) # side of a inscribed square (si = n-gon) inside a radius 1 circle print("n-gon: {0:10d} - {1:1.18f}".format(4,2*si) ) for n in range(1,maxiter): # t = (si/2)**2 # si here is the old side length si = ( np.sqrt( ((1-np.sqrt(1-t))**2 + t) ) ) # si is the new side length print("n-gon: {0:10d} - {1:1.18f}".format(4*2**n,si*2**(n+1)) ) # multi by number of sides, 2**(n+1) # to get total circumference # An interesting point is that tiny erros acumulate, resulting in errors at the # 15 decimal place pie = np.pi # get an accurate (to at least 15 places) value for pi print("Pythons default pi {0:1.18f}".format(pie) ) # the numpy module has its own accurate value for pi # major side note, python's value of pi has an error in the 16th place, # this is due to storing np.pi in a single precision storage location # print("Exact value pi {0:1.18f}".format(3.141592653589793238) ) # doesn't work print("Exact value pi {0:1.15f}{1:3d}".format(3.141592653589793,238) ) # python defaults to its 'single precision' which is valid to about 14 or 15 significant # digits. If you really need more you need to import multiprecison "mpmath" module # otherwise variables are stored in containers that truncate