如何找出小数与10的乘幂相乘后最接近的整数

2024-09-27 07:34:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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

math.isclose(a, b)

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

另一个例子:

1.2799999997163347应该在它乘以100 (10 ** 2)后给出128

有没有办法完成这件事?你知道吗


Tags: 整数math例子浮点浮点数办法isclose
3条回答

^{}告诉您,给定参数rel_tolabs_tol,两个floats是否接近。默认设置为

rel_tol=1e-09, abs_tol=0.0

^{}将直接跳到下一个整数,它可能远远超出这些公差。你知道吗

abs_tol设置为<0.5将使iscloseTrue成为您在round上使用过的内容:

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

由于使用字符串操作的解决方案似乎还可以,下面是一个简短的解决方案:

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

连续分数是很强大的。也许这是一个小的过度,但它的工作。你知道吗

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

相关问题 更多 >

    热门问题