聲明:本人編程菜鳥,剛發現的一些問題,隨手寫出來了。
版本:python 3.7.2
1.問題:取整不是我想要的;
1.1 用math.ceil()
import numpy as np import math x = np.arange(0,1+0.04,0.04) list1=[] for i in x: y = math.ceil(i/0.04) #向上取整 list1.append(y) print(list1) #應該是0到25 #結果[0, 1, 2, 3, 4, 5, 6, 8, 8, 9, 10, 11, 12, 13, 15, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
1.2 用 // or math.floor()
// :來表示整數除法,返回不大於結果的一個最大的整數(問題可能是計算機存儲小數的存儲方式的原因)
/ :則單純的表示浮點數除法
import numpy as np x = np.arange(0,1+0.04,0.04) print(x // 0.04) #結果:array([ 0., 1., 2., 2., 4., 5., 5., 7., 8., 8., 10., 10., 11., 13., 14., 14., 16., 17., 17., 18., 20., 20., 21., 23., 23., 24.])
import numpy as np import math x = np.arange(0,1+0.04,0.04) list1=[] for i in x: y = math.floor(i/0.04) #向下取整 list1.append(y) print(list1) #結果:0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
1.3 用 int():
import numpy as np import math x = np.arange(0,1+0.04,0.04) list1=[] for i in x: y = int(i/0.04) #向0取整 list1.append(y) print(list1) #結果:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]
1.4 round():四舍五入
>>> round(1/2) 0 >>> round(1/3) 0 >>> round(6/10) 1 >>> round(1/3,3) 0.333
這塊這邊給的細,不同版本的規定不一樣;
地址:https://www.runoob.com/w3cnote/python-round-func-note.html
2.我又發現了新的小數除法問題(一定要注意保留啊):
>>> 0.04/2 0.02 >>> 0.28 0.28 >>> 0.28 + 0.04/2 0.30000000000000004
>>> 0.28 + 0.02
0.30000000000000004
>>> Decimal(0.28 + 0.04/2).quantize(Decimal("0.00")) Decimal('0.30') >>> round(0.28 + 0.04/2,2) 0.3
問題:小數存儲方式。