加、減、乘、除
>>> 1+2
3
>>> 2-1
1
>>> 1*2
2
>>> 1/2
0
>>> 1/2.0
0.5
有問題的地方:
>>> 10.0/3
3.3333333333333335
>>> 0.1 + 0.2
0.30000000000000004
>>> 0.1 + 0.2 - 0.2
0.10000000000000003
>>> 0.1 + 0.2 - 0.3
5.551115123125783e-17
我們輸入的是十進制,計算機要把十進制的數轉化為二進制,然后再計算。但是,在轉化中,浮點數轉化為二進制,轉化為二進制后,不會精確等于十進制的0.1。同時,計算機存儲的位數是有限制的,所以,就出現上述現象了。對于需要非常精確的情況,可以使用 decimal
模塊,它實現的十進制運算適合會計方面的應用和高精度要求的應用。
余數
>>> 5%2
1
>>> 5%2.0
1.0
可以使用內建函數divmod()
來返回商和余數
>>> divmod(5,2) #表示5除以2,返回商和余數
(2, 1)
>>> divmod(5,3)
(1, 2)
>>> divmod(5,2.0)
(2.0, 1.0)
四舍五入
使用內建函數round()
來實現
>>> round(1.2345,2)
1.23
>>> round(1.2345,3) #有問題,應該是1.235,歸根到底還是浮點數中的十進制轉化為二進制惹的禍。
1.234
math模塊
導入模塊
>>> import math
>>> math.pi
3.141592653589793
>>> dir(math) # 查看模塊中包含的工具
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
>>> help(math.pow) #查看每個函數的使用說明
常用的幾個math函數:
>>> math.sqrt(9)
3.0
>>> math.floor(3.14)
3.0
>>> math.floor(3.92)
3.0
>>> math.fabs(-2) #等價于abs(-2)
2.0
>>> abs(-2)
2
>>> math.fmod(5,3) #等價于5%3
2.0
>>> 5%3
2