简体   繁体   English

Python 3.x 中的圆形变量

[英]Round variable in Python 3.x

I have an application that generates these values:我有一个生成这些值的应用程序:

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

How can I round the number -1.00929366e-16 to 0 ?如何将数字-1.00929366e-160 what I want is if there is an x number of zeros from the right point, it substituted that value with zero.我想要的是,如果从正确的点开始有 x 个零,它会用零替换该值。

The simplest solution is just using the built in mathematical function最简单的解决方案是使用内置的数学函数

round(float)

Which will return the integer component of the float if the 10ths decimal place is less than 5 and will return one more than that if the 10ths decimal place is greater than or equal to 5.如果第 10 位小数位小于 5,则返回浮点数的整数部分,如果第 10 位小数位大于或等于 5,则返回比小数点多 1 的整数部分。

This should be all that you require instead of counting zeros.这应该就是您所需要的,而不是计算零。

*Note: Since you appear to have a list of values, use *注意:由于您似乎有一个值列表,请使用

[round(each_number) for each_number in list_of_floats]

to apply the rounding to each of the values.将舍入应用于每个值。

**Note if you are going to be applying any mathematical operations to these numbers which require any measurement of variance, I would recommend that you do not round them as you usually want to avoid having an output of 0 from calculating, say, the standard deviation if you're going to be using it in a later function (This has caused me many headaches and required me to actually include minor variation in my floats to avoid errors in later calculations). **请注意,如果您要对这些需要任何方差测量的数字应用任何数学运算,我建议您不要对它们进行四舍五入,因为您通常希望避免计算输出为 0,例如,标准如果你打算在以后的函数中使用它,偏差(这让我很头疼,并要求我在我的浮点数中实际包含微小的变化以避免以后计算中的错误)。

For more information see: https://docs.python.org/3/library/functions.html#round有关更多信息,请参阅: https : //docs.python.org/3/library/functions.html#round

(Recommended by Deja Vu) (Deja Vu 推荐)

Correct me if I'm wrong: you don't just want to round the value.如果我错了,请纠正我:您不只是想对值进行四舍五入。 You want to do so only if "there is a number of zeroes from the right point".只有当“从正确的点开始有多个零”时,您才想要这样做。

Let's say this number is 5. You don't want to round 0.001 , but you want to round 0.000001 to 0. And 1.000001 to 1. Well, you can do so by checking the distance between your number and the nearest integer, like this:假设这个数字是 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])

Which yields:其中产生:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM