Flooring to nearest multiple of 0.2 in numpy?

Viewed 818

How can I floor a number to the nearest multiple of 0.2 in numpy?

For example, I have this:

0.2 * np.floor(xi / 0.2)

It works most of the time e.g.

>>> xi = 9.4
>>> 0.2 * np.floor(xi / 0.2)
9.4

However, it fails for some numbers, such as 9.6

>>> xi = 9.6
>>> 0.2 * np.floor(xi / 0.2)
9.4

I would expect the previous calculation to return 9.4.

How can I fix this?

2 Answers

This is because float format - note that 9.6/0.2 returns 47.9999999....

Some rounding here and there will do the trick:

round(0.2*np.floor(round(xi / 0.2,2)),1)

Inner rounding is 2 decimal places, to make sure you won't loose the precision, and still will have something to floor. Outer round is - so you will have proper rounding to 0.2 (and not e.g. 9.6000...1)

Use np.round

0.2 * np.round(xi / 0.2)

output:

9.600000000000001

The little bit extra is due to floating point math.

Related