Created
December 28, 2019 00:41
-
-
Save cosinekitty/9c36d685151956dda5da5f2f751ef4c7 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python3 | |
# | |
# better.py - by Don Cross | |
# | |
# Test the formula pi = 4*(arctan(1/2) + arctan(1/3)). | |
# | |
import math | |
def ArctanDenom(d): | |
# Calculates arctan(1/d) = 1/d - 1/(3*d^3) + 1/(5*d^5) - 1/(7*d^7) + ... | |
tolerance = 1.0e-20 # how small the residue needs to be before we stop iterating | |
total = term = 1.0 / d | |
n = 0 | |
while abs(term) > tolerance: | |
n += 1 | |
term /= -d*d | |
total += term / (2*n + 1) | |
print('ArctanDenom({}) = {:0.15f}; took {} iterations.'.format(d, total, n)) | |
return total | |
if __name__ == '__main__': | |
calc_pi = 4 * (ArctanDenom(2) + ArctanDenom(3)) | |
print('pi = {:0.15f}, error = {:0.4g}'.format(calc_pi, math.pi - calc_pi)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment