NumPy(六): 数学函数&算术函数

数学函数

NumPy 包含大量的各种数学运算的函数,包括三角函数,算术运算的函数,复数处理函数等。

三角函数

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

>>> import numpy as np
>>> a = np.array([0,30,45,60 ,90])
#正弦
>>> print(np.sin(a*np.pi/180))
[0.         0.5        0.70710678 0.8660254  1.        ]
#余弦
>>> print(np.cos(a*np.pi/180))
[1.00000000e+00 8.66025404e-01 7.07106781e-01 5.00000000e-01
 6.12323400e-17]
#正切
>>> print(np.tan(a*np.pi/180))
[0.00000000e+00 5.77350269e-01 1.00000000e+00 1.73205081e+00
 1.63312394e+16]

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

>>> a = np.array([0,30,45,60,90])  
>>> sin = np.sin(a*np.pi/180)  
>>> print (sin)
[0.         0.5        0.70710678 0.8660254  1.        ]
>>> inv = np.arcsin(sin)  
>>> print (inv)
[0.         0.52359878 0.78539816 1.04719755 1.57079633]
>>> print (np.degrees(inv))
[ 0. 30. 45. 60. 90.]

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

numpy.around(a,decimals)

参数说明:

  • a: 数组
  • decimals: 舍入的小数位数。 默认值为0。 如果为负,整数将四舍五入到小数点左侧的位置
>>> a = np.array([1.0,5.55,  123,  0.567,  25.532])  
>>> print(a)
[  1.      5.55  123.      0.567  25.532]
>>> print (np.around(a))
[  1.   6. 123.   1.  26.]
>>> print (np.around(a, decimals =  1))
[  1.    5.6 123.    0.6  25.5]
>>> print (np.around(a, decimals =  -1))
[  0.  10. 120.   0.  30.]

numpy.floor() 返回小于或者等于指定表达式的最大整数,即向下取整。

numpy.ceil() 返回大于或者等于指定表达式的最小整数,即向上取整。

NumPy 算术函数

NumPy 算术函数包含简单的加减乘除: add()subtract()multiply() 和 divide()

>>> a = np.arange(9, dtype = np.float_).reshape(3,3)  
>>> a
array([[0., 1., 2.],
       [3., 4., 5.],
       [6., 7., 8.]])
>>> b = np.array([10,10,10])  
>>> b
array([10, 10, 10])
#加
>>> print (np.add(a,b))
[[10. 11. 12.]
 [13. 14. 15.]
 [16. 17. 18.]]
#减
>>> print (np.subtract(a,b))
[[-10.  -9.  -8.]
 [ -7.  -6.  -5.]
 [ -4.  -3.  -2.]]
#乘
>>> print (np.multiply(a,b))
[[ 0. 10. 20.]
 [30. 40. 50.]
 [60. 70. 80.]]
#除
>>> print (np.divide(a,b))
[[0.  0.1 0.2]
 [0.3 0.4 0.5]
 [0.6 0.7 0.8]]

numpy.reciprocal() 函数返回参数逐元素的倒数。如 1/4 倒数为 4/1

>>> a = np.array([0.25,  1.33,  1,  100])  
>>> print (a)
[  0.25   1.33   1.   100.  ]
>>> print (np.reciprocal(a))
[4.        0.7518797 1.        0.01     ]

numpy.mod() 计算输入数组中相应元素的相除后的余数。 函数 numpy.remainder() 也产生相同的结果。

>>> a = np.array([10,20,30]) 
>>> b =np.array([3,5,7])
>>> print(np.divide(a,b))
[3.33333333 4.         4.28571429]
>>> print(np.mod(a,b))
[1 0 2]
>>> print (np.remainder(a,b))
[1 0 2]

猜你喜欢

转载自blog.csdn.net/zcb_data/article/details/110146037
今日推荐