jacg
jacg

Reputation: 2120

How to understand the results of numpy.nextafter

Consider the following calls to numpy.nextafter

>>> from numpy import nextafter
>>> nextafter( 0.1, -1)
0.099999999999999992
>>> nextafter( 0.1, +1)
0.10000000000000002
>>> nextafter( 1  , -1)
0.99999999999999989
>>> nextafter( 1  , +1)
1.0
>>> nextafter(10  , -1)
9.9999999999999982
>>> nextafter(10  , +1)
9.9999999999999982

I would expect all the cases where the second argument is positive, to return a value which is greater than the first argument; and the result to be smaller than the first argument whenever the second argument is less than zero.

My expectations are not met by the exhibited behaviour, specifically:

  1. nextafter(1, +1) does not change the first input at all, rather than increasing it.
  2. nextafter(10, +1) decreases the first input, rather than increasing it.

Is this a bug or a feature?

These examples were generated with Numpy 1.13.1 on Python 3.6.1

Upvotes: 4

Views: 1696

Answers (1)

MB-F
MB-F

Reputation: 23637

You misunderstood the meaning of the second parameter. According to the docs, the function does (emphasis mine)

Return the next floating-point value after x1 towards x2, element-wise.

Thus, nextafter(1, +1) does not change anything because you are trying to go from 1.0 towards 1.0. nextafter(10, +1) decreases the input because that's how to go from 10.0 to 1.0.

You can go towards +/- infinity if you always want to increase/decrease:

import numpy as np
nextafter( 0.1, -np.inf)  # 0.099999999999999992
nextafter( 0.1, +np.inf)  # 0.10000000000000002
nextafter( 1  , -np.inf)  # 0.99999999999999989
nextafter( 1  , +np.inf)  # 1.0000000000000002
nextafter(10  , -np.inf)  # 9.9999999999999982
nextafter(10  , +np.inf)  # 10.000000000000002

Upvotes: 9

Related Questions