如何检查一个浮点值是否是一个整数 [英] How to check if a float value is a whole number
问题描述
处理=真
n = 12000
处理中:
n - = 1
如果n **(1/3)==#检查是否有小数
我不知道如何检查是否是一个整数或通过!我可以将它转换为一个字符串,然后使用索引来检查结束值,看看他们是否是零,这似乎相当繁琐,但。有没有更简单的方法?
要检查浮点值是否是整数,请使用 float.is_integer()
方法:
>>> (1.0).is_integer()
True
>>> (1.555).is_integer()
False
该方法被添加到<$ c在Python 2.6中使用$ c> float 类型。
考虑到在Python 2中, 1/3 code> 0
(整数运算数的整数除法!),浮点运算可能不精确(a float
是使用二进制分数的近似值,而不是精确的实数)。但是稍微调整一下你的循环就可以了:
>>> (12000,-1,-1):
... if(n **(1.0 / 3))。is_integer():
... print n
...
27
8
1
0
<这意味着任何超过3立方(包括10648)由于上述不精确而错过了:
>> ;> (4 ** 3)**(1.0 / 3)
3.9999999999999996
>>> 10648 **(1.0 / 3)
21.999999999999996
您必须检查数字或者不用 float()
来找到你的号码。像下面四舍五入的 12000
的立方体根:
>> > int(12000 **(1.0 / 3))
22
>>> 22 ** 3
10648
如果您使用的是Python 3.5或更新的版本, math.isclose()
函数
>>>从数学导入isclose
>>> isclose((4 ** 3)**(1.0 / 3),4)
True
>>> isclose(10648 **(1.0 / 3),22)
True
,该函数的天真实现(跳过错误检查,忽略无穷大和NaN)如PEP485中提到的 :
def isclose(a,b,rel_tol = 1e-9,abs_tol = 0.0):
返回abs(a-b)<= max(rel_tol * max(abs(a),abs(b)),abs_tol)
I am trying to find the largest cube root that is a whole number, that is less than 12,000.
processing = True
n = 12000
while processing:
n -= 1
if n ** (1/3) == #checks to see if this has decimals or not
I am not sure how to check if it is a whole number or not though! I could convert it to a string then use indexing to check the end values and see whether they are zero or not, that seems rather cumbersome though. Is there a simpler way?
To check if a float value is a whole number, use the float.is_integer()
method:
>>> (1.0).is_integer()
True
>>> (1.555).is_integer()
False
The method was added to the float
type in Python 2.6.
Take into account that in Python 2, 1/3
is 0
(floor division for integer operands!), and that floating point arithmetic can be imprecise (a float
is an approximation using binary fractions, not a precise real number). But adjusting your loop a little this gives:
>>> for n in range(12000, -1, -1):
... if (n ** (1.0/3)).is_integer():
... print n
...
27
8
1
0
which means that anything over 3 cubed, (including 10648) was missed out due to the aforementioned imprecision:
>>> (4**3) ** (1.0/3)
3.9999999999999996
>>> 10648 ** (1.0/3)
21.999999999999996
You'd have to check for numbers close to the whole number instead, or not use float()
to find your number. Like rounding down the cube root of 12000
:
>>> int(12000 ** (1.0/3))
22
>>> 22 ** 3
10648
If you are using Python 3.5 or newer, you can use the math.isclose()
function to see if a floating point value is within a configurable margin:
>>> from math import isclose
>>> isclose((4**3) ** (1.0/3), 4)
True
>>> isclose(10648 ** (1.0/3), 22)
True
For older versions, the naive implementation of that function (skipping error checking and ignoring infinity and NaN) as mentioned in PEP485:
def isclose(a, b, rel_tol=1e-9, abs_tol=0.0):
return abs(a - b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
这篇关于如何检查一个浮点值是否是一个整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!