Had a very very very annoying bug today. acos() somewhere inside ancient code returned a sort of NONE, and the int that was assigned NONE has propagated this bug so freaking far, it took me the hole day to regress my steps to code I have written about a month ago. The bug was occurring under very rare circumstances to which replicate was depending on luck mostly.
My question is this. since c++ doesn't throw an exception as soon as acos() receives an invalid input, how do I in the future deal with these functions which return weird values such as this NONE? What are these values, are they like NULL just for integers? which number represents NONE in memory?
I seriously doubt that the rare circumstances had anything to do with failure on the part of the acos() function.
The way to prevent it is to never pass an argument out of domain [-1,1]. So check before you use acos(). If the argument is bad, fix it or handle the error some other way.
Also, there is no NONE for integers or in standard C or C++. Where did you get it from?
my bad I mean floats or doubles ofcoarse, I had a cast to int in my code so I got confused. The debugger at the visual studio was representing the int as NONE so i'm not sure what that means, and how to protect from it.
If you want to exit when some floating-point variable x is a NaN (not "NONE"),
1 2
if( std::isnan(x) )
exit(1);
or, if you don't have isnan,
1 2
if(x != x)
exit(1);
On some compilers, you could also make acos() throw an exception when it encounters a domain error, with Visual Studio, it will be a "structured exception", not a C++ exception (although it can be converted to C++ with _set_se_translator), and it is enabled via _control87()
Software that summarily quits because of (from the user's point of view) something random (and from the program's point of view, handling a bad number) is evil software. People can't uninstall that stuff fast enough.
Just do as you have been advised: clamp x to [-1,1] before passing it to acos().
Remember, floating point arithmetic is not simple.