python小数整除除法

声明:本人编程菜鸟,刚发现的一些问题,随手写出来了。

版本: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

问题:小数存储方式。