Created
May 25, 2015 04:26
-
-
Save tnishimura/f8b0a670e731c3cee49e 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
import sys | |
import math | |
import fractions | |
def pi_fraction(gap): | |
"""Print the fraction within gap of pi that has the smallest denominator. | |
>>> pi_fraction(0.01) | |
22 / 7 = 3.142857142857143 | |
>>> pi_fraction(1) | |
3 / 1 = 3.0 | |
>>> pi_fraction(1.0/8) | |
13 / 4 = 3.25 | |
>>> pi_fraction(1e-6) | |
355 / 113 = 3.1415929203539825 | |
""" | |
denominator = 1 | |
numerator = 1 | |
while True: | |
while float(numerator)/denominator < math.pi + gap: | |
if abs(float(numerator)/denominator - math.pi) < gap: | |
print "%d / %d = %f" % (numerator, denominator, float(numerator)/denominator) | |
return | |
numerator += 1 | |
denominator += 1 | |
numerator = denominator * 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment