python中math常用函數

python中math的使用

import math   #先導入math包

1 三角函數

print math.pi #打印pi的值
3.14159265359
print math.radians(180)  #把度數轉化爲弧度,即180=pi
3.14159265359
sin90 = math.sin(math.pi/2)  #計算sin(pi/2)
sin180 = math.sin(math.pi)  #計算sin(pi)
cos90 = math.cos(math.pi/2) #計算cos(pi/2)
cos180 = math.cos(math.pi)  #計算cos(pi)
print 'sin90 is {}  ,sin180 is {}  ;cos90 is {}  ,cos180 is {}  .'.format(sin90,sin180,cos90,cos180)
sin90 is 1.0  ,sin180 is 1.22464679915e-16  ;cos90 is 6.12323399574e-17  ,cos180 is -1.0  .

從上面可以看到sin(pi)和cos(pi/2)都不爲0,而是一個很接近0的數,這是因爲math.pi不是精確的pi。pi是一個無理數,而機器在存儲無理數時只會根據精度截取其中一部分,也就是說機器會根據精度用有理數來代替無理數。所以這裏的計算會存在一些誤差,但這裏的誤差已經到了10的-16次,這對計算機來說已經非常小了,一般我們要求的誤差是10的-5次。
當然啦,我們也可以指定輸出浮點數的位數,如下:

print ('%.3f'%(sin180))  #保留3位小數
0.000

2 乘方 開方

#乘方開方,可以藉助math中的pow函數
print math.pow(10,3)  #10是底數,3是指數
print math.pow(27,1/3)
1000.0
1.0

從上面的結果可以看到math.pow()函數得出的結果是浮點數。如果我們希望乘方的結果是整數的話,我們也可以使用下面的方法。

print 10**3
1000

3 上下取整

print math.floor(3.14)#向下取整
3.0
print math.ceil(3.14)#向上取整
4.0

4 取最大最小值

min(1,100,90,700)  #取最小值
1
max(1,100,90,700)   #取最大值
700

5 求和

sum([1,2,3,4,5])
15

6 同時取商和餘數

divmod(10,3)  #求10除以3的商和餘數
(3, 1)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章