Python

(Python) 소수 연산

Accept 2024. 3. 6. 23:20

1. 반올림, 버림, 올림

# 반올림
s = 123.4567
rounded_s = round(s, 2) # 소수점 아래 2자리까지 반올림
print(rounded_s)  # 출력: 123.46

# 올림
ceiled = math.ceil(3.14159)  # 4

# 버림
import math
floored = math.floor(3.14159)  # 3

# 절삭1
truncated = int(3.14159)  # 3

# 절삭2
import math
truncated = math.trunc(3.14159)  # 3

 

2. 정밀한 소수 연산

from decimal import Decimal, getcontext

getcontext().prec = 10  # 정밀도 설정
result = Decimal('1.1') + Decimal('2.2')
print(result)  # 출력: 3.300000000

 

3. 대규모 배열의 소수 처리

import numpy as np

arr = np.array([1.1, 2.2, 3.3])
result = arr * 2
print(result)  # 출력: [2.2 4.4 6.6]

'Python' 카테고리의 다른 글

(Python) 비트 단위 논리 연산자  (0) 2024.03.10
(Python) 유니코드 변환  (0) 2024.02.02
(Python) 진수 표기법  (0) 2024.02.01
(Python) 특수 문자 다루기  (0) 2024.02.01
(Python) math  (1) 2024.01.30