如何将浮点数转换为分数? [英] How to convert float to fraction?
本文介绍了如何将浮点数转换为分数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是一个作业问题.我想编写一个将浮点数转换为整数对的函数:分子和分母.例如:float 0.5应该转换为(1,2).
This is a homework problem. I want to write a function to convert a float to a pair of integers: numerator and denominator. For instance: float 0.5 should be converted to (1,2).
我正在尝试做某事. (请参阅下文),但坦率地说,它对我来说并不好.
I am trying smth. (see below) but frankly it does not look great for me.
// f is the input float
int n = 1
while(fractional_part(f) > 0)
f *= 10;
n++
int m = f;
gcd = gcd(m, n)
return (m/gcd, n/gcd)
如何将浮点数转换为分数?
How would you convert a float to a fraction ?
推荐答案
您可以只使用分数库.
但是,如果您想开发该算法,则建议如下:
But, if you would like to develop the algorithm, here is a suggestion:
from math import floor
from fractions import gcd
def func(v, tol=1e-4):
"""
Don't handle negative values.
Use binary search to find the fraction of a float.
The algorithm is based in a very simple theorem: If a < b then a < (a+b)/2 < b.
"""
f = v - floor(v)
lo = (0, 1)
hi = (1, 1)
while True:
# mid = (lo + hi)/2
# if lo = a/b and hi = c/d, then mid = (ad+bc)/(2ad)
mid = (lo[0]*hi[1] + hi[0]*lo[1], 2*lo[1]*hi[1])
# gcd to reduce fraction
k = gcd(mid[0], mid[1])
mid = (mid[0]/k, mid[1]/k)
d = 1.*mid[0]/mid[1]
# are we close enough?
if abs(f - d) < tol:
break
# if we are above our goal, get high to middle
elif d > f:
hi = mid
# if we are under our goal, get lower to middle
else:
lo = mid
# Add integer part
mid = (mid[0] + int(floor(v))*mid[1], mid[1])
# Debug comparing to Fraction library solution.
#print v, mid, Fraction('%s' % v)
return mid
这篇关于如何将浮点数转换为分数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文