Checking if a complex number has NaN - c++

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

Related

Difference in behaviour of pow from math.h for same input [duplicate]

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
int n,i,ele;
n=5;
ele=pow(n,2);
printf("%d",ele);
return 0;
}
The output is 24.
I'm using GNU/GCC in Code::Blocks.
What is happening?
I know the pow function returns a double , but 25 fits an int type so why does this code print a 24 instead of a 25? If n=4; n=6; n=3; n=2; the code works, but with the five it doesn't.
Here is what may be happening here. You should be able to confirm this by looking at your compiler's implementation of the pow function:
Assuming you have the correct #include's, (all the previous answers and comments about this are correct -- don't take the #include files for granted), the prototype for the standard pow function is this:
double pow(double, double);
and you're calling pow like this:
pow(5,2);
The pow function goes through an algorithm (probably using logarithms), thus uses floating point functions and values to compute the power value.
The pow function does not go through a naive "multiply the value of x a total of n times", since it has to also compute pow using fractional exponents, and you can't compute fractional powers that way.
So more than likely, the computation of pow using the parameters 5 and 2 resulted in a slight rounding error. When you assigned to an int, you truncated the fractional value, thus yielding 24.
If you are using integers, you might as well write your own "intpow" or similar function that simply multiplies the value the requisite number of times. The benefits of this are:
You won't get into the situation where you may get subtle rounding errors using pow.
Your intpow function will more than likely run faster than an equivalent call to pow.
You want int result from a function meant for doubles.
You should perhaps use
ele=(int)(0.5 + pow(n,2));
/* ^ ^ */
/* casting and rounding */
Floating-point arithmetic is not exact.
Although small values can be added and subtracted exactly, the pow() function normally works by multiplying logarithms, so even if the inputs are both exact, the result is not. Assigning to int always truncates, so if the inexactness is negative, you'll get 24 rather than 25.
The moral of this story is to use integer operations on integers, and be suspicious of <math.h> functions when the actual arguments are to be promoted or truncated. It's unfortunate that GCC doesn't warn unless you add -Wfloat-conversion (it's not in -Wall -Wextra, probably because there are many cases where such conversion is anticipated and wanted).
For integer powers, it's always safer and faster to use multiplication (division if negative) rather than pow() - reserve the latter for where it's needed! Do be aware of the risk of overflow, though.
When you use pow with variables, its result is double. Assigning to an int truncates it.
So you can avoid this error by assigning result of pow to double or float variable.
So basically
It translates to exp(log(x) * y) which will produce a result that isn't precisely the same as x^y - just a near approximation as a floating point value,. So for example 5^2 will become 24.9999996 or 25.00002

How to compare two NAN values in C++

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

What kind of C++ constant/macro is -1.#IND?

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.

Is there a double value which will remain itself despite any computation applied to it?

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.

strange double to int conversion behavior in c++

The following program shows the weird double to int conversion behavior I'm seeing in c++:
#include <stdlib.h>
#include <stdio.h>
int main() {
double d = 33222.221;
printf("d = %9.9g\n",d);
d *= 1000;
int i = (int)d;
printf("d = %9.9g | i = %d\n",d,i);
return 0;
}
When I compile and run the program, I see:
g++ test.cpp
./a.out
d = 33222.221
d = 33222221 | i = 33222220
Why is i not equal to 33222221?
The compiler version is GCC 4.3.0
Floating point representation is almost never precise (only in special cases). Every programmer should read this: What Every Computer Scientist Should Know About Floating-Point Arithmetic
In short - your number is probably 33222220.99999999999999999999999999999999999999999999999999999999999999998 (or something like that), which becomes 33222220 after truncation.
When you attach a debugger and inspect the values, you will see that the value of d is actually 33222220.999999996, which is correctly truncated to 33222220 when converted to integer.
There is a finite amount of numbers that can be stored in a double variable, and 33222221 is not one of them.
Due to floating point approximation, 33222.221 may actually be 33222.220999999999999. Multiplied by 1000 yields 33222220.999999999999. Casting to integer ignores all decimals (round down) for a final result of 33222220.
If you change the "9.9g" in your printf() calls to 17.17 to recover all possible digits of precision with a 64-bit IEEE 754 FP number, you get 33222220.999999996 for the double value. The int conversion then makes sense.
I don't want to repeat the explanations of the other comments.
So, here is just an advice to avoid problems like the one described:
Avoid floating point arithemtics in the first place whereever possible (especially when computation is involved).
If floating point arithmetics is really necessary, you must not compare numbers by operator== by all means! Use your own comparison function instead (or use one supplied by some library), which does something like an "is almost equal" comparison using some kind of epsilon compare (either absolute or relative to the number's magniture).
See for example the excellent article
http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
by Bruce Dawson instead!
Stefan