The Math "pow" function returns -1.#IND. What kind of error value is -1.#IND and how do I detect the error in an if-statement?
-1.#IND is the textual representation of NaN on Windows.
You can check if a float value is NaN with this small function:
// NaN never compares equal, not even to itself
bool is_nan(double d){ return d != d; }
(As #chris notes, if you have a C++11 compliant stdlib, you get std::isnan in <cmath>.)
In normal program flow, you shouldn't need to worry about NaN as long as you sanity-check your math inputs. Of course, you can also go the other way and just do your math calculations and check against NaN afterwards. :)
The value you see is a representation for NaN or not a number. These values show up as a result of a floating point operation which has an undefined value. For example, 0.0 / 0.0 will yield a NaN. There are a number of other situations where a NaN is produced. If you want to determine if a floating point value is a NaN, you can test for them:
if (std::isnan(value)) {
...
}
There are few other other special values which can be produced as the result of floating point operations, e.g., positive or negative infinity and there are tests in <cmath> for these, as well.
-1#IND normally happens when you have a /0 somewhere in your code. Protect against it by checking all denominators or bases in pow functions with -ve exponents for 0's.
Once the division or pow operation has been completed, if you didn't check your inputs, check your outputs with:
if (output != output) return 0; // or some default
else return output;
-1.#IND is a NaN, not a number. NaNs arise for many reasons. Expressions such as 0.0/0.0 are indeterminate; you'll get a NaN if you try. The square root of -1 (or of any negative real) is pure imaginary; use the float or double sqrt function and you'll get a NaN as a result. Here the result is not indeterminate, but it is not real, either. It's a NaN.
Another way to express sqrt(-1.0) is pow(-1.0, 0.5). This also generates a NaN.
Related
I have a program in C++ where I divide two numbers, and I need to know if the answer is an integer or not. What I am using is:
if(fmod(answer,1) == 0)
I also tried this:
if(floor(answer)==answer)
The problem is that answer usually is a 5 digit number, but with many decimals. For example, answer can be: 58696.000000000000000025658 and the program considers that an integer.
Is there any way I can make this work?
I am dividing double a/double b= double answer
(sometimes there are more than 30 decimals)
Thanks!
EDIT:
a and b are numbers in the thousands (about 100,000) which are then raised to powers of 2 and 3, added together and divided (according to a complicated formula). So I am plugging in various a and b values and looking at the answer. I will only keep the a and b values that make the answer an integer. An example of what I got for one of the answers was: 218624 which my program above considered to be an integer, but it really was: 218624.00000000000000000056982 So I need a code that can distinguish integers with more than 20-30 decimals.
You can use std::modf in cmath.h:
double integral;
if(std::modf(answer, &integral) == 0.0)
The integral part of answer is stored in fraction and the return value of std::modf is the fractional part of answer with the same sign as answer.
The usual solution is to check if the number is within a very short distance of an integer, like this:
bool isInteger(double a){
double b=round(a),epsilon=1e-9; //some small range of error
return (a<=b+epsilon && a>=b-epsilon);
}
This is needed because floating point numbers have limited precision, and numbers that indeed are integers may not be represented perfectly. For example, the following would fail if we do a direct comparison:
double d=sqrt(2); //square root of 2
double answer=2.0/(d*d); //2 divided by 2
Here, answer actually holds the value 0.99999..., so we cannot compare that to an integer, and we cannot check if the fractional part is close to 0.
In general, since the floating point representation of a number can be either a bit smaller or a bit bigger than the actual number, it is not good to check if the fractional part is close to 0. It may be a number like 0.99999999 or 0.000001 (or even their negatives), these are all possible results of a precision loss. That's also why I'm checking both sides (+epsilon and -epsilon). You should adjust that epsilon variable to fit your needs.
Also, keep in mind that the precision of a double is close to 15 digits. You may also use a long double, which may give you some extra digits of precision (or not, it is up to the compiler), but even that only gets you around 18 digits. If you need more precision than that, you will need to use an external library, like GMP.
Floating point numbers are stored in memory using a very different bit format than integers. Because of this, comparing them for equality is not likely to work effectively. Instead, you need to test if the difference is smaller than some epsilon:
const double EPSILON = 0.00000000000000000001; // adjust for whatever precision is useful for you
double remainder = std::fmod(numer, denom);
if(std::fabs(0.0 - remainder) < EPSILON)
{
//...
}
Alternatively, if you want to include values that are close to integers (based on your desired precision), you can modify the if condition slightly (since the remainder returned by std::fmod will be in the range [0, 1)):
if (std::fabs(std::round(d) - d) < EPSILON)
{
// ...
}
You can see the test for this here.
Floating point numbers are generally somewhat precise to about 12-15 digits (as a double), but as they are stored as a mantissa (fraction) and a exponent, rational numbers (integers or common fractions) are not likely to be stored as such. For example,
double d = 2.0; // d might actually be 1.99999999999999995
Because of this, you need to compare the difference of what you expect to some very small number that encompasses the precision you desire (we will call this value, epsilon):
double d = 2.0;
bool test = std::fabs(2 - d) < epsilon; // will return true
So when you are trying to compare the remainder from std::fmod, you need to check it against the difference from 0.0 (not for actual equality to 0.0), which is what is done above.
Also, the std::fabs call prevents you from having to do 2 checks by asserting that the value will always be positive.
If you desire a precision that is greater than 15-18 decimal places, you cannot use double or long double; you will need to use a high precision floating point library.
I have an application in which a code area produces NAN values. I have to compare the values for equality and based on that execute the rest of the code.How to compare two NAN values in C++ for equality?
Assuming an IEEE 754 floating point representation, you cannot compare two NaN values for equality. NaN is not equal to any value, including itself. You can however test if they are both NaN with std::isnan from the <cmath> header:
if (std::isnan(x) && std::isnan(y)) {
// ...
}
This is only available in C++11, however. Prior to C++11, the Boost Math Toolkit provides some floating point classifiers. Alternatively, you can check if a value is NaN by comparing it with itself:
if (x != x && y != y) {
// ...
}
Since NaN is the only value that is not equal to itself. In the past, certain compilers screwed this up, but I'm not sure of the status at the moment (it appears to work correctly with GCC).
MSVC provides a _isnan function.
The final alternative is to assume you know the representation is IEEE 754 and do some bit checking. Obviously this is not the most portable option.
Regarding pre-C++11, there's a boost for that, too.
#include <boost/math/special_functions/fpclassify.hpp>
template <class T>
bool isnan(T t); // NaN.
Any given NaN is not equal to anything, it will never be equal to any other NaN, so comparing them against each other is a futile exercise.
From GNU docs:
NaN is unordered: it is not equal to, greater than, or less than anything, including itself. x == x is false if the value of x is NaN. source
I'm trying to check if a std::complex number that is a result of a fourier transform (using http://fftw.org/) contains a NaN in either the real or imag part.
I'm using Borland C++, so I don't have access to std::isnan. I have tried to check if the number is NaN by comparing it to itself:
(n.imag() != n.imag())
However, as soon as I call the n.imag() or std::imag(n), I get a "floating point invalid operation".
Is there any way to validate if a std::complex is good; if it contains a NaN?
This works on g++ :
#include<iostream>
#include<cmath>
#include<complex>
int main(){
double x=sqrt(-1.);
std::complex<double> c(sqrt(-1.), 2.);
std::cout<<x<<"\n";
std::cout<<c<<"\n";
std::cout<< ( (c!=c) ? "yup" : "nope" )<<"\n";
}
From the float.h header
int _isnan(double d);
Returns a nonzero value (TRUE) if the value passed in is a NaN; otherwise it returns 0 (FALSE).
int _fpclass(double __d);
Returns an integer value that indicates the floating-point class of its argument. The possible values are defined in FLOAT.H (NaN, INF, etc.)
Is there fpclassify() in math.h? It should return FP_NAN for NaNs. Or better yet use isnan(). If there are no such functions/macros, you may look at the binary representation of your floats or doubles and check manually for NaNs. See IEEE-754 single and double precision formats for details.
I found out that Borland has its own math library. So if you want to avoid floating point errors, use IsNan from Borlands Math.
http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/delphivclwin32/Math_IsNan#Double.html
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).
Quiet NaN should do just fine. You can get it from std::numeric_limits<double>::quiet_NaN() by including the <limits> header. There's also a signaling NaN, but using it will usually result in an exception.
Remember however, that you can't simple use mydouble == qNaN, since NaN compares equal to nothing, not even itself. You have to use that property of NaN to test it: bool isNaN = mydouble != mydouble;.
Any floating point operation involving NaN results in NaN again (to my knowledge). Moreover, NaN compares unequal to itself, and it is unique among IEEE754 floats with this property. So, to test for it:
bool is_nan(double x) { return x != x; }
If you have C++11 support, you can use std::isnan(x) != 0 or std::fpclassify(x) == std::FP_NAN from <cmath> instead [thanks #James Brock].
To make it:
double make_nan() {
assert(std::numeric_limits<double>::has_quiet_NaN);
return std::numeric_limits<double>::quiet_NaN();
}
You shouldn't rely on NaN to 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 like 0 * NaN. Be aware that this might impact performance.
To get a NaN,
std::numeric_limits<double>::quiet_NaN()
To test for NaN
inline bool is_NaN(double x) { return !(x == x); }
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, Maybe you can give it a try.]
Actually there is a special floating point value named Not-A-Number (NaN). Any expression with NaN involved will return NaN.
#include <limits>
numeric_limits<double>::quiet_NaN()
Infinity not always remains the same. For example it become NaN if you try to divide on Infinity.
I just wrote the following code in C++:
double variable1;
double variable2;
variable1=numeric_limits<double>::max()-50;
variable2=variable1;
variable1=variable1+5;
cout<<"\nVariable1==Variable2 ? "<<(variable1==variable2);
The answer to the cout statement comes out 1, even when variable2 and variable1 are not equal.Can someone help me with this? Why is this happening?
I knew the concept of imprecise floating point math but didn't think this would happen with comparing two doubles directly. Also I am getting the same resuklt when I replace variable1 with:
double variable1=(numeric_limits<double>::max()-10000000000000);
The comparison still shows them as equal. How much would I have to subtract to see them start differing?
The maximum value for a double is 1.7976931348623157E+308. Due to lack of precision, adding and removing small values such as 50 and 5 does not actually changes the values of the variable. Thus they stay the same.
There isn't enough precision in a double to differentiate between M and M-45 where M is the largest value that can be represented by a double.
Imagine you're counting atoms to the nearest million. "123,456 million atoms" plus 1 atom is still "123,456 million atoms" because there's no space in the "millions" counting system for the 1 extra atom to make any difference.
numeric_limits<double>::max()
is a huuuuuge number. But the greater the absolute value of a double, the smaller is its precision. Apparently in this case max-50and max-5 are indistinguishable from double's point of view.
You should read the floating point comparison guide. In short, here are some examples:
float a = 0.15 + 0.15
float b = 0.1 + 0.2
if(a == b) // can be false!
if(a >= b) // can also be false!
The comparison with an epsilon value is what most people do.
#define EPSILON 0.00000001
bool AreSame(double a, double b)
{
return fabs(a - b) < EPSILON;
}
In your case, that max value is REALLY big. Adding or subtracting 50 does nothing. Thus they look the same because of the size of the number. See #RichieHindle's answer.
Here are some additional resources for research.
See this blog post.
Also, there was a stack overflow question on this very topic (language agnostic).
From the C++03 standard:
3.9.1/ [...] The value representation of floating-point types is
implementation-defined
and
5/ [...] If during the evaluation of an expression, the result is not
mathematically defined or not in the range of representable values for
its type, the behavior is undefined, unless such an expression is a
constant expression (5.19), in which case the program is ill-formed.
and
18.2.1.2.4/ (about numeric_limits<T>::max()) Maximum finite value.
This implies that once you add something to std::numeric_limits<T>::max(), the behavior of the program is implementation defined if T is floating point, perfectly defined if T is an unsigned type, and undefined otherwise.
If you happen to have std::numeric_limits<T>::is_iec559 == true, in this case the behavior is defined by IEEE 754. I don't have it handy, so I cannot tell whether variable1 is finite or infinite in this case. It seems (according to some lecture notes on IEEE 754 on the internet) that it depends on the rounding mode..
Please read What Every Computer Scientist Should Know About Floating-Point Arithmetic.