0

I have some code that I will simplify to this:

double x;
double y;
double z;
.
.

while (x + y != z)
    do stuff;

The problem is that x + y is very close to z but somewhere in my code it looses precision and so is x + y is a bit off. I have tried things like:

while (x + y + 0.0001 > z && x + y - 0.0001 < z) but I wanna do something more general. Is there some notation / function like this:

while (x + y != nextdouble(z) && x + y != prevdouble(z) && x + y != z)

where nextdouble() would give the smallest possible double greater than the parameter.

Theo Walton
  • 1,085
  • 9
  • 24
  • Have a look at [**Difference between float and double**](https://stackoverflow.com/questions/2386772/difference-between-float-and-double) and specifically the link in the 2nd answer. – David C. Rankin Aug 05 '17 at 07:31
  • 2
    It's best not to compare floating point values for equality. If you absolutely *must*, using a range **is** the way to go. –  Aug 05 '17 at 07:35
  • 1
    It does not necessary have to be "the next closest number". There is no easy and straightforward answer for the question you ask. You need to learn a bit of theory of numeric calculations. – 0___________ Aug 05 '17 at 07:53
  • `nextafter()`/`nexttoward()` – EOF Aug 05 '17 at 08:44
  • Maybe you should use `static inline double reldiff(double x, double y) { return fabs(x - y) / fmax(fabs(x), fabs(y)); }` and test `if (reldiff(x + y, z) < 1E-8)` or some other similar small fraction. – Jonathan Leffler Aug 05 '17 at 14:38

0 Answers0