Decimals -> Fraction strings, my solution
Remco Gerlich
scarblac-spamtrap at pino.selwerd.nl
Tue May 16 19:23:09 EDT 2000
Scott wrote in comp.lang.python:
> Hi all,
>
> I've come up with one solution to my problem. Its probably quite
> inefficient, but it does what I need for now. Feel free to
> tear it apart and/or give any advice on how to better implement it.
> This code will take either a number or a string (ie '0.5') and return
> a string of the fraction (ie '1/2'). Here it is:
I had been playing with it too. Your method for finding the gcd is very slow.
To find the gcd of two numbers a and b, you substract the lower from the
higher one, until they are equal.
My solution is this, but it only works for 0 < x < 1. For negative numbers,
integers, and bigger numbers you have some more string formatting to do.
def makefract(x):
assert type(x) == type(1.0) and 0.0 < x < 1
# These lines may count as a hack, but it works
sx = str(x)
digits = len(sx)-2
value = long(sx[2:])
# The fractional representation is "value/(10**digits)".
# A better representation divides both by the gcd.
a, b = value, 10L**digits
GCD = gcd(a,b)
return "%s/%s" % (a/GCD, b/GCD)
def gcd(a,b):
while a != b:
if a < b:
b = b - a
else:
a = a - b
return a
--
Remco Gerlich, scarblac at pino.selwerd.nl
1:22am up 71 days, 13:36, 7 users, load average: 0.04, 0.11, 0.06
More information about the Python-list
mailing list