Generating Values Of Pi To A Specified Number Of Decimal Places
A step-by-step approach to writing the Chudnovsky algorithm in python codes
This article will explain how to write an algorithm that will generate the values of π to a specified number of decimals using the Chudnovsky algorithm in python.
The Chudnovsky algorithm was published by the Chudnovsky brothers in 1988 as a fast method for calculating the digits of π, based on Ramanujan’s π formulae.
Here is a web application that generates π to a number of decimal places you specify and is based on the codes of this very article.
Click here to know more about the Chudnovsky algorithm as this article will go straight into translating the algorithm to python codes.
Importing libraries
Import the needed libraries to be able to write the algorithm. Decimal will be required to perform the surd of large numbers and get a highly accurate decimal value of any mathematical operation, math will be needed to perform advanced mathematical functions.
import decimal
import math
Python has a default pi value and we can display this with this code
print(math.pi)
>>> 3.141592653589793
This value of π has a maximum default of 15 decimal places.
Writing Chudnovsky algorithm in python codes
The Chudnovsky algorithm can be written in codes as follows;
Refer to the function using the following codes and input the number of decimals when prompted
n = int(input("Please type number: "))
print(compute_pi(n))
Saving the generated digits to a text file on your local machine
Create a text file in the present directory and save the generated π digits using the following code;
with open("pi_digits.txt", mode='w') as file:
file.write('Pi digits to ' + str(n) +' decimal place is:'\
+'\n' + compute(n))
Find the pi_digits.txt file in the machine to view the saved file.
Execution time
It should be noted that the execution time of this code differs from system to system due to their spec. Higher-level programming languages are also slower when compared to lower-level programming languages.
This program used approximately 36.4 s to generate 10000 decimal digits of π on my machine.
Output:
Pi digits to 10000 decimal place is:
3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534...........................................................................................................................944070469120914093870012645600162374288021092764579310657922955249887275846101264836999892256959688159205600101655256375678
This program can be used to generate as many decimal digits of π as possible.