0

I'm trying to check my floating point operations in c99.

Should I be doing all of my operations inside of isnormal()? Does this code make sense?

double dTest1 = 0.0;
double dTest2 = 0.0;
double dOutput = 0.0;

dTest1 = 5.0;
dTest2 = 10.3;
dOutput = dTest1 * dTest2;

//add some logic based on output
isnormal(dOutput);
Deduplicator
  • 44,692
  • 7
  • 66
  • 118

1 Answers1

2

Your use of isnormal does not look like anything idiomatic. I am not sure what you expect exactly from using isnormal this way (it's obviously going to be true for 5.0*10.3, I would expect the compiler to optimize it so), but here are at least some obvious problems assuming you use it for other computations:

Zero is not normal, so you shouldn't use isnormal as a sanity check for a result that can be zero.

isnormal will not tell you if your computation came so close to zero that it lost precision (the subnormal range) and went back into the normal range later.

You might be better served by FPU exceptions: there is one for each possible event for which you might want to know if it happened since you initiated your computations, and the way to use them is sketched out in this existing answer.

Community
  • 1
  • 1
Pascal Cuoq
  • 79,187
  • 7
  • 161
  • 281
  • My compiler doesn't have FPU exceptions. Should I use different error checking depending on the type of floating-point operation then? if I think a large number is going to be divided by a small number should I check for an underflow? if I'm multiplying two large numbers should I check for an overflow? – CodeSlapper Dec 15 '15 at 03:15
  • @CodeSlapper For a single multiplication of values that you know to be non-zero, using `isnormal` on the result is fine to check that the accuracy of the result is good. But it is expensive: `isnormal` probably costs more than the multiplication itself. The reason I recommended exceptions is that you can check them only at the end of a long sequence of operations, and determine that all operations computed according to plan, which is more readable and more efficient. – Pascal Cuoq Dec 15 '15 at 10:04