Created
May 8, 2018 03:23
-
-
Save cjanis/45421fb0779554ba469ecbef5ee80955 to your computer and use it in GitHub Desktop.
Calculate pi using the Nilakantha series with up to 48 decimals of precision
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
calculate pi using the Nilakantha series up to 48 decimals of precision | |
Nilakantha series approximates pi, but is not as accurate as some other, more intensive methods | |
the most accurate predictions come with odd number decimal precision | |
'' | |
def calculate_pi(decimals): | |
# make the calculation | |
pi = 0 | |
for i in range(1,decimals+1): | |
# All this weirdness is part of the Nilikantha series | |
change = 4 / ((i * 2) * ((i * 2) + 1) * ((i * 2) + 2)) | |
if (i % 2 == 0): | |
pi -= change | |
else: | |
pi += change | |
pi = pi + 3 | |
# cut answer off at required decimals | |
pi = f"%.{decimals}f" % pi | |
# print results | |
return f"\nPi calculated to {decimals} decimals of precisions is:\n{pi}\n\n\n" | |
# get required decimals of precision | |
while True: | |
# ask for decimals of precision (Nilakantha series is most accurate with odd numbers) | |
decimals = input("\nHow many decimals of precision do you need? > ") | |
# validate that it's a number | |
try: | |
int(decimals) | |
except: | |
print("Error: Please enter a whole number.") | |
continue | |
decimals = int(decimals) | |
# max out at 1000 decimal places | |
if (decimals > 48): | |
print(f"Error: {decimals} is too large. I automatically set it to 48 for you.") | |
decimals = 48 | |
# require at least 2 decimal places | |
if (decimals < 2): | |
print(f"Error: {decimals} is too small. I automatically set it to 2 for you.") | |
decimals = 2 | |
# fire up the calculator | |
print(calculate_pi(decimals)) | |
# end the while loop | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment