top
Loading...
NumPy 數學函數

NumPy 數學函數

NumPy 包含大量的各種數學運算的函數,包括三角函數,算術運算的函數,復數處理函數等。

三角函數

NumPy 提供了標准的三角函數:sin()、cos()、tan()。

實例

import numpy as np a = np.array([0,30,45,60,90]) print ('不同角度的正弦值:') # 通過乘 pi/180 轉化為弧度 print (np.sin(a*np.pi/180)) print ('\n') print ('數組中角度的余弦值:') print (np.cos(a*np.pi/180)) print ('\n') print ('數組中角度的正切值:') print (np.tan(a*np.pi/180))

輸出結果為:

不同角度的正弦值:
[0.         0.5        0.70710678 0.8660254  1.        ]

數組中角度的余弦值:
[1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01
 6.12323400e-17]

數組中角度的正切值:
[0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00
 1.63312394e+16]

arcsin,arccos,和 arctan 函數返回給定角度的 sin,cos 和 tan 的反三角函數。

這些函數的結果可以通過 numpy.degrees() 函數將弧度轉換為角度。

實例

import numpy as np a = np.array([0,30,45,60,90]) print ('含有正弦值的數組:') sin = np.sin(a*np.pi/180) print (sin) print ('\n') print ('計算角度的反正弦,返回值以弧度為單位:') inv = np.arcsin(sin) print (inv) print ('\n') print ('通過轉化為角度製來檢查結果:') print (np.degrees(inv)) print ('\n') print ('arccos 和 arctan 函數行為類似:') cos = np.cos(a*np.pi/180) print (cos) print ('\n') print ('反余弦:') inv = np.arccos(cos) print (inv) print ('\n') print ('角度製單位:') print (np.degrees(inv)) print ('\n') print ('tan 函數:') tan = np.tan(a*np.pi/180) print (tan) print ('\n') print ('反正切:') inv = np.arctan(tan) print (inv) print ('\n') print ('角度製單位:') print (np.degrees(inv))

輸出結果為:

含有正弦值的數組:
[0.         0.5        0.70710678 0.8660254  1.        ]

計算角度的反正弦,返回值以弧度為單位:
[0.         0.52359878 0.78539816 1.04719755 1.57079633]

通過轉化為角度製來檢查結果:
[ 0. 30. 45. 60. 90.]

arccos 和 arctan 函數行為類似:
[1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01
 6.12323400e-17]

反余弦:
[0.         0.52359878 0.78539816 1.04719755 1.57079633]

角度製單位:
[ 0. 30. 45. 60. 90.]

tan 函數:
[0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00
 1.63312394e+16]

反正切:
[0.         0.52359878 0.78539816 1.04719755 1.57079633]

角度製單位:
[ 0. 30. 45. 60. 90.]

捨入函數

numpy.around() 函數返回指定數字的四捨五入值。

numpy.around(a,decimals)

參數說明:

  • a: 數組
  • decimals: 捨入的小數位數。 默認值為0。 如果為負,整數將四捨五入到小數點左側的位置

實例

import numpy as np a = np.array([1.0,5.55, 123, 0.567, 25.532]) print ('原數組:') print (a) print ('\n') print ('捨入後:') print (np.around(a)) print (np.around(a, decimals = 1)) print (np.around(a, decimals = -1))

輸出結果為:

原數組:
[  1.      5.55  123.      0.567  25.532]

捨入後:
[  1.   6. 123.   1.  26.]
[  1.    5.6 123.    0.6  25.5]
[  0.  10. 120.   0.  30.]

numpy.floor()

numpy.floor() 返回數字的下捨整數。

實例

import numpy as np a = np.array([-1.7, 1.5, -0.2, 0.6, 10]) print ('提供的數組:') print (a) print ('\n') print ('修改後的數組:') print (np.floor(a))

輸出結果為:

提供的數組:
[-1.7  1.5 -0.2  0.6 10. ]

修改後的數組:
[-2.  1. -1.  0. 10.]

numpy.ceil()

numpy.ceil() 返回數字的上入整數。

實例

import numpy as np a = np.array([-1.7, 1.5, -0.2, 0.6, 10]) print ('提供的數組:') print (a) print ('\n') print ('修改後的數組:') print (np.ceil(a))

輸出結果為:

提供的數組:
[-1.7  1.5 -0.2  0.6 10. ]

修改後的數組:
[-1.  2. -0.  1. 10.]
北斗有巢氏 有巢氏北斗