About the Examples






About the Examples

Most of the examples in this chapter use a header file named "mathutil.h". This header file defines a function, show_exceptions, that displays the floating-point exceptions that are currently raised. For details, see Appendix B.2.

Compiler optimizations often hide exceptions. For example, the expression 0.0/0.0 should raise the "invalid" exception. However, compilers often evaluate an expression like that at compile time and simply plug in a NaN (not a number) value instead of doing the division at runtime. The result is that no exception is raised. This can be very confusing.

C99 has a #pragma directive to tell the compiler that you're going to be testing the floating-point status flag and to report everything that happens. I haven't used it in these examples, because it's not required by the C++ standard.[3] If your compiler supports it, though, you should add

[3] TR1 is entirely library extensions and doesn't add anything to the language itself.

#include <fenv.h>
#pragma STDC  FENV_ACCESS ON

to the beginning of all your test programs.

If your compiler doesn't support this pragma, turn off optimizations. You may also have to play around with the way you write expressions. For example, the function

double divide(double x, double y)
  {
  return x / y;
  }

doesn't raise "inexact" when called with divide(2.0, 3.0). Rewriting it as

double divide(double x, double y)
  {
  double res = x / y;
  return res ;
  }

fixes this problem.



 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows