[Python] A story that seemed to fall into a rounding trap

Introduction

When I was implementing a trial calculation using Python in my business, I was about to get caught in a trap.

I just wanted to round ...

"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 ... "

This is the main subject of the farce

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?

I investigated

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 ...

Solution

@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

[Python] A story that seemed to fall into a rounding trap
A story that struggled to handle the Python package of PocketSphinx
A story that I was addicted to when I made SFTP communication with python
Python that merges a lot of excel into one excel
[Python] How to write a docstring that conforms to PEP8
A story that I was addicted to at np.where
[Python] A convenient library that converts kanji to hiragana
A Python program that converts ical data into text
A story that got stuck when trying to upgrade the Python version on GCE
A story that took time to understand python's argsort (memorial)
A road to intermediate Python
A function that divides iterable into N pieces in Python
A Python script that saves a clipboard (GTK) image to a file.
A story about how to specify a relative path in python.
How to write a metaclass that supports both python2 and python3
A story about trying to implement a private variable in Python.
A python script that converts Oracle Database data to csv
A story that didn't work when I tried to log in with the Python requests module
How to turn ugly code into plain code that isn't a beautiful object-oriented design with Python refactoring
A story that I was addicted to calling Lambda from AWS Lambda.
The story that the version of python 3.7.7 was not adapted to Heroku
A story that Qiita really wanted to see under a proxy environment
I want to use a wildcard that I want to shell with Python remove
How to make a string into an array or an array into a string in Python
A story about adding a REST API to a daemon made with Python
[Python] A memo that I tried to get started with asyncio
A story that was struggling to loop processing 3 million ID data
A story about trying to run multiple python versions (Mac edition)
A special Python codec that seems to know but does not know
A script that returns 0, 1 attached to the first Python prime number
A quick guide to PyFlink that combines Apache Flink and Python
I made a library that adds docstring to a Python stub file.
[python] A note that started to understand the behavior of matplotlib.pyplot
The story of making a module that skips mail with python
[Python] A program that rotates the contents of the list to the left
How to write a Python class
5 Ways to Create a Python Chatbot
[Python] I made a decorator that doesn't seem to have any use.
[Python] A program that calculates the number of socks to be paired
A story I was addicted to when inserting from Python to a PostgreSQL table
A memo that allows you to change Pineapple's Python environment with pyenv
A python program that resizes a video and turns it into an image
How to use hmmlearn, a Python library that realizes hidden Markov models
A story that suffered from OS differences when trying to implement a dissertation
[Python] A program that creates stairs with #
[Python] Use pandas to extract △△ that maximizes ○○
A story about remodeling Lubuntu into a Chromebook
[Python] How to make a class iterable
[Python] How to convert a 2D list to a 1D list
A super introduction to Python bit operations
Send a message from Python to Slack
A story that stumbled upon a comparison operation
Sample script to trap signals in Python
I want to build a Python environment
[Python] How to invert a character string
How to get a stacktrace in python
10 Python errors that are common to beginners
[Python] Create a LineBot that runs regularly
A story about Python pop and append
A typed world that begins with Python
The story of blackjack A processing (python)