Skip to content

Instantly share code, notes, and snippets.

@CTimmerman
Last active December 2, 2017 13:57
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 CTimmerman/63a52128b8aa3a94a9be661985687088 to your computer and use it in GitHub Desktop.
Save CTimmerman/63a52128b8aa3a94a9be661985687088 to your computer and use it in GitHub Desktop.
Decimals to fractions, and some other stuff i was playing with and forgot about.
# https://www.quora.com/How-do-you-determine-sum-limits_-n-1-infty-frac-n+1-4-n-by-hand/answer/Job-Bouwman
from __future__ import division, print_function # Fix Python 2.
def dec2frac(f):
"From scratch, 7dec15. Handles negative input since 9apr17."
of = f
f = abs(f)
n = 1
d = 2
while 1:
diff = n/d - f
#print(n, d, diff, f)
if abs(diff) < 0.00001: break
if diff > 0:
n -= 1
d += 1
else: n += 1
return (-n if of < 0 else n, d)
print(dec2frac(0.235)) # => 47/200
print(dec2frac(0.3333333333333)) # => 1/3
print(dec2frac(0.35)) # => 7/20
print(dec2frac(0.13)) # => 13/100
print(dec2frac(0.37)) # => 37/100
print(dec2frac(7/8)) # => 7/8
1/0 # lazy exit
def gcd(a, b):
"https://en.wikipedia.org/wiki/Greatest_common_divisor"
gcd = int(a)
while gcd > 1:
if a%gcd == 0 and b%gcd == 0: break
gcd -= 1
return gcd
def dec_to_frac(f):
"http://www.purplemath.com/modules/percents2.htm"
if f == 0: return 0
sf = str(f%1)[2:]
lf = len(sf)
repeating = False
for i, c in enumerate(sf):
if sf.find(c) < i:
lf = i
repeating = True
break
x = 10**(lf)
print("f:%s len:%s x:%s"%(str(f), lf, x))
a = int(x*f)#-f)
if repeating:
a = int(x*f-f)
b = x -1
else:
a = int(x*f)
b = x
print("gcd(x*f, x)", x*f)
d = gcd(a, x)
#print(a, b, d)
return (a//d, b//d)
sum = 0
for i in range(5):
n = i+1
sum += (n+1)/(4**n)
print(i, sum)
print(7/9)
for i in range(10):
print("{}/{}={}, {}".format(i, i+1, i/(i+1), dec2frac(i/(i+1))))
@CTimmerman
Copy link
Author

CTimmerman commented Apr 9, 2017

Python can do this since 4 months ago:

>>> Decimal('-3.14').as_integer_ratio()
(-157, 50)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment