Skip to content

Instantly share code, notes, and snippets.

@tnishimura
Created May 25, 2015 04:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tnishimura/f8b0a670e731c3cee49e to your computer and use it in GitHub Desktop.
Save tnishimura/f8b0a670e731c3cee49e to your computer and use it in GitHub Desktop.
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