Numpy 基本除法運算和模運算


基本算術運算符+、-和*隱式關聯着通用函數add、subtract和multiply

在數組的除法運算中涉及三個通用函數divide、true_divide和floor_division,以及兩個對應的運算符/和//

 

1. 數組的除法運算

import numpy as np


# divide函數在整數和浮點數除法中均只保留整數部分(python3中的np.divide == np.true_divide)

a = np.array([2,6,5])
b = np.array([1,2,3])
print (np.divide(a,b),np.divide(b,a))
# (array([2, 3, 1]), array([0, 0, 0]))


# true_divide函數與數學中的除法定義更為接近,即返回除法的浮點數結果而不作截斷

print (np.true_divide(a,b),np.true_divide(b,a))
# (array([ 2. , 3. , 1.66666667]), array([ 0.5 , 0.33333333, 0.6 ]))

  

# floor_divide函數總是返回整數結果,相當於先調用divide函數再調用floor函數(floor函數將對浮點數進行向下取整並返回整數)

print (np.floor_divide(a,b),np.floor_divide(b,a))
# [2 3 1] [0 0 0]
c = 3.14 * b
print (np.floor_divide(c,b),np.floor_divide(b,c))
# [ 3. 3. 3.] [ 0. 0. 0.]

  

# /運算符相當於調用divide函數

print (a/b,b/a)
# (array([2, 3, 1]), array([0, 0, 0]))

  

# 運算符//對應於floor_divide函數

print (a//b,b//a)
# [2 3 1] [0 0 0]
print (c//b,b//c)
# [ 3. 3. 3.] [ 0. 0. 0.]

  

 

2. 模運算
# 計算模數或者余數,可以使用NumPy中的mod、remainder和fmod函數。也可以用%運算符

import numpy as np

# remainder函數逐個返回兩個數組中元素相除后的余數

d = np.arange(-4,4)
print (np.remainder(d,2))
# [0 1 0 1 0 1 0 1]

  

# mod函數與remainder函數的功能完全一致

print (np.mod(d,2))
# [0 1 0 1 0 1 0 1]

  

# %操作符僅僅是remainder函數的簡寫(功能一樣)

print ( d % 2 )
# [0 1 0 1 0 1 0 1]

  

# fmod函數處理負數的方式與remainder、mod和%不同。所得余數的正負由被除數決定,與除數的正負無關

print (np.fmod(d,2))
# [ 0 -1 0 -1 0 1 0 1]

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM