将浮点四舍五入到最接近的 2/100

del*_*tap 2 python numpy scipy

我需要取一个像 0.405 这样的数字并将其四舍五入为 0.40,同时还将 0.412 四舍五入为 0.42。有没有内置函数可以做到这一点?

pax*_*blo 5

作为通用解决方案,这允许舍入到任意分辨率(当然,除了零之外,但零分辨率没有什么意义(a))。对于您的情况,您只需要提供0.02分辨率,尽管其他值也是可能的,如测试用例所示。

# This is the function you want.

def roundPartial (value, resolution):
    return round (value / resolution) * resolution

# All these are just test cases, the first two being your own test data.

print "Rounding to fiftieths"
print roundPartial (0.405, 0.02)
print roundPartial (0.412, 0.02)

print "Rounding to quarters"
print roundPartial (1.38, 0.25)
print roundPartial (1.12, 0.25)
print roundPartial (9.24, 0.25)
print roundPartial (7.76, 0.25)

print "Rounding to hundreds"
print roundPartial (987654321, 100)
Run Code Online (Sandbox Code Playgroud)

这输出:

Rounding to fiftieths
0.4
0.42
Rounding to quarters
1.5
1.0
9.25
7.75
Rounding to hundreds
987654300.0
Run Code Online (Sandbox Code Playgroud)

(a)如果您患有特殊的人格障碍,需要您处理这种可能性,请注意您正在寻找最接近的数字,该数字是您所需分辨率的倍数。N由于(对于任何 )最接近N0 倍数的数字始终为 0,因此您可以按如下方式修改该函数:

def roundPartial (value, resolution):
    if resolution == 0:
        return 0
    return round (value / resolution) * resolution
Run Code Online (Sandbox Code Playgroud)

或者,您可以简单地承诺自己不通过零作为决议:-)