2016-11-03 65 views
0

我正在寫一段測試代碼,它將兩個浮點數int相加。我可以得到準確的結果,但是當我將結果插入python列表中時會出現額外的點數,我不知道是什麼導致了這種後果。請給我一個提示!python列表中的浮點數問題

我的代碼:

center = [120.688281,30.500036] 
    coupon_list = [] 
    for i in range(5): 
     seed_x = random.randint(1,100) 
     print 'seed_x:' 
     print seed_x 
     random.seed(seed_x) 
     rand_x = random.randrange(100,500,20)/float(100000) 

     seed_y = random.randint(1,100) 
     print 'seed_y:' 
     print seed_y 
     random.seed(seed_y) 
     rand_y = random.randrange(100,500,20)/float(100000) 
     print 'rand_x:' 
     print rand_x 
     print 'rand_y:' 
     print rand_y 
     print 'float convert:' 
     x = center[0]+ rand_x 
     y = center[1] + rand_y 
     print 'x:' 
     print x 
     print 'y:' 
     print y 
     coupon = [] 
     coupon.append(x) 
     coupon.append(y) 
     print 'coupon:' 
     print coupon 
     coupon_list.append(coupon) 
    print coupon_list 

我的結果:

seed_x: 
22 
seed_y: 
15 
rand_x: 
0.0048 
rand_y: 
0.0048 
float convert: 
x: 
120.693081 
y: 
30.504836 
coupon: 
[120.693081, 30.504836] 
seed_x: 
2 
seed_y: 
95 
rand_x: 
0.0048 
rand_y: 
0.004 
float convert: 
x: 
120.693081 
y: 
30.504036 
coupon: 
[120.693081, 30.504036000000003] 
seed_x: 
52 
seed_y: 
6 
rand_x: 
0.0048 
rand_y: 
0.004 
float convert: 
x: 
120.693081 
y: 
30.504036 
coupon: 
[120.693081, 30.504036000000003] 
seed_x: 
83 
seed_y: 
86 
rand_x: 
0.0028 
rand_y: 
0.004 
float convert: 
x: 
120.691081 
y: 
30.504036 
coupon: 
[120.691081, 30.504036000000003] 
seed_x: 
4 
seed_y: 
11 
rand_x: 
0.0018 
rand_y: 
0.0028 
float convert: 
x: 
120.690081 
y: 
30.502836 
coupon: 
[120.690081, 30.502836000000002] 
[[120.693081, 30.504836], [120.693081, 30.504036000000003], [120.693081, 30.504036000000003], [120.691081, 30.504036000000003], [120.690081, 30.502836000000002]] 
+2

這裏沒有問題。列表中的對象由它們的'repr()'輸出表示。你的float對象具有這個確切的值,但'str()'轉換限制了打印的位數。 –

+1

@ Martijin Pieters爲什麼有些結果會出現額外的點數,有些則不是?如果不是問題,所有結果都應打印出相同數量的點。 – pipi

+1

浮點數使用二進制分數來近似值。不是所有的值都可以用*表示*精確*使用二進制分數。你有一些這樣的數字,所以有一個非常非常小的偏差來使它適合。 –

回答

2

如果你能有多少你需要的精度決定,你可以總是可以使用這樣的事情。

coupon.append(float(format(x,'.6f'))) 
coupon.append(float(format(y,'.6f'))) 

在這種情況下,在小數點後面給出6位數字。
例如

>>> a=30.504036000000003 
>>> print a 
30.504036 
>>> repr(a) 
'30.504036000000003' 
>>> coupon=[] 
>>> coupon.append(a) 
>>> coupon 
[30.504036000000003] 
>>> coupon.append(float(format(a,'.6f'))) 
>>> coupon 
[30.504036000000003, 30.504036] 
>>> coupon[0]+coupon[1] 
61.008072 
>>> type(coupon[0]) 
<type 'float'> 
>>> type(coupon[1]) 
<type 'float'> 

編輯:或馬克在他的評論中指出,你可以改用:

coupon.append(round(x,6)) 
coupon.append(round(y,6)) 

,並得到同樣的結果。

+1

'float(格式(a,'.6f'))'是說'round(a,6)'的一種相當複雜的方式。 –

+0

@MarkDickinson coupon.append(round(a,6))您的權利!檢查它,你會得到一個存儲在'coupon'中的'float'。我沒有想到它,但這就是蟒蛇的美妙之處,總有不止一種方法來狩獵貓。 –