如果数字以.0结尾,我将尝试运行一个测试
我正在运行一个程序,数字之间有几个数量级的距离,所以我不能估计到一定数量的数字。使用%也不起作用,因为这样会排除某些数字。这个程序中的所有数字都是浮点数,所以我需要一种方法来检查它是否以.0结尾,而不是以.00000000000001232结尾,或者它必须以.0结尾
舍入函数的问题是,我要处理的是几个数量级的数字。我需要一些东西来检查它是否只有一个小数。或者检查小数是否为0的东西。
代码:
from myro import *
from math import *
def main():
z = 3
a = 2
b = 2
x = 3
y = 2 #starts at y = 3
lim = 25
c = (a**x + b**y)**(1.0/z)
resultnum = 0
while z <= lim:
while a <= lim:
while b <= lim:
while x <= lim:
while y <= lim:
y = y + 1
c = (a**x + b**y)**(1.0/z)
if float(int(c) + 1) != round(c, 6):
pass
else:
print str(a) + "^" + str(x) + " + " + str(b) + "^" + str(y) + " = " + str(int(c)+1) + "^" + str(z)
resultnum = resultnum + 1
print c
y = 3
x = x + 1
x = 3
b = b + 1
b = 3
a = a + 1
a = 3
z = z + 1
print z
print "code cycle complete"
print str(resultnum) + " results"
main()发布于 2013-06-08 09:57:05
>>> n1 = 2.0
>>> int(n1) == n1 and isinstance(n1, float)
True
>>> n1 = 2
>>> int(n1) == n1 and isinstance(n1, float)
False
>>> n1 = 2.01
>>> int(n1) == n1 and isinstance(n1, float)
False
>>> n1 = 1E1 #works for scientific notation as well
>>> int(n1) == n1 and isinstance(n1, float)
True发布于 2013-06-08 10:13:14
Python已经做到了这一点。使用Python作为字符串提供的内容可能是您想要的:
In [577]: def dot_zero(number):
.....: return str(number).endswith('.0')
.....:
In [578]: dot_zero(2.0)
Out[578]: True
In [579]: dot_zero(2)
Out[579]: False
In [580]: dot_zero(2.01)
Out[580]: False编辑
正如@jamylak指出的那样,这不适用于大数字,因为str使用的是科学记数法。保持了转换为字符串的基本思想,但也迎合了大数字,我们最终得到了更冗长和丑陋的解决方案:
def dot_zero_string(number):
# tested and works with Python 3.3
split = str(number).split('e')
return len(split) == 2 or split[0].endswith('.0')这是来自@AshwiniChaudhary的答案中的解决方案
def dot_zero_inst(number):
return int(number) == number and isinstance(number, float)比较不同的案例会得到相同的结果:
numbers = [1, 1.0, 1000, 1000.0, 3e38, 1.5555555555555555555555e12,
1.5555555555555555555555e17, 0, 0.0]
numbers = numbers + [-number for number in numbers]
for number in numbers:
assert dot_zero_inst(number) == dot_zero_string(number)发布于 2013-06-08 10:15:59
为了展示另一种方法,您总是可以用‘.’进行拆分:
>>> num = 12.023
>>> str(num).split('.')[1] == '0'
False
>>> num = 12.0
>>> str(num).split('.')[1] == '0'
True请注意,这之所以有效,是因为您说过都是浮点数。这将提供一个错误num is an int
https://stackoverflow.com/questions/16995249
复制相似问题