# Understanding nextfloat() and prevfloat()

Hello,

I’m currently reading the Julia documentation/tutorial and I think I don’t really understand how nextfloat(x) and prevfloat(x) are computed. Reading the document I thought they would be respectively `x + eps(x)` and `x - eps(x)` , however if it seems to be the case for nextfloat(x), it is not for prevfloat(x).

example:

``````julia> 1.0+eps(1.0)
1.0000000000000002

julia> nextfloat(1.0)
1.0000000000000002
``````

and

``````julia> 1.0-eps(1.0)
0.9999999999999998

julia> prevfloat(1.0)
0.9999999999999999
``````

So, how are these number computed ?

Thank you !

The thing you’re missing is that `eps(0.9999999999999999)` is half of `eps(1.0)` due to how floating point numbers work. The way these results are computed by Julia is that `nextfloat(x)` is just the result of reinterpreting `x` as an `Integer`, adding 1, and reinterpreting back as a floating point number (or subtracting for prevfloat).

2 Likes

To elaborate on that, values that are exactly powers of 2—like `1.0`—are on the cusp between a smaller `eps` size and the next bigger `eps` size. And since `eps(x)` is defined such that `eps(x) = nextfloat(x) - x`, that means that `eps(x)` is going to be bigger than `x - prevfloat(x)` for powers of two; for all other values of `x`, `nextfloat(x) - x` and `x - prevfloat(x)` are equal. There’s a case to be made for either definition of `eps(x)` on the cusp, but the larger value is conventional.

5 Likes

thank you both @Oscar_Smith and @StefanKarpinski I understand now

1 Like