이진수 대신 십진수를 쓰면 오차가 없어질까?

algorithms
featured
float
decimal
python
Author

Yunho Kee

Published

May 26, 2024

Intro

정수 아닌 실수 연산은 오차 관리가 더 힘들다. 십진수를 쓰면 문제가 없을까?

정수 오차

저장 용량에 따른 자릿수를 초과하면 이진법이나 십진법이나 오차가 있다.

실수 오차

정수 아닌 실수도 마찬가지인데 소수점 이하 자릿수가 무한일 수 있다: 무한소수.

four = (7 - 10 / 6 * 3) * 2
print(four)
print(int(four))
4.0
4
from decimal import Decimal, ROUND_DOWN

four = (Decimal('7') - Decimal('10') / Decimal('6') * Decimal('3')) * 2
print(four)
print(int(four))
print(four.quantize(Decimal('0'), ROUND_DOWN))
3.999999999999999999999999998
3
3

오차 관리

소수점 이하 무한한 자릿수가 모두 필요할 일은 거의 없다. 가령 소수점 이하 n번째 자리까지 필요하다면 그보다 작은 수를 가령 n + 1번째 자리에 1을 더하거나 빼 주면 된다. 더할 때는 절삭, 절하, 내림, ROUND_DOWN이나 ROUND_HALF_UP이 필요할 때이다. 뺄 때는 절상, 올림, ROUND_UP이나 ROUND_HALF_DOWN이 요구될 때이다.

_EPSILON = 1e-2

four = (7 - 10 / 6 * 3) * 2 + _EPSILON
print(four)
print(int(four))
4.01
4
from decimal import Decimal, ROUND_DOWN

_EPSILON = Decimal('1e-2')

four = (Decimal('7') - Decimal('10') / Decimal('6') * Decimal('3')) * 2 + _EPSILON
print(four)
print(int(four))
print(four.quantize(Decimal('0'), ROUND_DOWN))
4.009999999999999999999999998
4
4
Back to top

Citation

BibTeX citation:
@online{kee2024,
  author = {Kee, Yunho},
  title = {이진수 대신 십진수를 쓰면 오차가 없어질까?},
  date = {2024-05-26},
  url = {https://yhkee0404.github.io/posts/algorithms/decimal-round-down},
  langid = {ko}
}
For attribution, please cite this work as:
Kee, Yunho. 2024. “이진수 대신 십진수를 쓰면 오차가 없어질까?” May 26, 2024. https://yhkee0404.github.io/posts/algorithms/decimal-round-down.