首页 > 解决方案 > 如何在不使用标准函数的情况下合理化分数?

问题描述

那么,如何在不使用标准函数模块的情况下编写一个找到一个有理数的python代码,这个有理数接近一个分数,比如f?

例如,3.14=22/7

分子和分母也有限制,例如:

我的工作:

# calculates i/j upto a precision of 0.001 closer to f.
while( abs((i/j)-f)> 0.001 and i<p, j<q):
    j=j-1
    i =?, 

现在我很困惑,我应该如何修改我的 i 和 j 以使其工作?我可以以任何方式使用 Newton Raphson 算法吗?

标签: pythonnewtons-method

解决方案


Pythons 标准库为此提供了一个模块:

print(fractions.Fraction.from_float(math.pi).limit_denominator(30))

输出

22/7

蛮力方法:

import math

def approx(number, p):
    best = None
    best_dist = number
    for d in range(1, p + 1):
        n0 = int(d / number)
        for n in (n0 -1, n0, n0 + 1):
            if n <= 0:
                continue
            dist = abs(number - d / n)
            if dist < best_dist:
                best_dist = dist
                best = (d, n)
    return best


print(approx(math.pi, 30))

输出

(22, 7)

然后还有第三种选择:https ://www.johndcook.com/blog/2010/10/20/best-rational-approximation/


推荐阅读