데이터 타입: 숫자형
- 데이터 타입
# math 외부 모듈
import math
기타 math 함수: https://docs.python.org/3/library/math.html
math — Mathematical functions — Python 3.10.1 documentation
math — Mathematical functions This module provides access to the mathematical functions defined by the C standard. These functions cannot be used with complex numbers; use the functions of the same name from the cmath module if you require support for co
docs.python.org
+ 추가
- 반올림: round()
:round() 함수는 소숫점 값이 5이상부터 올림을 적용한다. 그러나 python3부터 round to nearest even이라고 해서 정수부분이 짝수일 경우 가까운 짝수를 만들기 위해 소숫점 값이 5이더라도 그 값을 버린다.
예로 들면
print(round(4.4))는 4를 출력,
print(round(4.5))는 4를 출력,
print(round(4.6))는 5를 출력,
print(round(3.4))는 3를 출력,
print(round(3.5))는 4를 출력,
print(round(3.6))는 4를 출력한다.
반올림하고 싶은 자리수를 지정하고 싶을 경우, 하이퍼파라미터로 소숫점아래 몇번째 자리에서 반올림하고 싶은지 속성값으로 지정한다.
예로 들어 print(round(3.141592, 2))로 작성하면 3.141592의 소숫점 아래 두번째 자리에서 반올림한 값을 반영하고 싶다는 뜻이고 그 출력값은 3.14가 된다. (참고로 print(round(3.15, 1))의 값은 3.2로 출력된다.)
- 올림: math.ceil()
사용법은 round와 유사. 단 자릿수를 설정할 수 없다.
- 내림: math.truncate(), math.floor()
truncate는 0의 방향으로 내림을 하고, floor는 일반적으로 알고있는 내림을 한다.
예로 들어
math.truncate(-3.14)는 -3을 출력하고
math.floor(3.14)sms -4를 출력한다.
- 나눗셈: divmod(v1, v2)
몫과 나머지를 구하는 또다른 나눗셈 방법 중 하나. 큰 수의 나눗셈을 할 때 속도면에서 //나 %보다 좋다.
튜플값으로 (몫, 나머지)를 반환한다.