如何检查浮点值是否在一定范围内并且具有给定的十进制数字?

时间:2021-12-03 17:08:04

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应为false(十进制数字太多)。但是15.22应该是真的。

I tried something like:

我试过类似的东西:

data= input()
if data in range(0.50,150.00):
   return True

4 个解决方案

#1


11  

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 point values are imprecise. Many values don't have a precise representation. Say for example 1.40. It might be displayed "as it":

简单地说,浮点值是不精确的。许多值没有精确的表示。比如说1.40。它可能会显示为“as it”:

>>> 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 f is quite different:

但这是一种幻觉。 Python已经舍入该值以便很好地显示它。变量f引用的实际值非常不同:

>>> from decimal import Decimal
>>> Decimal(f)
Decimal('1.399999999999999911182158029987476766109466552734375')

According to your rule of having only 2 decimals, should f reference a valid value or not?

根据你只有2位小数的规则,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 guess them from your question, you should definitively consider using "decimal arithmetic". Python provides the decimal module for that purpose.

作为最后的建议,根据你的问题,我猜测你的需求,你应该明确地考虑使用“十进制算术”。 Python为此提供了十进制模块。

#2


3  

float is the wrong data type to use for your case, Use Decimal instead.

float是用于您的案例的错误数据类型,请改用Use 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.

浮点数在计算机硬件中表示为基数2(二进制)分数。

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.

无论你愿意使用多少个2位数字,一些十进制值(如0.1)都不能完全表示为基数2分数。

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.

在运行Python的典型机器上,Python浮点数有53位可用精度,因此输入十进制数时内部存储的值是二进制小数,它接近但不完全等于它。

The documentation for the built-in round() function says that it rounds to the nearest value, rounding ties away from zero.

内置的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 decimal module.

如果您处理的情况是您关注十进制中间情况的四舍五入,则应考虑使用十进制模块。

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 100 to convert them to float yourself.

看到你需要2位数的确定射击精度,我建议生成范围[50,15000]中的整数随机数并将它们除以100以将它们转换为浮动自己。

import random
random.randint(50, 15000)/100.0

#3


2  

Why don't you just use round?

你为什么不用圆?

round(random.uniform(0.5, 150.0), 2)

#4


0  

Probably what you want to do is not to change the value itself. As said by Cyber in 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

#1


11  

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 point values are imprecise. Many values don't have a precise representation. Say for example 1.40. It might be displayed "as it":

简单地说,浮点值是不精确的。许多值没有精确的表示。比如说1.40。它可能会显示为“as it”:

>>> 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 f is quite different:

但这是一种幻觉。 Python已经舍入该值以便很好地显示它。变量f引用的实际值非常不同:

>>> from decimal import Decimal
>>> Decimal(f)
Decimal('1.399999999999999911182158029987476766109466552734375')

According to your rule of having only 2 decimals, should f reference a valid value or not?

根据你只有2位小数的规则,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 guess them from your question, you should definitively consider using "decimal arithmetic". Python provides the decimal module for that purpose.

作为最后的建议,根据你的问题,我猜测你的需求,你应该明确地考虑使用“十进制算术”。 Python为此提供了十进制模块。

#2


3  

float is the wrong data type to use for your case, Use Decimal instead.

float是用于您的案例的错误数据类型,请改用Use 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.

浮点数在计算机硬件中表示为基数2(二进制)分数。

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.

无论你愿意使用多少个2位数字,一些十进制值(如0.1)都不能完全表示为基数2分数。

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.

在运行Python的典型机器上,Python浮点数有53位可用精度,因此输入十进制数时内部存储的值是二进制小数,它接近但不完全等于它。

The documentation for the built-in round() function says that it rounds to the nearest value, rounding ties away from zero.

内置的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 decimal module.

如果您处理的情况是您关注十进制中间情况的四舍五入,则应考虑使用十进制模块。

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 100 to convert them to float yourself.

看到你需要2位数的确定射击精度,我建议生成范围[50,15000]中的整数随机数并将它们除以100以将它们转换为浮动自己。

import random
random.randint(50, 15000)/100.0

#3


2  

Why don't you just use round?

你为什么不用圆?

round(random.uniform(0.5, 150.0), 2)

#4


0  

Probably what you want to do is not to change the value itself. As said by Cyber in 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