# Thread: lowest spacing between numbers

1. ## lowest spacing between numbers

I was woundering if there is some kind of function that returns what is the lowest posible spacing for some variable.
For example, in Fortran you can use function "spacing". Lets say that a variable x is a double (in fortran real :: kind(8) = x). Then spacing(x) would return 2.225073858507201E-308. If for example x was a float, than spacing(x) would give 1.17549435082228E-38. Is there some kind of equivalent to this in c++?

2. #include <limits>, then use std::numeric_limits<T>::epsilon() for the type T.

3. Thanks!

4. But epsilon itself is only valid when added to 1.0.

If the value stored in the double is much larger (say 1E20), then the apparent 'epsilon' you need to add to cause a change will be so much greater.

5. As Salem points out, the Epsilon function is the smallest number that "will make a difference" when added/subtracted from 1.0 for any (floating point) type.

I don't think it's trivial to come up with a "spacing" function. Do you want this to be super-fast, or is it a rarely called function?

I'm thinking that you could do something like this:
Code:
```double spacing(double x)
{
double orig = x;
double sp;
sp = x / (double) (1U << 31;
while (sp != 0.0 && (x + sp != orig)) {
sp /= 2.0;
}
sp *= 2.0;
return sp;
}```
It's probably not very inefficient, but there may be some way that we could make it better. If you have a compiler/processor that supports 64-bit integers, you can probably use a bigger shift than 31, and reduce the number of loops needed to find the number.

An alternative solution is to use some bit manipulation of the incoming number - that's less portable but probably a fair bit faster.

--
Mats

6. Do you need it to be portable? This one works for IEEE-754 floating point numbers.
Code:
```static_assert(sizeof(int) == sizeof(float));

float f = something;
unsigned int &fbits = reinterpret_cast<unsigned int &>(f);

const unsigned int exponent_mask = 0x7F800000;
float epsilon;
unsigned int &ebits = reinterpret_cast<unsigned int &>(epsilon);
ebits = (fbits & exponent_mask) | 1;```
It works the same with double and a 64-bit integer type. In this case, the mask is 0x7FF0000000000000.

7. But if the LSB of the float mantissa is already 1, then or-ing with 1 won't do anything.

8. Eh? I'm masking out everything but the exponent. I construct the positive floating point number that has the same exponent as the source number but the smallest possible mantissa. Which is the smallest floating pointer number that has an effect when added to or subtracted from the original floating point number.

9. So you are