On the Windows XP..7 platforms, for x86 instruction sets, using standard C++ or a Microsoft compiler, is there a value I can assign a double which, when other computations are applied to it, will always result in that same value?
e.g.
const double kMagicValue = ???;
double x = kMagicValue;
cout << x * 9.1; // still outputs kMagicValue
As I understand it, there is a floating point error condition that once trigged, the remainder of all floating point computations will result in NAN or something similar…
I ask because I have a series of functions that try to compute a double for a given input, and for some inputs, “no answer (NAN)” is a good output (conceptually).
And I want to be able to be lazy, and string together computations that should, if any part results in NAN, result as a whole in NAN (i.e. kMagicValue).
You shouldn’t rely on
NaNto do the job. It will always compare false to any value, including itself, and you have to make sure that the platform respects IEEE754 semantics to a certain extent (this includes having a NaN in the first place).See horror stories there: Negative NaN is not a NaN?
If you really want this approach, and you are confident enough about IEEE754 support, be sure to compile with
/fp:precise(since you use MSVC) so that the compiler doesn’t optimize away stuff like0 * NaN. Be aware that this might impact performance.To get a NaN,
To test for NaN
But this approach is probably more trouble than it is worth. I’d rather use exceptions for control flow here.
The right thing to use is
boost::optional<double>, but it can be a little verbose at some places[Also, the Haskell language has first-class support for these kind of control flow, if C++ is not a must-go option,
Maybeyou can give it a try.]