수치해석을 위한 Python
13 Apr 2023 -
5 minute read
작성자 : 김지은
수치해석을 위한 Python
1. Python 문법
-
리스트(lists)
# 데이터를 저장한 후 출력하는 Python 프로그램 x = [0, 1, 2, 3] y = [1.2, 3.7, 1.5] print('x = ', x) # x = [0, 1, 2, 3] print('y = ', y) # y = [1.2, 3.7, 1.5]
-
range 함수
# 리스트 구조를 만들어주는 range 함수에 대한 프로그램 a = range(0, 10, 2) # range(처음, 끝, 간격)의 형태 b = range(0, 5) print('a = ', list(a)) # a = [0, 2, 4, 6, 8] print('b = ', list(b)) # b = [0, 1, 2, 3, 4]
-
반복을 위한 for
# 알고리즘에 반복구조를 만들어주는 for에 대한 프로그램 for i in range(0, 5): # 문장 끝에 콜론:을 반드시 작성 print(i) # 들여쓰기 하지 않으면 오류 발생
Python 프로그램 작성시 유의점
Python은 직관적이며 간결해서 다른 컴퓨터 언어에 비해서 배우기 쉬운 언어이다. 다만 처음으로 입문하는 사람들이 많이 겪게 되는 오류 중의 하나는 여백과 들여쓰기를 무시하는 것이다. 들여쓰기 자체가 Python 문법이기에 무시하면 안된다.
2. Nympy
왜 Numpy를 사용하는가?
본격적인 수치해석에서의 연산을 수행하기 위해서는 다차원의 배열과 또는 벡터를 보다 수월하게 다룰 수 있는 방식이 필요하다. Numpy는 배열과 행렬 연산을 위한 매우 효율적인 Python 라이브러리이다
벡터와 행렬 만들기
# array 함수를 사용하여 배열구조로 만들어주는 프로그램
from numpy import array # Numpy를 불러오는 방법
alist = [0, 1, 2, 3, 4]
yvector = array(alist)
avector = array([0, 1, 2, 3, 4])
print(yvector) # [0 1 2 3 4]
print(avector) # [0 1 2 3 4]
print(len(avector)) # 5
# array 함수를 사용하여 3 x 3 행렬을 만들어주는 프로그램
from numpy import array
amat = array([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
print(amat.shape) # (3, 3)
arange / linspace 함수
# arange 함수를 사용하여 배열을 만들어주는 프로그램
from numpy import arange
brange = arange(5)
crange = arange(0, 10, 3)
print(brange) # [0 1 2 3 4]
print(crange) # [0 3 6 9]
# linspace 함수를 사용하여 배열을 만들어주는 프로그램
from numpy import linspace
aspace = linspace(0, 1, 5) # 등간격 배열 생성
print(aspace) # [0. 0.25 0.5 0.75 1. ]
ones/zeros/eye 함수
# ones, zeros, eye 함수의 사용 예
from numpy import ones, zeros, eye
aones = ones((3, 3)) # 3행 3열의 2차원 배열을 1로 초기값 설정
azeros = zeros((3, 3)) # 3행 3열의 2차원 배열을 0 으로 초기화
aeye = eye(3) # 3행 3열의 단위행렬
print('ones = ', aones)
print('zeros = ', azeros)
print('eye = ', aeye)
'''
ones = [[1. 1. 1.]
[1. 1. 1.]
[1. 1. 1.]]
zeros = [[0. 0. 0.]
[0. 0. 0.]
[0. 0. 0.]]
eye = [[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
'''
행렬연산
#행렬연산의 예
from numpy import array
A = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
B = array([[-1, 1, 2], [5, 4, 2], [3, 1, -2]])
madd = A + B
msub = A - B
print('A+B = ', madd)
print('A-B = ', msub)
mult = A * 10.0
divi = A / 2.0
print('A*10 = ', mult)
print('A/2 = ', divi)
'''
A+B = [[ 0 3 5]
[ 9 9 8]
[10 9 7]]
A-B = [[ 2 1 1]
[-1 1 4]
[ 4 7 11]]
A*10 = [[10. 20. 30.]
[40. 50. 60.]
[70. 80. 90.]]
A/2 = [[0.5 1. 1.5]
[2. 2.5 3. ]
[3.5 4. 4.5]]
'''
내적(inner products)과 행렬 곱
# 벡터 내적의 예
from numpy import array
a = array([1, 2])
b = array([3, 4])
dots = a.dot(b)
print(dots) # 11
# 행렬의 내적과 행렬 곱의 예
from numpy import array, dot
A = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
B = array([[-1, 1, 2], [5, 4, 2], [3, 1, -2]])
mmt = A * B
dotp = A.dot(B)
print('matrix multiplication = ', mmt)
print('dot product = ', dotp)
'''
matrix multiplication = [[ -1 2 6]
[ 20 20 12]
[ 21 8 -18]]
dot product = [[18 12 0]
[39 30 6]
[60 48 12]]
'''
조회 (indexing)
# 행렬에서의 요소의 조회
from numpy import array
a = array([1, 2, 3, 4, 5])
print('a[1] = ', a[1]) # a[1] = 2
print('a[3] = ', a[3]) # a[3] = 4
print('a[-1] = ', a[-1]) # a[-1] = 5
# 행렬에서의 요소의 조회
from numpy import array
A = array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(A[1,1]) # 5
print(A[2,1]) # 8
추출 (slicing)
# 행렬에서 요소의 추출
from numpy import array
a = array([0,1,2,3,4,5,6,7,8])
print('a[1:5] = ', a[1:5]) # a[1:5] = [1 2 3 4]
print('a[:3] = ', a[:3]) # a[:3] = [0 1 2]
벡터화 기법
# 벡터화 기법을 적용하지 않은 경우
from numpy import linspace, zeros, cos
x = linspace(0, 2, 10)
n = len(x)
y = zeros(n)
for i in range(n):
y[i] = cos(x[i])
print('%8.4f ' %y[i])
'''
1.0000
0.9754
0.9028
0.7859
0.6303
0.4437
0.2352
0.0152
-0.2055
-0.4161
'''
# 벡터화 기법을 적용한 경우
from numpy import linspace, zeros, cos
x = linspace(0, 2, 10)
y = cos(x)
print(y)
'''
[ 1. 0.97541009 0.90284967 0.78588726 0.63027505 0.44366602
0.23523757 0.01524018 -0.20550672 -0.41614684]
'''
3. Matplotlib
Matplotlib?
Matplotlib는 그림 그리기에 특화된 Python 라이브러리로서 Numpy와 함께 가장 널리 사용되고 있다.
Cosine function (1)
# y = cos(x)을 그리는 프로그램
from numpy import linspace, cos, pi
import matplotlib.pyplot as plt
x = linspace(0, 2.0*pi, 40)
y = cos(x)
plt.plot(x, y, 'k')
plt.show()
Cosine function (2)
# y = cos(x)을 그리고, 각 축에 명칭을 표시하는 프로그램
from numpy import linspace, cos, pi
import matplotlib.pyplot as plt
x = linspace(0, 2.0*pi, 40)
y = cos(x)
plt.plot(x,y)
plt.xlabel('x') # x축 이름
plt.ylabel('y') # y축 이름
plt.title('y = cos(x)') # 표 이름
plt.show()
Cosine and sine function
# y = cos(x)과 y = sin(x)를 그리고 명칭을 표시하는 프로그램
from numpy import linspace, cos, sin, pi
import matplotlib.pyplot as plt
x = linspace(0, 2.0*pi, 40)
yc = cos(x)
ys = sin(x)
plt.plot(x, yc, 'ko-', label='cos(x)')
plt.plot(x, ys, 'k--', label='sin(x)')
plt.legend()
plt.xlabel('x')
plt.ylabel('y')
plt.title('y = cos(x) & sin(x)')
plt.show()
데이터를 사용하여 그리기
# 데이터를 그리는 프로그램from numpy import array
import matplotlib.pyplot as plt
x = array([0, 1, 3, 7, 8])
y = array([1.1, 2.5, -0.7, 3.0, 2.9])
plt.plot(x, y, 'ko-')
plt.xlabel('x')
plt.ylabel('y')
plt.show()