Python 如何检查浮点值是否在某个范围内并具有给定的十进制数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25466104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if a float value is within a certain range and has a given number of decimal digits?
提问by user3841581
How to check if a float value is within a range (0.50,150.00) and has 2 decimal digits?
如何检查浮点值是否在范围 (0.50,150.00) 内并且有 2 个十进制数字?
For example, 15.22366 should be false (too many decimal digits). But 15.22 should be true.
例如,15.22366 应该是假的(十进制数字太多)。但 15.22 应该是真的。
I tried something like:
我试过类似的东西:
data= input()
if data in range(0.50,150.00):
return True
采纳答案by Sylvain Leroux
Is that you are looking for?
是你要找的吗?
def check(value):
if 0.50 <= value <= 150 and round(value,2)==value:
return True
return False
Given your comment:
鉴于您的评论:
i input 15.22366 it is going to return true; that is why i specified the range; it should accept 15.22
我输入 15.22366 它将返回 true;这就是为什么我指定了范围;它应该接受 15.22
Simply said, floating pointvalues are imprecise. Many values don't have a precise representation. Say for example 1.40. It might be displayed "as it":
简单地说,浮点值是不精确的。许多值没有精确的表示。比如说1.40。它可能会显示为“原样”:
>>> f = 1.40
>>> print f
1.4
But this is an illusion. Python has rounded that value in order to nicely display it. The real value as referenced by the variable fis quite different:
但这是一种错觉。Python 已舍入该值以便很好地显示它。变量引用的实际值f完全不同:
>>> from decimal import Decimal
>>> Decimal(f)
Decimal('1.399999999999999911182158029987476766109466552734375')
According to your rule of having only 2 decimals, should freference a valid value or not?
根据您只有两位小数的规则,是否应该f引用有效值?
The easiest way to fix that issue is probably to use round(...,2)as I suggested in the code above. But this in only an heuristic -- only able to reject "largely wrong" values. See my point here:
解决该问题的最简单方法可能是round(...,2)按照我在上面代码中的建议使用。但这只是一种启发式——只能拒绝“严重错误”的值。在这里看到我的观点:
>>> for v in [ 1.40,
... 1.405,
... 1.399999999999999911182158029987476766109466552734375,
... 1.39999999999999991118,
... 1.3999999999999991118]:
... print check(v), v
...
True 1.4
False 1.405
True 1.4
True 1.4
False 1.4
Notice how the last few results might seems surprising at first. I hope my above explanations put some light on this.
请注意最后几个结果乍一看似乎令人惊讶。我希望我上面的解释能说明这一点。
As a final advice, for your needs as I guessthem from your question, you should definitively consider using "decimal arithmetic". Python provides the decimalmodule for that purpose.
作为最后的建议,根据我从您的问题中猜测的您的需求,您应该明确考虑使用“十进制算术”。为此,Python 提供了小数模块。
回答by TidB
Why don't you just use round?
你为什么不直接使用round?
round(random.uniform(0.5, 150.0), 2)
回答by u1860929
floatis the wrong data type to use for your case, Use Decimalinstead.
float是用于您的案例的错误数据类型,请Decimal改用。
Check python docs for issues and limitations. To quote from there (I've generalised the text in Italics)
检查python 文档的问题和限制。从那里引用(我用斜体概括了文本)
Floating-point numbers are represented in computer hardware as base 2 (binary) fractions.
no matter how many base 2 digits you're willing to use, some decimal value (like 0.1)cannot be represented exactly as a base 2 fraction.
Stop at any finite number of bits, and you get an approximation
On a typical machine running Python, there are 53 bits of precision available for a Python float, so the value stored internally when you enter a decimal number is the binary fraction which is close to, but not exactly equal to it.
The documentation for the built-in round() function says that it rounds to the nearest value, rounding ties away from zero.
浮点数在计算机硬件中表示为基数 2(二进制)分数。
无论您愿意使用多少个基数为 2 的数字,某些十进制值(如 0.1)都不能准确地表示为基数为 2 的分数。
停在任何有限的位数上,你会得到一个近似值
在运行 Python 的典型机器上,Python 浮点数有 53 位精度可用,因此当您输入十进制数时,内部存储的值是接近但不完全等于它的二进制小数。
内置 round() 函数的文档说它四舍五入到最接近的值,四舍五入远离零。
And finally, it recommends
最后,它建议
If you're in a situation where you care which way your decimal halfway-cases are rounded, you should consider using the decimalmodule.
如果您在乎小数中途情况的舍入方式,则应考虑使用小数模块。
And this will hold for your case as well, as you are looking for a precision of 2 digits after decimal points, which float just can't guarantee.
这也适用于您的情况,因为您正在寻找小数点后 2 位的精度,而浮点数无法保证。
EDIT Note:The answer below corresponds to original question related to random float generation
编辑注意:下面的答案对应于与随机浮点生成相关的原始问题
Seeing that you need 2 digits of sure shot precision, I would suggest generating integer random numbers in range [50, 15000]and dividing them by 100to convert them to float yourself.
看到您需要 2 位数的确定射击精度,我建议在范围内生成整数随机数并将它们[50, 15000]除以将它们100转换为自己浮动。
import random
random.randint(50, 15000)/100.0
回答by enrico.bacis
Probably what you want to do is not to change the value itself. As said by Cyberin the comment, even if your round a floating point number, it will always store the same precision. If you need to change the way it is printed:
可能你想做的不是改变值本身。正如Cyber在评论中所说的那样,即使您舍入一个浮点数,它也将始终存储相同的精度。如果您需要更改打印方式:
n = random.uniform(0.5, 150)
print '%.2f' % n # 58.03
回答by Mohammed Hasif Meera S
The easiest way is to first convert the decimal to string and split with '.' and check if the length of the character. If it is >2 then pass on. i.e. Convert use input number to check if it is in a given range.
最简单的方法是先将十进制转换为字符串,然后用'.'分割。并检查字符的长度。如果大于 2,则继续。即转换使用输入数字来检查它是否在给定的范围内。
a=15.22366
if len(str(a).split('.')[1])>2:
if 0.50 <= value <= 150:
<do your stuff>>

