2016-02-04 109 views
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?

+3

你應該瞭解[與浮點運算的問題] (https://docs.python.org/2/tutorial/floatingpoint.html) – soon

+0

[浮點數學是否被破壞?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken ) – Lafexlos

+0

你可以使用'prin t'%.1f'%n'在這種情況下。 –

回答

2

並非所有的floating point numbers都可以完全表示。例如,這是與Python 3.5的輸出:

1 
0.9 
0.8 
0.7000000000000001 
0.6000000000000001 
0.5000000000000001 
0.40000000000000013 
0.30000000000000016 
0.20000000000000015 
0.10000000000000014 
1.3877787807814457e-16 

一種解決方案可以四捨五入:

def myRange(start, stop, step): 
    s = start 
    if step < 0: 
     while s > stop: 
      yield s 
      s += step 
      s = round(s, 15) 
    if step > 0: 
     while s < stop: 
      yield s 
      s += step 
      s = round(s, 15) 

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 
0.0