如何在乘以 10 的幂后找出最接近小数的整数



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

math.isclose(a, b)

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

再比如:

1.2799999997163347 乘以 128 后应得到 100 (10 ** 2)

有没有办法做到这一点?

连续分数非常强大。也许这里有一个小的矫枉过正,但它有效。

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

由于使用字符串操作的解决方案似乎没问题,这里有一个不错的简短解决方案:

def nearest( x, Max9 = 2 ):
    s = str(x).replace('.','')
    splitter = Max9 * '9'
    sOut = s.split( splitter )[0]
    return int( sOut ) + 1
a = 7.999999985666533
b = 1.5999999991220535
c = 1.2799999997163347
print nearest( a )
print nearest( b )
print nearest( c )

只是提供:

>> 8
>> 16
>> 128

编辑

正如@gc7__正确指出的那样,上述解决方案忽略了值稍大的情况。这使得代码有点复杂,但仍然很好。

import re
def nearest( x, Max09 = 2, digits=25 ):
    s = ('{val:.{dig}f}'.format( dig=digits, val=x ) ).split('.')
    rnd = 0
    if len(s) < 2 or s[1] == '0':## input is integer xyz or float of type xyz.
        out = int( x )
    else:
        s0, s9 = Max09*'0', Max09*'9'
        splitter = '{}|{}'.format( s0, s9)
        body = s[0]
        p0, p9 = s[1].find(s0), s[1].find(s9) ### returns -1 if nothing is found
        tail = re.split( splitter, s[1] )[0]
        out = int( body + tail )
        if p9 > -1 and ( p9 < p0 or p0 < 0 ):
            rnd = 1
    return out + rnd
a = 7.999998560066533
b = 1.5999999991220535
c = 1.2799999997163347
d = 1233
e = 19935
f = 1.6000000000123
g = 10006.6000000000123
h = 500001.0
print nearest( a )
print nearest( b )
print nearest( c )
print nearest( d )
print nearest( e )
print nearest( f )
print nearest( g )
print nearest( h )

提供:

>> 8
>> 16
>> 128
>> 1233
>> 19935
>> 16
>> 100066
>> 500001

math.isclose告诉您给定参数 rel_tolabs_tol 的情况下,两个floats是否接近。 默认设置是

rel_tol=1e-09, abs_tol=0.0

round将跳到下一个整数,这可能远远超出这些容差。

abs_tol设置为<0.5的内容将使您round使用过的内容isclose True

from math import isclose
f = 1.5999999991220535
r = round(f)
print(r)                                  # 2
print(isclose(f, r))                      # False
print(isclose(f, r, abs_tol=0.5-0.00001)) # True

最新更新