首页 > 解决方案 > 如何在乘以 10 的幂后找出最接近小数的整数

问题描述

我有一个最接近 8 的浮点数7.999999985666533,我使用过它math.isclose

math.isclose(a, b)

但是对于浮点值,例如1.5999999991220535最接近的整数是 2 但如果我将它与 相乘10 (10 ** 1),我得到 16 作为最接近的整数,这也是结果isclose

另一个例子:

1.2799999997163347乘以后应该得到 128100 (10 ** 2)

有没有办法做到这一点?

标签: pythonpython-3.xmath

解决方案


连续分数非常强大。也许这是一个小小的矫枉过正,但它的工作原理。

import numpy as np

def get_cont_fraction(x, depth=0, maxdepth=10, precision=1e-6):
    if depth > maxdepth:
        out = []
    else:
        assert x >= 0
        out=[]
        if not depth:
            out += [ int(x) ] + get_cont_fraction( x - int( x ), depth=depth + 1, maxdepth=maxdepth, precision=precision)
        elif x < precision :
            out=[]
        else:
            out += [ int(1./ x) ] + get_cont_fraction(1. / x - int( 1. / x ), depth=depth + 1, maxdepth=maxdepth, precision=precision)
    return out

def get_fraction(inList):
    num = inList[-1]
    den = 1
    testList = inList[:-1:]
    testList = testList[::-1]
    for a in testList:
        num , den = a * num + den, num
    return ( num, den )

if __name__ == "__main__":
    a = get_fraction( get_cont_fraction( 1.5999999991220535  ) )
    print a
    print a[0]*1./a[1]
    a = get_fraction( get_cont_fraction( 1.2799999997163347  ) )
    print a
    print a[0]*1./a[1]

给予:

>> (8, 5)
>> 1.6
>> (32, 25)
>> 1.28

推荐阅读