Last active
November 28, 2023 18:06
-
-
Save SeijiEmery/639d48fded11bcf9279a to your computer and use it in GitHub Desktop.
From-scratch PI approximation (based on Archimedes' method using inscribed regular hexagons)
This file contains hidden or 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
def approx_pi (iterations): | |
''' pi approximation based on Archimedes' geometric method (find the | |
perimeter of a regular hexagon subdivided n times, and use that | |
as an approximation to C = 2*pi*r, with r = 1.0). | |
Note: Becomes increasingly inaccurate when iterations > 15 due to | |
the limitations of Python's floating point numbers. Would have to | |
implement bignums w/ an extremely accurate sqrt fcn to get better | |
precision. | |
''' | |
d = 1.0 | |
for i in range(iterations): | |
d = (2.0 - (4.0 - d ** 2) ** 0.5) ** 0.5 | |
d *= 2.0 ** iterations | |
return 3.0 * d | |
if __name__ == '__main__': | |
from math import pi | |
print('approx: {0}'.format(approx_pi(15))) | |
print('actual: {0}'.format(pi)) | |
# Outputs: | |
# approx: 3.14159264532 | |
# actual: 3.14159265359 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment