round() returns floating point, not int, for some numpy floats when no second arg
See original GitHub issueThe semantics of round() changed in Python 3:
round(number[, ndigits]) Return number rounded to ndigits precision after the decimal point. If ndigits is omitted or is None, it returns the nearest integer to its input.
This works incorrectly in the case of np.float64, which returns a float. I believe the __round__ method is calling __rint__, which should return an integer but doesn’t.
Reproducing code example:
import numpy as np
In [50]: round(1.0)
Out[50]: 1
In [51]: round(float(1.0))
Out[51]: 1
In [52]: round(np.float(1.0))
Out[52]: 1
In [53]: round(np.float64(1.0))
Out[53]: 1.0
This behavior is the same for float16, float32, and float128.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:24
- Comments:14 (8 by maintainers)
Top Results From Across the Web
round() returns different result depending on the number of ...
The round function returns an integer if the second argument is not specified, else the return value has the same type as that...
Read more >Python round() function with EXAMPLES - Guru99
Round() is a built-in function available with python. It will return you a float number that will be rounded to the decimal places...
Read more >How to Use Numpy Round - Sharp Sight
In this tutorial I'll explain how to use the Numpy round function (AKA, ... can be a single number (i.e., a Python float)...
Read more >numpy.set_printoptions — NumPy v1.24 Manual
Set printing options. These options determine the way floating point numbers, arrays and other NumPy objects are displayed. Parameters: precisionint ...
Read more >The Right Way to Compare Floats in Python - davidamos.dev
Floating -point numbers are a fast and efficient way to store and work ... similar to numpy.allclose() and returns whether or not the...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
NumPy round applied to numpy floats does not return integers. It is a feature, not a bug. The Python behavior you illustrate is new in Python 3.
Another thought on this issue: since
isinstance(np.float64(1), float)
is true, the current implementation breaks Liskov substitution principle making the use of numpy scalars very unSOLID.The problem is that one has a lot of paths (sometimes unexpected) in which
numpy.float64
values sneaks into existing code, which makes unit testing and maintenance unnecessarily cumbersome.