0
我寫了下面創建負浮點步驟的範圍:範圍浮點數和負的步
def myRange(start, stop, step):
s = start
if step < 0:
while s > stop:
yield s
s += step
if step > 0:
while s < stop:
yield s
s += step
但r = myRange(1,0,-0.1)
輸出看起來有些奇怪
>>> r = myRange(1,0,-0.1)
>>> for n in r: print n
...
1
0.9
0.8
0.7
0.6
0.5
0.4
0.3
0.2
0.1
1.38777878078e-16
這最後一個數字來自哪裏?爲什麼它不是0?
你應該瞭解[與浮點運算的問題] (https://docs.python.org/2/tutorial/floatingpoint.html) – soon
[浮點數學是否被破壞?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken ) – Lafexlos
你可以使用'prin t'%.1f'%n'在這種情況下。 –