Reputation: 293
The Matlab function eps(x)
returns "the positive distance from abs(x) to the next larger floating-point number of the same precision as x
." I use this to calculate the smallest floating-point number greater than x
, via x + eps(x)
. I would also like to obtain the largest floating point number less than x
, but I'm unaware of a function similar to eps
that would facilitate this. How can I find the largest floating point number less than x
?
Upvotes: 4
Views: 589
Reputation: 7874
For all numbers except subnormals (i.e. those smaller than 2.225073.8585072014e-308
) you can do:
v = 1 - eps()/2;
b = x / v; # next larger in magnitude
c = x * v; # next smaller in magnitude
(based on this answer).
Upvotes: 0
Reputation: 35525
You can subtract eps
in almost all cases.
However as you probably have realized, this does not apply when the mantisa changes, or in other words, when you want to subtract from a power of two.
A negative-side eps
then is easy to implement, knowing that the current eps
is smaller than the distance to the next power of two that will trigger a step change. Therefore, the eps
of our number minus its eps
should do the trick.
function out=neps(in)
out=eps(in-eps(in));
This seem to work fine
eps(2)
4.440892098500626e-16
neps(2)
2.220446049250313e-16
Upvotes: 6