Skip to main content
 首页 » 编程设计

python之python 中 floor() 函数的意外值

2025年05月04日18shanyou

import numpy 
import math 
 
x = numpy.roots([2,-2,(21 - 21**2)]) 
print x[0], math.floor(x[0]) 

输出是:

15.0 14.0  

我希望

15.0 15.0 

我不认为有任何理由让下限等于 14.0。请解释!

请您参考如下方法:

我之前使用过一个名为 fAlmostEqual 的函数,基于 numpy 的 allclose功能:

import math 
 
def fAlmostEqual(a, b, rtol=1.0000000000000001e-05, atol=1e-08): 
    """Checks if the given floats are almost equal. Uses the algorithm 
    from numpy.allclose.""" 
    return math.fabs(a - b) <= (atol + rtol * math.fabs(b)) 

基于此创建模糊楼层函数:

def fuzzyFloor(v): 
    """Returns the floor of the given number, unless it is equal to its 
    ceiling (within floating point error).""" 
    floor = math.floor(v) 
    if fAlmostEqual(floor+1, v): 
        return floor+1 
    return floor 
 
print fuzzyFloor(14.9999999999999) 
print fuzzyFloor(15) 
print fuzzyFloor(14.99) 
print fuzzyFloor(14.5) 

这打印:

15.0 
15.0 
14.0 
14.0