round
Peter Otten
__peter__ at web.de
Thu Jun 7 08:17:29 EDT 2018
ast wrote:
> Hi
>
> round is supposed to provide an integer when
> called without any precision argument.
>
> here is the doc:
>
> >>> help(round)
>
> round(number[, ndigits]) -> number
>
> Round a number to a given precision in decimal digits (default 0 digits).
> This returns an int when called with one argument, otherwise the
> same type as the number
That's not the complete story. Quoting
https://docs.python.org/dev/library/functions.html#round
"""
For a general Python object number, round delegates to number.__round__.
"""
Bogus example to make the point:
>>> class A:
... def __round__(self): return "whatever"
...
>>> round(A())
'whatever'
> but in some circumstances it provides a float
>
> import numpy as np
>
> M = np.array([[0, 9],[2, 7]], dtype=int)
> np.linalg.det(M)
> -18.000000000000004
> round(np.linalg.det(M))
> -18.0 # i was expecting an integer -18, not a float
>
> # same problem with np.round
> np.round(np.linalg.det(M))
> -18.0
>>> M = np.array([[0, 9],[2, 7]], dtype=int)
>>> type(np.linalg.det(M))
<class 'numpy.float64'>
So numpy.linalg.det() returns a custom type float64 which maps round() to
float64:
>>> round(np.float64(1.23))
1.0
>>> type(_)
<class 'numpy.float64'>
More information about the Python-list
mailing list