Distance between doubles, etc

J

janzon

Hello!

Suppose x is a double not equal to Inf or NaN. How can I find the
smallest double y, such that x<y? It would be nice not having to deal
with bits, big and little endian and so forth. (But maybe I have to.)

Is there a quick and dirty way to get a rough estimate? Is the number
DBL_EPSILON*x of any value?
 
P

Pete Becker

Suppose x is a double not equal to Inf or NaN. How can I find the
smallest double y, such that x<y? It would be nice not having to deal
with bits, big and little endian and so forth. (But maybe I have to.)

nextafter(x, numeric_limits<double>::max())

nextafter was added to C in C99, and is in C++'s TR1. It's also been
voted into the next version of the standard.

If your implementation doesn't supply it you'll probably have to do some
bit twiddling.

--

-- Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com)
Author of "The Standard C++ Library Extensions: a Tutorial and
Reference." (www.petebecker.com/tr1book)
 
L

loic-dev

Hello,
nextafter(x, numeric_limits<double>::max())

nextafter was added to C in C99, and is in C++'s TR1. It's also been
voted into the next version of the standard.

If your implementation doesn't supply it you'll probably have to do some
bit twiddling.

A portable /nextafter(x,numeric_limits<double>::max())/ could look like
the one given after the signature. Without any explicit or implied
warranty ;-)

Cheers,
Loic.
--
#include <float.h>

/*
* return the smallest double y, such that x < y
*/
double
my_nextafter(double x)
{
double y;
if (x>=0) {
y = x*(1+DBL_EPSILON);
} else {
y = x*(1-DBL_EPSILON);
}
double middle;
while (x < y ) {
middle = (x+y)/2;
if (x < middle && y!=middle) {
y = middle;
} else {
break;
}
}
return y;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,430
Messages
2,571,676
Members
48,796
Latest member
Greg L.

Latest Threads

Top