파이썬 round() 함수 문제점
round()는 반올림을 의미함. 당연히 round(1.5) 면 2 가 되어야... Matlab 등에서는 잘 작동한다. 그런데...
검색을 해 보니 python 3 에서부터 있는 문제라 함. 심지어 3.10 에서도 같은 문제 발생. -_-;;
https://medium.com/thefloatingpoint/pythons-round-function-doesn-t-do-what-you-think-71765cfa86a8
Python’s round() Function Doesn’t do What You Think
How to avoid this simple mistake with round() in Python 3
medium.com
해결책은 다음과 같은 함수를 만들어 사용해야...
# python 3 rounding error solution
def normal_round(num, ndigits=0):
"""
Rounds a float to the specified number of decimal places.
num: the value to round
ndigits: the number of digits to round to
"""
if ndigits == 0:
return int(num + 0.5)
else:
digit_value = 10 ** ndigits
return int(num * digit_value + 0.5) / digit_value