Python 3.x 中的圆形变量

Round variable in Python 3.x

我有一个生成这些值的应用程序:

[ -2.00000000e+00 -1.00000000e+00 -1.00929366e-16 1.00000000e+00]

如何将数字 -1.00929366e-16 舍入为 0?我想要的是如果从正确的点开始有 x 个零,它将那个值替换为零。

最简单的解决方案就是使用内置的数学函数

round(float)

如果小数点后第10位小于5,则return浮点数的整数部分,如果小数点后10位大于等于5,则return多一位.

这应该是您需要的所有内容,而不是计算零。

*注意:由于您似乎有一个值列表,请使用

[round(each_number) for each_number in list_of_floats]

将舍入应用于每个值。

**请注意,如果您要对这些需要任何方差测量的数字应用任何数学运算,我建议您不要对它们进行四舍五入,因为您通常希望避免计算结果为 0 ,比如说,标准偏差,如果你打算在以后的函数中使用它(这让我很头疼,并且要求我在我的浮点数中实际包含微小的变化以避免在以后的计算中出错)。

有关详细信息,请参阅:https://docs.python.org/3/library/functions.html#round

(似曾相识推荐)

如果我错了请纠正我:你不只是想四舍五入这个值。仅当 "there is a number of zeroes from the right point" 时才需要这样做。

假设这个数字是 5。你不想将 0.001 舍入,但你想将 0.000001 舍入为 0。而 1.000001 为 1。好吧,你可以通过检查你的数字和最接近的整数之间的距离来做到这一点,像这样:

def round_special(n):
    return round(n) if abs(n-round(n)) < 1e-5 else n

print round_special(0.001)
print round_special(0.0001)
print round_special(0.00001)
print round_special(0.000001)
print round_special(1.0000099)

print map(round_special, [0.001, 0.0001, 0.00001, 0.000001, 1.0000099])

产生:

0.001
0.0001
1e-05
0.0
1.0
[0.001, 0.0001, 1e-05, 0.0, 1.0]