Python round is not strictly round

round function

I think I would use the round function when I wanted to turn a number with a decimal into an integer, but it's not exactly a rounding function. Specifically, it is as follows.

>>> round(3.5) #I want you to be 4
4              #Become 4
>>> round(2.5) #I want you to be 3
2              #Become 2(<-??)
>>> round(2.50000001) #I want you to be 3
3              #Become 3

This is also mentioned in the Official Documentation (https://docs.python.org/ja/3/library/functions.html?highlight=round#round), to (even) +0.5 when rounding to an integer. When it is, it is not rounded up and is rounded down. This is due to the nature of the bank rounding algorithm, and other cases do not seem to change when rounding to an integer. (Corrected after being pointed out by @shiracamus at 12:21 on 9/5/2020)

numpy round

If the built-in function round is not good, you should use numpy round, but numpy round gives the same result. This is also described in the Official Documentation.

>>> import numpy as np
>>> np.round(3.5)   #I want you to be 4
4.0                 #Become 4
>>> np.round(2.5)   #I want you to be 3
2.0                 #Become 2

approach

There is no problem because you can use the if statement to multiply round by one number, but if you turn the for statement for numpy's ndarray and turn it one by one, the code becomes redundant. If you do the following, 2.5 and 4.5 will also be rounded correctly.

my_Definition of round function


def my_round(a:np.ndarray) -> np.ndarray:
    rounded_a = np.round(a)+(((a%1)==0.5)*(a//1%2==0))
    return rounded_a

When I run it, it looks like this

>>> a = np.arange(-3,3,0.5)
>>>print(a)
[-3.  -2.5 -2.  -1.5 -1.  -0.5  0.   0.5  1.   1.5  2.   2.5]
>>>print(np.round(a))
[-3. -2. -2. -2. -1. -0.  0.  0.  1.  2.  2.  2.]
>>>print(my_round(a))
[-3. -2. -2. -1. -1.  0.  0.  1.  1.  2.  2.  3.]

You can see that it is rounded correctly.

What you are doing

What ((a% 1) == 0.5) * (a // 1% 2 == 0) is doing is (a% 1) == 0.5 in the form of * .5 By creating an array where 1 stands only where it is, and by creating an array where 1 stands only where the integer part is even at ʻa // 1% 2 == 0` and multiplying them, ( It's a straightforward way to add 1 only where it's even) .5. This method doesn't use a for statement (which is said to be slow in python), so it's expected to be a bit faster than doing it straightforwardly with for.

Recommended Posts

Python round is not strictly round
Python list is not a list
python note: when easy_install is not available
[Python] Name Error: name'urlparse' is not defined
Python is easy
What is python
Python is instance
What is Python
Python Pandas is not suitable for batch processing
Python log is not output with docker-compose up
python int is infinite
[Python] What is Pipeline ...
Python Not Implemented Error
Python3> round (a --b, 7)
[Python] What is virtualenv
[Python] Lint pylint is not installed is displayed [VS Code]
python> check NoneType or not> if a == None:> if a is None:
Python memo using perl-Dictionary type (case is not valid)
[Python] Debugging is more efficient!
Is time.time () not very accurate?
Test.py is not reflected on the web server in Python3.
TypeError:'int' object is not subscriptable
How Python __dict__ is used
filter rollbar python 404 not found
Python is painful. But use
Python is an adult language
Python version does not switch
[Python] Python and security-① What is Python?
Python release cycle is faster!
Python Boolean operation return value is not always bool type
[Python] * args ** What is kwrgs?
[Python] Not just count collections.Counter
Identity and equivalence Python is and ==
pip install scikit-learn says Numerical Python (NumPy) is not installed.
NameError: name'__file__' is not defined
What is a python map?
Python Basic Course (1 What is Python)
Build Python environment on Ubuntu (when pip is not the default)
[Python] What is a zip function?
[Python] What is a with statement?
Python Note: About comparison using is
ppa: jonathonf / python-3.6 is now private
Difference between == and is in python
Use fabric as is in python (fabric3)
Golang vs. Python – Is Golang Better Than Python?
Command is not found in sudo
Python is UnicodeEncodeError in CodeBox docker
[Python] What is @? (About the decorator)
Which is better, PyPy or Python?
[python] What is the sorted key?
Python for statement ~ What is iterable ~
There is no switch in python
[Django error]'RenameAttributes' object is not iterable
Today's python error: image is blank
Multiplicative hash is not perfect (proven)
What is the python underscore (_) for?
Determining which OS is running Python
Python> What is an extended slice?
Python in is also an operator
Sympy Laplace transform is not practical
Did not change from Python 2 to 3