기초"수학"에 대해 배워보도록하겠습니다.
그중 오늘은 기초수학중 자연수와 정수에 대해 간단하게 알아보려고 합니다.
Python에서 수학적 개념을 다룰 때 자주 사용하는 모듈은 Numpy가 있습니다
특징으로는
input
import numpy as np
print(np.sqrt(100))
print(np.sqrt(-4)) # not a number
output
10.0
nan
import [모듈이름] as [별명]을 사용하여 numpy를 np로 인식하게끔 바꾸어 줍니다.
sqrt는 numpy 모듈에 들어있는 제곱근을 구해주는 함수이므로 100의 제곱근인 10이 나오고,
-4는 제곱근이 없으므로 NAN처리가 되었습니다.
input
a=3.7
print(a)
print(type(a))
b=round(a)
print(b)
print(type(b))
output
3.7
<class 'float'>
4
<class 'int'>
round는 반올림을 해주는 함수이므로, 반올림 후 자료형이 int 바뀐것을 확인 할 수 있습니다.
input
a=3.7
print(a)
b=int(a) #정수로 변환
print(b)
print(float(b)) #실수로 변환
output
3.7
3
3.0
정수에서 실수로 실수에서 정수로 변경 또한 가능합니다.
input
a=[1,2,3,4,5]
print(min(a),max(a)) #최소,최대
output
1 5
input
a=[1,2,3]
b=[4,5,6]
c=[]
d=[]
e=[]
f=[]
for i in range(3):
c.append(a[i]+b[i])
d.append(a[i]-b[i])
e.append(a[i]*b[i])
f.append(a[i]/b[i])
print(c)
print(d)
print(e)
print(f)
output
[5, 7, 9][-3, -3, -3]
[4, 10, 18][0.25, 0.4, 0.5]
.append함수를 이용하여 빈 배열에 각 값을 넣을 수 있습니다.
input
a=np.array([1,2,3]) # 리스트를 넘파이배열로 변환
b=np.array([4,5,6])
print(np.multiply(a,b)) # 곱셈
print(np.max(a))
print(np.min(b))
print(np.argmax(a)) #최대값의 인덱스
print(np.argmin(b)) #최소값의 인덱스
output
[ 4 10 18]
3
4
2
0
넘파이 배열로 바꾸어준다면 바로 계산이 가능합니다.
input
import numpy as np
np.random.seed(100)
print(np.random.randint(9)) # 0~9미만의 정수난수
print(np.random.randint(100,150,size=5)) # 100~150미만의 5개의 정수난수
output
8
[124 103 139 123 115]
Random함수를 이용하여 난수(랜덤한 수)를 생성할 수 있습니다.
이상으로 파이썬을 사용하여 수학적 계산을 도와주는 Numpy에 대해 배워 보았습니다.
다음 시간에는 그래프에대해 배워보도록 하겠습니다.