Chapter2 Arithmetic Operations: Notebook2 ndarray Multiplication, Division and Modulo
우리가 Python에서 사용하는 Multiplication과 Division,Modulo는 각각 다음과 같다.
import numpy as np
Python List¶
operand1 = 10
operand2 = 3
print(operand1 * operand2)
print(operand1 / operand2)
print(operand1 % operand2)
그러면 list를 이용하여 이 연산이 가능할지 알아보자.
operand1 = [10, 20, 30, 40, 50]
operand2 = [3, 3, 3, 3, 3]
print(operand1 * operand2)
print(operand1 / operand2)
print(operand1 % operand2)
위에서 볼 수 있듯이, python list는 말그대로 list이고 vector가 아니기 때문에 우리가 원하는 결과를 얻기 힘들다.
만약 우리가 broadcating을 생각해서 다음과 같이 연산하려고 한다고 해보자.
operand1 = [10, 20, 30, 40, 50]
operand2 = 3
print(operand1 * operand2)
print(operand1 / operand2)
print(operand1 % operand2)
Python list의 *연산은 list를 반복하는 연산이므로 원하는 결과가 아니고, division, modulo 연산은 아예 사용할 수 없다. 즉, NumPy를 이용하지 않고 이런 vector operation을 하려고 한다면 우리는 Python에게 너무 많은 것을 바라고 있는 것이다.
ndarray Multiplication, division and Modulo¶
ndarray를 사용해보자. 이때 broadcating과 조금 더 친해지기 위해 앞으로 broadcating을 사용해보도록 한다.
operand1 = np.array([10, 20, 30, 40, 50])
operand2 = 3
print(operand1 * operand2)
print(operand1 / operand2)
print(operand1 % operand2)
위와 같이 우리가 원하는 vector operation을 할 수 있다.
이때 정말 중요한 점은 element-wise operation인 점이다. 즉, ndarray의 *연산은 우리가 아는 veoctor의 dot product가 아니다. 각각 element마다의 연산을 해주는 element-wise operation이라는 것을 꼭 기억하자.
operand1 = np.random.randint(low = 0, high = 10, size = (3,4))
operand2 = np.array([3, 4, 5]).reshape(3,1)
print("====== Original Operands =======")
print("operand1:\n", operand1)
print("operand2:\n", operand2)
print("operand1.shape:", operand1.shape, "operand2.shape:", operand2.shape, '\n\n')
print("operand1 * operand2:\n", operand1 * operand2)
print("operand1 / operand2:\n", operand1 / operand2)
print("operand1 % operand2:\n", operand1 % operand2)
위의 결과로 알 수 있듯이, addition, subtraction 외에도 multiplication, division, modulo operation들도 모두 동일하게 작동하는 것을 확인할 수 있다.