Numpy 數學函數及邏輯函數

2020-10-28 14:00:33

目錄

一、向量化和廣播

二、數學函數

算數運算

numpy.add

numpy.subtract

numpy.multiply

numpy.divide

numpy.floor_divide

numpy.power

三、三角函數

numpy.sin

numpy.cos

numpy.tan

numpy.arcsin

numpy.arccos

numpy.arctan

四、邏輯函數

真值測試

numpy.all

numpy.any

陣列內容¶

numpy.isnan

邏輯運算

numpy.logical_not

numpy.logical_and

numpy.logical_or

numpy.logical_xor

五、對照

numpy.greater

numpy.greater_equal

numpy.equal

numpy.not_equal

numpy.less

numpy.less_equal

numpy.isclose

numpy.allclose

六、指數和對數

numpy.exp

numpy.log

numpy.exp2¶

numpy.log2

numpy.log10


 

函數描述用法
abs
fabs
計算 整型/浮點/複數 的絕對值
對於沒有複數的快速版本求絕對值
np.abs()
np.fabs()
sqrt計算元素的平方根。等價於array ** 0.5np.sqrt()
square計算元素的平方。等價於 array **2np.squart()
exp計算以自然常數e為底的冪次方np.exp()
log
log10
log2
log1p
自然對數(e)
基於10的對數
基於2的對數
基於log(1+x)的對數
np.log()
np.log10()
np.log2()
np.log1p()
sign計算元素的符號:1:正數 0:0 -1:負數np.sign()
ceil計算大於或等於元素的最小整數np.ceil()
floor計算小於或等於元素的最大整數np.floor()
rint對浮點數取整到最近的整數,但不改變浮點數型別np.rint()
modf分別返回浮點數的整數和小數部分的陣列np.modf()
isnan返回布林陣列標識哪些元素是 NaN (不是一個數)np.isnan()
isfinite
isinf
返回布林陣列標識哪些元素是有限的(non-inf, non-NaN)或無限的np.isfiniter()
np.isinf()
cos, cosh, sin sinh, tan, tanh三角函數 
arccos, arccosh, arcsin, arcsinh, arctan, arctanh反三角函數 
logical_and/or/not/xor邏輯與/或/非/互斥或 等價於 ‘&’ ‘|’ ‘!’ ‘^’測試見下方

 

# 邏輯與
>>> np.logical_and(True, False)
False
>>> np.logical_and([True, False], [False, False])
array([False, False], dtype=bool)

>>> x = np.arange(5)
>>> np.logical_and(x>1, x<4)
array([False, False,  True,  True, False], dtype=bool)

# 邏輯或
>>> np.logical_or(True, False)
True
>>> np.logical_or([True, False], [False, False])
array([ True, False], dtype=bool)

>>> x = np.arange(5)
>>> np.logical_or(x < 1, x > 3)
array([ True, False, False, False,  True], dtype=bool)

# 邏輯非
>>> np.logical_not(3)
False
>>> np.logical_not([True, False, 0, 1])
array([False,  True,  True, False], dtype=bool)

>>> x = np.arange(5)
>>> np.logical_not(x<3)
array([False, False, False,  True,  True], dtype=bool)

# 邏輯互斥或
>>> np.logical_xor(True, False)
True
>>> np.logical_xor([True, True, False, False], [True, False, True, False])
array([False,  True,  True, False], dtype=bool)

>>> x = np.arange(5)
>>> np.logical_xor(x < 1, x > 3)
array([ True, False, False, False,  True], dtype=bool)

>>> np.logical_xor(0, np.eye(2))
array([[ True, False],
       [False,  True]], dtype=bool)

一、向量化和廣播

向量化和廣播這兩個概念是 numpy 內部實現的基礎。有了向量化,編寫程式碼時無需使用顯式迴圈。這些迴圈實際上不能省略,只不過是在內部實現,被程式碼中的其他結構代替。向量化的應用使得程式碼更簡潔,可讀性更強,也可以說使用了向量化方法的程式碼看上去更「Pythonic」。

廣播(Broadcasting)機制描述了 numpy 如何在算術運算期間處理具有不同形狀的陣列,讓較小的陣列在較大的陣列上「廣播」,以便它們具有相容的形狀。並不是所有的維度都要彼此相容才符合廣播機制的要求,但它們必須滿足一定的條件。

若兩個陣列的各維度相容,也就是兩個陣列的每一維等長,或其中一個陣列為 一維,那麼廣播機制就適用。如果這兩個條件不滿足,numpy就會丟擲異常,說兩個陣列不相容。

總結來說,廣播的規則有三個:

  • 如果兩個陣列的維度數dim不相同,那麼小維度陣列的形狀將會在左邊補1。
  • 如果shape維度不匹配,但是有維度是1,那麼可以擴充套件維度是1的維度匹配另一個陣列;
  • 如果shape維度不匹配,但是沒有任何一個維度是1,則匹配引發錯誤;
二維陣列加一維陣列
 
import numpy as np
 
x = np.arange(4)
y = np.ones((3, 4))
print(x.shape)  # (4,)
print(y.shape)  # (3, 4)
 
print((x + y).shape)  # (3, 4)
print(x + y)
# [[1. 2. 3. 4.]
#  [1. 2. 3. 4.]
#  [1. 2. 3. 4.]]
兩個陣列均需要廣播
 
import numpy as np
 
x = np.arange(4).reshape(4, 1)
y = np.ones(5)
 
print(x.shape)  # (4, 1)
print(y.shape)  # (5,)
 
print((x + y).shape)  # (4, 5)
print(x + y)
# [[1. 1. 1. 1. 1.]
#  [2. 2. 2. 2. 2.]
#  [3. 3. 3. 3. 3.]
#  [4. 4. 4. 4. 4.]]
 
x = np.array([0.0, 10.0, 20.0, 30.0])
y = np.array([1.0, 2.0, 3.0])
z = x[:, np.newaxis] + y
print(z)
# [[ 1.  2.  3.]
#  [11. 12. 13.]
#  [21. 22. 23.]
#  [31. 32. 33.]]
不匹配報錯的例子
 
import numpy as np
 
x = np.arange(4)
y = np.ones(5)
 
print(x.shape)  # (4,)
print(y.shape)  # (5,)
 
print(x + y)
# ValueError: operands could not be broadcast together with shapes (4,) (5,) 

二、數學函數

算數運算

numpy.add

numpy.subtract

numpy.multiply

numpy.divide

numpy.floor_divide

numpy.power

  • numpy.add(x1, x2, *args, **kwargs) Add arguments element-wise.
  • numpy.subtract(x1, x2, *args, **kwargs) Subtract arguments element-wise.
  • numpy.multiply(x1, x2, *args, **kwargs) Multiply arguments element-wise.
  • numpy.divide(x1, x2, *args, **kwargs) Returns a true division of the inputs, element-wise.
  • numpy.floor_divide(x1, x2, *args, **kwargs) Return the largest integer smaller or equal to the division of the inputs.
  • numpy.power(x1, x2, *args, **kwargs) First array elements raised to powers from second array, element-wise.

在 numpy 中對以上函數進行了運運算元的過載,且運運算元為 元素級。也就是說,它們只用於位置相同的元素之間,所得到的運算結果組成一個新的陣列。

注意 numpy 的廣播規則。
 
import numpy as np
 
x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
y = x + 1
print(y)
print(np.add(x, 1))
# [2 3 4 5 6 7 8 9]
 
y = x - 1
print(y)
print(np.subtract(x, 1))
# [0 1 2 3 4 5 6 7]
 
y = x * 2
print(y)
print(np.multiply(x, 2))
# [ 2  4  6  8 10 12 14 16]
 
y = x / 2
print(y)
print(np.divide(x, 2))
# [0.5 1.  1.5 2.  2.5 3.  3.5 4. ]
 
y = x // 2
print(y)
print(np.floor_divide(x, 2))
# [0 1 1 2 2 3 3 4]
 
y = x ** 2
print(y)
print(np.power(x, 2))
# [ 1  4  9 16 25 36 49 64]
注意 numpy 的廣播規則。
 
import numpy as np
 
x = np.array([[11, 12, 13, 14, 15],
              [16, 17, 18, 19, 20],
              [21, 22, 23, 24, 25],
              [26, 27, 28, 29, 30],
              [31, 32, 33, 34, 35]])
y = x + 1
print(y)
print(np.add(x, 1))
# [[12 13 14 15 16]
#  [17 18 19 20 21]
#  [22 23 24 25 26]
#  [27 28 29 30 31]
#  [32 33 34 35 36]]
 
y = x - 1
print(y)
print(np.subtract(x, 1))
# [[10 11 12 13 14]
#  [15 16 17 18 19]
#  [20 21 22 23 24]
#  [25 26 27 28 29]
#  [30 31 32 33 34]]
 
y = x * 2
print(y)
print(np.multiply(x, 2))
# [[22 24 26 28 30]
#  [32 34 36 38 40]
#  [42 44 46 48 50]
#  [52 54 56 58 60]
#  [62 64 66 68 70]]
 
y = x / 2
print(y)
print(np.divide(x, 2))
# [[ 5.5  6.   6.5  7.   7.5]
#  [ 8.   8.5  9.   9.5 10. ]
#  [10.5 11.  11.5 12.  12.5]
#  [13.  13.5 14.  14.5 15. ]
#  [15.5 16.  16.5 17.  17.5]]
 
y = x // 2
print(y)
print(np.floor_divide(x, 2))
# [[ 5  6  6  7  7]
#  [ 8  8  9  9 10]
#  [10 11 11 12 12]
#  [13 13 14 14 15]
#  [15 16 16 17 17]]
 
y = x ** 2
print(y)
print(np.power(x, 2))
# [[ 121  144  169  196  225]
#  [ 256  289  324  361  400]
#  [ 441  484  529  576  625]
#  [ 676  729  784  841  900]
#  [ 961 1024 1089 1156 1225]]
注意 numpy 的廣播規則。
 
import numpy as np
 
x = np.array([[11, 12, 13, 14, 15],
              [16, 17, 18, 19, 20],
              [21, 22, 23, 24, 25],
              [26, 27, 28, 29, 30],
              [31, 32, 33, 34, 35]])
 
y = np.arange(1, 6)
print(y)
# [1 2 3 4 5]
 
z = x + y
print(z)
print(np.add(x, y))
# [[12 14 16 18 20]
#  [17 19 21 23 25]
#  [22 24 26 28 30]
#  [27 29 31 33 35]
#  [32 34 36 38 40]]
 
z = x - y
print(z)
print(np.subtract(x, y))
# [[10 10 10 10 10]
#  [15 15 15 15 15]
#  [20 20 20 20 20]
#  [25 25 25 25 25]
#  [30 30 30 30 30]]
 
z = x * y
print(z)
print(np.multiply(x, y))
# [[ 11  24  39  56  75]
#  [ 16  34  54  76 100]
#  [ 21  44  69  96 125]
#  [ 26  54  84 116 150]
#  [ 31  64  99 136 175]]
 
z = x / y
print(z)
print(np.divide(x, y))
# [[11.          6.          4.33333333  3.5         3.        ]
#  [16.          8.5         6.          4.75        4.        ]
#  [21.         11.          7.66666667  6.          5.        ]
#  [26.         13.5         9.33333333  7.25        6.        ]
#  [31.         16.         11.          8.5         7.        ]]
 
z = x // y
print(z)
print(np.floor_divide(x, y))
# [[11  6  4  3  3]
#  [16  8  6  4  4]
#  [21 11  7  6  5]
#  [26 13  9  7  6]
#  [31 16 11  8  7]]
 
z = x ** np.full([1, 5], 2)
print(z)
print(np.power(x, np.full([5, 5], 2)))
# [[ 121  144  169  196  225]
#  [ 256  289  324  361  400]
#  [ 441  484  529  576  625]
#  [ 676  729  784  841  900]
#  [ 961 1024 1089 1156 1225]]

三、三角函數

numpy.sin

numpy.cos

numpy.tan

numpy.arcsin

numpy.arccos

numpy.arctan

  • numpy.sin(x, *args, **kwargs) Trigonometric sine, element-wise.
  • numpy.cos(x, *args, **kwargs) Cosine element-wise.
  • numpy.tan(x, *args, **kwargs) Compute tangent element-wise.
  • numpy.arcsin(x, *args, **kwargs) Inverse sine, element-wise.
  • numpy.arccos(x, *args, **kwargs) Trigonometric inverse cosine, element-wise.
  • numpy.arctan(x, *args, **kwargs) Trigonometric inverse tangent, element-wise.

通用函數(universal function)通常叫作ufunc,它對陣列中的各個元素逐一進行操作。這表明,通用函數分別處理輸入陣列的每個元素,生成的結果組成一個新的輸出陣列。輸出陣列的大小跟輸入陣列相同。

三角函數等很多數學運運算元合通用函數的定義,例如,計算平方根的sqrt()函數、用來取對數的log()函數和求正弦值的sin()函數。

import numpy as np
 
x = np.linspace(start=0, stop=np.pi / 2, num=10)
print(x)
# [0.         0.17453293 0.34906585 0.52359878 0.6981317  0.87266463
#  1.04719755 1.22173048 1.3962634  1.57079633]
 
y = np.sin(x)
print(y)
# [0.         0.17364818 0.34202014 0.5        0.64278761 0.76604444
#  0.8660254  0.93969262 0.98480775 1.        ]
 
z = np.arcsin(y)
print(z)
# [0.         0.17453293 0.34906585 0.52359878 0.6981317  0.87266463
#  1.04719755 1.22173048 1.3962634  1.57079633]
 
y = np.cos(x)
print(y)
# [1.00000000e+00 9.84807753e-01 9.39692621e-01 8.66025404e-01
#  7.66044443e-01 6.42787610e-01 5.00000000e-01 3.42020143e-01
#  1.73648178e-01 6.12323400e-17]
 
z = np.arccos(y)
print(z)
# [0.         0.17453293 0.34906585 0.52359878 0.6981317  0.87266463
#  1.04719755 1.22173048 1.3962634  1.57079633]
 
y = np.tan(x)
print(y)
# [0.00000000e+00 1.76326981e-01 3.63970234e-01 5.77350269e-01
#  8.39099631e-01 1.19175359e+00 1.73205081e+00 2.74747742e+00
#  5.67128182e+00 1.63312394e+16]
 
z = np.arctan(y)
print(z)
# [0.         0.17453293 0.34906585 0.52359878 0.6981317  0.87266463
#  1.04719755 1.22173048 1.3962634  1.57079633]

四、邏輯函數

真值測試

numpy.all

numpy.any

  • numpy.all(a, axis=None, out=None, keepdims=np._NoValue) Test whether all array elements along a given axis evaluate to True.
  • numpy.any(a, axis=None, out=None, keepdims=np._NoValue) Test whether any array element along a given axis evaluates to True.
  • import numpy as np
     
    a = np.array([0, 4, 5])
    b = np.copy(a)
    print(np.all(a == b))  # True
    print(np.any(a == b))  # True
     
    b[0] = 1
    print(np.all(a == b))  # False
    print(np.any(a == b))  # True
     
    print(np.all([1.0, np.nan]))  # True
    print(np.any([1.0, np.nan]))  # True
     
    a = np.eye(3)
    print(np.all(a, axis=0))  # [False False False]
    print(np.any(a, axis=0))  # [ True  True  True]

     

陣列內容

numpy.isnan

  • numpy.isnan(x, *args, **kwargs) Test element-wise for NaN and return result as a boolean array.
a=np.array([1,2,np.nan])
print(np.isnan(a))
#[False False  True]

邏輯運算

numpy.logical_not

numpy.logical_and

numpy.logical_or

numpy.logical_xor

  • numpy.logical_not(x, *args, **kwargs)Compute the truth value of NOT x element-wise.
  • numpy.logical_and(x1, x2, *args, **kwargs) Compute the truth value of x1 AND x2 element-wise.
  • numpy.logical_or(x1, x2, *args, **kwargs)Compute the truth value of x1 OR x2 element-wise.
  • numpy.logical_xor(x1, x2, *args, **kwargs)Compute the truth value of x1 XOR x2, element-wise.
計算非x元素的真值。
 
import numpy as np
 
print(np.logical_not(3))  
# False
print(np.logical_not([True, False, 0, 1]))
# [False  True  True False]
 
x = np.arange(5)
print(np.logical_not(x < 3))
# [False False False  True  True]
計算x1 AND x2元素的真值。
 
print(np.logical_and(True, False))  
# False
print(np.logical_and([True, False], [True, False]))
# [ True False]
print(np.logical_and(x > 1, x < 4))
# [False False  True  True False]
逐元素計算x1 OR x2的真值。
 
 
print(np.logical_or(True, False))
# True
print(np.logical_or([True, False], [False, False]))
# [ True False]
print(np.logical_or(x < 1, x > 3))
# [ True False False False  True]
計算x1 XOR x2的真值,按元素計算。
 
print(np.logical_xor(True, False))
# True
print(np.logical_xor([True, True, False, False], [True, False, True, False]))
# [False  True  True False]
print(np.logical_xor(x < 1, x > 3))
# [ True False False False  True]
print(np.logical_xor(0, np.eye(2)))
# [[ True False]
#  [False  True]]

五、對照

numpy.greater

numpy.greater_equal

numpy.equal

numpy.not_equal

numpy.less

numpy.less_equal

  • numpy.greater(x1, x2, *args, **kwargs) Return the truth value of (x1 > x2) element-wise.
  • numpy.greater_equal(x1, x2, *args, **kwargs) Return the truth value of (x1 >= x2) element-wise.
  • numpy.equal(x1, x2, *args, **kwargs) Return (x1 == x2) element-wise.
  • numpy.not_equal(x1, x2, *args, **kwargs) Return (x1 != x2) element-wise.
  • numpy.less(x1, x2, *args, **kwargs) Return the truth value of (x1 < x2) element-wise.
  • numpy.less_equal(x1, x2, *args, **kwargs) Return the truth value of (x1 =< x2) element-wise.
import numpy as np
 
x = np.array([1, 2, 3, 4, 5, 6, 7, 8])
 
y = x > 2
print(y)
print(np.greater(x, 2))
# [False False  True  True  True  True  True  True]
 
y = x >= 2
print(y)
print(np.greater_equal(x, 2))
# [False  True  True  True  True  True  True  True]
 
y = x == 2
print(y)
print(np.equal(x, 2))
# [False  True False False False False False False]
 
y = x != 2
print(y)
print(np.not_equal(x, 2))
# [ True False  True  True  True  True  True  True]
 
y = x < 2
print(y)
print(np.less(x, 2))
# [ True False False False False False False False]
 
y = x <= 2
print(y)
print(np.less_equal(x, 2))
# [ True  True False False False False False False]

numpy.isclose

numpy.allclose

  • numpy.isclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False) Returns a boolean array where two arrays are element-wise equal within a tolerance.
  • numpy.allclose(a, b, rtol=1.e-5, atol=1.e-8, equal_nan=False) Returns True if two arrays are element-wise equal within a tolerance.

numpy.allclose() 等價於 numpy.all(isclose(a, b, rtol=rtol, atol=atol, equal_nan=equal_nan))

The tolerance values are positive, typically very small numbers. The relative difference (rtol * abs(b)) and the absolute difference atol are added together to compare against the absolute difference between a and b.

判斷是否為True的計算依據:
 

np.absolute(a - b) <= (atol + rtol * absolute(b))
 
- atol:float,絕對公差。
- rtol:float,相對公差。
np.absolute(a - b) <= (atol + rtol * absolute(b))

- atol:float,絕對公差。
- rtol:float,相對公差。

NaNs are treated as equal if they are in the same place and if equal_nan=True. Infs are treated as equal if they are in the same place and of the same sign in both arrays.

比較兩個陣列是否可以認為相等。
 
import numpy as np
 
x = np.isclose([1e10, 1e-7], [1.00001e10, 1e-8])
print(x)  # [ True False]
 
x = np.allclose([1e10, 1e-7], [1.00001e10, 1e-8])
print(x)  # False
 
x = np.isclose([1e10, 1e-8], [1.00001e10, 1e-9])
print(x)  # [ True  True]
 
x = np.allclose([1e10, 1e-8], [1.00001e10, 1e-9])
print(x)  # True
 
x = np.isclose([1e10, 1e-8], [1.0001e10, 1e-9])
print(x)  # [False  True]
 
x = np.allclose([1e10, 1e-8], [1.0001e10, 1e-9])
print(x)  # False
 
x = np.isclose([1.0, np.nan], [1.0, np.nan])
print(x)  # [ True False]
 
x = np.allclose([1.0, np.nan], [1.0, np.nan])
print(x)  # False
 
x = np.isclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
print(x)  # [ True  True]
 
x = np.allclose([1.0, np.nan], [1.0, np.nan], equal_nan=True)
print(x)  # True

六、指數和對數

numpy.exp

numpy.log

numpy.exp2

numpy.log2

numpy.log10

  • numpy.exp(x, *args, **kwargs) Calculate the exponential of all elements in the input array.
  • numpy.log(x, *args, **kwargs) Natural logarithm, element-wise.
  • numpy.exp2(x, *args, **kwargs) Calculate 2**p for all p in the input array.
  • numpy.log2(x, *args, **kwargs) Base-2 logarithm of x.
  • numpy.log10(x, *args, **kwargs) Return the base 10 logarithm of the input array, element-wise.
The natural logarithm log is the inverse of the exponential function, so that log(exp(x)) = x. The natural logarithm is logarithm in base e.
 
import numpy as np
 
x = np.arange(1, 5)
print(x)
# [1 2 3 4]
y = np.exp(x)
print(y)
# [ 2.71828183  7.3890561  20.08553692 54.59815003]
z = np.log(y)
print(z)
# [1. 2. 3. 4.]