为什么在某些情况下,Python中的类型转换/乘法会失败? [英] Why does type-conversion/multiplication fail in Python for certain cases?
问题描述
我当然是Python的新手。因此,我很难理解下面的代码给我的结果i = 15和i = 21.在所有其他情况下,我的期望是。
I'm certainly a newbie to Python. Hence, I'm struggling to understand the results that the following bit of code gives me for i = 15 and i = 21. In all other cases is does what I expect.
import numpy as np
i_values = []
results = []
results2 = []
for i in range(27):
i_values.append(i)
result = np.int((i*0.02+0.03)*1.e2)
results.append(result)
result2 = (i*0.02+0.03)*1.e2
results2.append(result2)
print i_values
print results
print results2
我的问题是:为什么代码适用于大多数数字但是某些值失败我?我可以解决这个问题
My question is: Why is the code working for most numbers but fails for certain values of i? I could solve the problem by
result = np.int(np.rint(((i*0.02+0.03)*1.e2))
但我只是想了解为什么它首先发生。
but I just want to understand why it occurs in the first place.
提前谢谢。
推荐答案
我认为这个链接应该给你一个见解:
I think this link should give you an insight:
这是可以理解的,因为如果比较不同语言处理它们之间的结果,结果可能会略有不同。在python中使用之间的简单例子只是谷歌搜索答案:
It is understandable since the results can be slightly different due to precision if compared between how different languages deal with them. A quick example between using in python and just googling the answer:
这篇关于为什么在某些情况下,Python中的类型转换/乘法会失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!