Skip to content

Instantly share code, notes, and snippets.

@cosinekitty
Created December 28, 2019 00:57
Show Gist options
  • Save cosinekitty/f7a01ba8253f86d74ce92ebb9d03e852 to your computer and use it in GitHub Desktop.
Save cosinekitty/f7a01ba8253f86d74ce92ebb9d03e852 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
#
# machin.py - by Don Cross
#
# Test Machin's Formula: pi = 4*(4*arctan(1/5) - arctan(1/239)).
#
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 * (4*ArctanDenom(5) - ArctanDenom(239))
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