numpy的通用函数可以对数组进行向量化操作,可以提高数组元素的重复计算的效率。

一.numpy的算数运算符都是对python内置符的封装

  算数运算符

  

>>> import numpy as np
>>> x = np.arange(4)
>>> x
array([0, 1, 2, 3])
>>> x+2
array([2, 3, 4, 5])
>>> np.add(x,2)#加法
array([2, 3, 4, 5])
>>> x-2
array([-2, -1,  0,  1])
>>> np.subtract(x,2)#减法
array([-2, -1,  0,  1])
>>> x*2
array([0, 2, 4, 6])
>>> np.multiply(x,2)#乘法
array([0, 2, 4, 6])
>>> x/2
array([0. , 0.5, 1. , 1.5])
>>> np.divide(x,2)#除法
array([0. , 0.5, 1. , 1.5])
>>> x**2
array([0, 1, 4, 9], dtype=int32)
>>> np.power(x,2)#乘方
array([0, 1, 4, 9], dtype=int32)
>>> x//2
array([0, 0, 1, 1], dtype=int32)
>>> np.floor_divide(x,2)#地板除法
array([0, 0, 1, 1], dtype=int32)
>>> x%2
array([0, 1, 0, 1], dtype=int32)
>>> np.mod(x,2)#取余
array([0, 1, 0, 1], dtype=int32)

二,绝对值

1 >>> x=np.array([-1,-3,-5])
2 >>> np.abs(x)#取绝对值
3 array([1, 3, 5])
View Code

三, 三角函数以及反三角函数

 1 >>> theta=np.linspace(0,np.pi,3)#180°均分成3份
 2 >>> theta
 3 array([0.        , 1.57079633, 3.14159265])
 4  
 5 >>> np.sin(theta)#正弦函数
 6 array([0.0000000e+00, 1.0000000e+00, 1.2246468e-16])
 7  
 8 >>> np.cos(theta)#余弦函数
 9 array([ 1.000000e+00,  6.123234e-17, -1.000000e+00])
10  
11 >>> np.tan(theta)#正切函数
12 array([ 0.00000000e+00,  1.63312394e+16, -1.22464680e-16])
13 >>> 
View Code

       由于计算机的截断,舍入误差,有些为零的地方没有精确到零,但非常小。

 1 >>> x=np.array([-1,0,1])
 2  
 3 >>> np.arcsin(x)
 4 array([-1.57079633,  0.        ,  1.57079633])
 5  
 6 >>> np.arccos(x)
 7 array([3.14159265, 1.57079633, 0.        ])
 8  
 9 >>> np.arctan(x)
10 array([-0.78539816,  0.        ,  0.78539816])
11 >>> 
View Code

 

四,指数及对数运算

1 >>> x=np.array([1,2,3])
2  
3 >>> np.exp(x)
4 array([ 2.71828183,  7.3890561 , 20.08553692])
5  
6 >>> np.power(3,x)
7 array([ 3,  9, 27], dtype=int32)
View Code
 1 >>> x=np.array([1,8,64,100])
 2  
 3 >>> np.log(x) #自然对数ln(x)
 4 array([0.        , 2.07944154, 4.15888308, 4.60517019])
 5  
 6 >>> np.log2(x)
 7 array([0.        , 3.        , 6.        , 6.64385619])
 8  
 9 >>> np.log10(x)
10 array([0.        , 0.90308999, 1.80617997, 2.        ])
11 >>> 
View Code

注意:log(x)表示的是自然对数ln(x)

posted on 2019-04-28 17:21  frank007  阅读(138)  评论(0编辑  收藏  举报