How to implement the Fortran spacing() function in C++?

Viewed 129

The code I'm converting from Fortran to C++ contains the spacing(x) function. From the description, spacing(x) returns the

Smallest distance between two numbers of a given type

and

Determines the distance between the argument X and the nearest adjacent number of the same type.

Is there a C++ equivalent function or, if not, how do I implement that function in C++?

1 Answers

Using SPACING as Determines the distance between the argument X and the nearest adjacent number of the same type, use nexttoward().

upper = nexttoward(x, INFINITY) - x;
lower = x - nexttoward(x, -INFINITY);
spacing = fmin(upper, lower);

 

upper != lower in select cases: e.g. x is a power-of-2.
May need some work to handle implementations that lack a true INFINITY.

or

if (x > 0) {
  spacing = x - nexttoward(x, 0);
} else {
  // 1.0 used here instead of 0 to handle x==0
  spacing = nexttoward(x, 1.0) - x; 
}

or

// Subtract next smaller-in-magnitude value.  With 0, use next toward 1.
spacing = fabs(x - nexttoward(x, !x));

I suspect nextafter() will work as well, or better than, nexttoward().

Related