Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.nextafter decrementing instead of incrementing

I fell on a weird case. I tried either of the three solutions posted here from Pyson: Increment a python floating point value by the smallest possible amount. All three solutions display a weird behavior when I land on this floating point: 1.15898324042702949299155079643242061138153076171875.

Let say I have the following code:

import numpy as np
from __future__ import division

a = 1.15898324042702949299155079643242061138153076171875
b = 0
b = np.nextafter(a,1)
print a, b

For some reason, instead of incrementing b by the smallest amount possible, it is decremented. Why is that?

Here's some quick results that I got from playing around:

In [12]: a = 1.15898324042702949299155079643242061138153076171875

In [13]: a
Out[13]: 1.1589832404270295

In [14]: numpy.nextafter(a,1)
Out[14]: 1.1589832404270293

In [15]: numpy.nextafter(a,-1)
Out[15]: 1.1589832404270293
like image 346
macrocosme Avatar asked Nov 09 '12 01:11

macrocosme


Video Answer


1 Answers

From the docs (emphasis mine):

nextafter(x1, x2[, out])

Return the next representable floating-point value after x1 **in the direction
of x2 element-wise**.

The second argument isn't a direction given by +/-1, it's the value to aim toward.

In [12]: a = 1.15898324042702949299155079643242061138153076171875

In [13]: a
Out[13]: 1.1589832404270295

In [14]: numpy.nextafter(a, 0)
Out[14]: 1.1589832404270293

In [15]: numpy.nextafter(a, 1)
Out[15]: 1.1589832404270293

In [16]: numpy.nextafter(a, 1.16)
Out[16]: 1.1589832404270297

In [17]: numpy.nextafter(a, 2)
Out[17]: 1.1589832404270297
like image 133
DSM Avatar answered Oct 09 '22 23:10

DSM