Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there a difference between round(x) and round(np.float64(x))?

Tags:

python

numpy

From what i understand, 2.675 and numpy.float64(2.675) are both the same number. However, round(2.675, 2) gives 2.67, while round(np.float64(2.675), 2) gives 2.68. Why does this happen?

import numpy as np
from decimal import Decimal

x = 2.675
np_x = np.float64(x)
type(x) # float
Decimal(x)    # Decimal('2.67499999999999982236431605997495353221893310546875')
Decimal(np_x) # Decimal('2.67499999999999982236431605997495353221893310546875')
x == np_x # True

# This is the bit that bothers me
round(x, 2) # 2.67
round(np_x, 2) # 2.68

# Using numpy's round gives 2.68 for both the numpy float as well as the Python built-in float...
np.round(x, 2) # 2.68
np.round(np_x, 2) # 2.68

# ... but this is because it might be converting the number to a numpy float before rounding
type(np.round(x, 2)) # numpy.float64

# Versions
# Python 3.6.8 running on 64-bit Windows 10
# Numpy 1.16.2
like image 674
devan Avatar asked May 05 '19 16:05

devan


People also ask

What is the difference between float and float64?

float is an alias for python float type. np. float32 and np. float64 are numpy specific 32 and 64-bit float types.

What does NP round do?

The numpy. round_() is a mathematical function that rounds an array to the given number of decimals.

How do you round a value in an NP array?

To round elements of the array to the nearest integer, use the numpy. rint() method in Python Numpy. For values exactly halfway between rounded decimal values, NumPy rounds to the nearest even value. The out is a location into which the result is stored.

Is float64 a python?

Python float values are represented as 64-bit double-precision values. 1.8 X 10308 is an approximate maximum value for any floating-point number. If it exceeds or exceeds the max value, Python returns an error with string inf (infinity).


1 Answers

Very interesting question :) Looks like it has to do with numbers that end with a 5. Numpy rounds them by excess, but not always...

# list of incoherences between Python Numpy with round(x, 2)
for i in range(1001):
    x = i/1000
    np_x = np.float64(x)
    if round(x, 2) != round(np_x, 2):
        print(x)

# 0.005
# 0.015
# 0.025   <<< some values are missing!
# 0.065
# 0.075
# 0.085
# ...
like image 86
Omar Cusma Fait Avatar answered Nov 15 '22 00:11

Omar Cusma Fait