When I was implementing a trial calculation using Python in my business, I was about to get caught in a trap.
"Oh, I'll tell you what happened right now!"
** "I thought I was rounding off" 2.5 "to" 3 ", but before I knew it, it was" 2 "" **
"Well, I don't know what you're talking about, but I didn't know what you were doing ..."
"How pretty my head was ... If it's a calculation error or a misunderstanding, it's such a chaotic thing. I tasted something more scary ... "
As I said earlier, I wanted to round off in Python.
The first thing that comes to mind ** round function ** ** format function **
"Well, if you use it here and there, you can afford it."
The thought was suddenly shattered ...
>>> k=2.5
>>> round(k)
2
"e"
At this time, my brain was filled with distrust of rounding, which I should have learned in compulsory education at that time.
** "When did you get the illusion that 2.5 would be 3 by rounding?" **
No no no no
If you round off "2.5", it's "3".
But why?
Let's try it with the format function
>>> format(k, '.0f')
'2'
How. Are you guru?
But why?
When I look it up This person was investigating and suggested a ** solution ** as well. ↓ ↓ ↓ Note because I was addicted to rounding python3
In this article, it was found that the cause was ** rounding to even numbers **.
Round to nearest even number [edit] Round to the nearest even (RN) is rounded down if the fraction is less than 0.5, rounded up if the fraction is greater than 0.5, and rounded down or rounded up if the fraction is exactly 0.5. Round to. It is defined as Rule A in JIS Z 8401 and is considered "desirable" from Rule B (rounding). Bias occurs in rounding, even if there is a finite proportion of data with a fraction of 0.5, it is characterized by no bias, and even if a large number are added, the rounding error does not accumulate biased to a specific side (even + If the data has characteristics such as 0.5 appears but odd +0.5 does not appear, bias will still appear). See also: Wikipedia-Rounding
It seems that 0.5 can be rounded up to Python2 Python 3 is like this.
In other words If you set it to "2.5", it will be "2" on the even side.
So if you do it with "3.5", it will be "4".
>>> k=3.5
>>> round(k)
4
Where is the demand for this specification ...
@Shiracamus suggested a solution to the article I introduced earlier.
def round(x):
return (x*2+1)//2
def round(x,d=0): #Do this when specifying the number of digits
p=10**d
return (x*p*2+1)//2/p
This solved it. @ sak_2 @shiracamus Thank you very much.
Please be careful, too.
Recommended Posts