Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a complex number has NaN

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?

like image 521
dagur Avatar asked Feb 21 '12 10:02

dagur


2 Answers

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";
}
like image 162
ev-br Avatar answered Sep 29 '22 06:09

ev-br


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.)

like image 33
Sergey Zv Avatar answered Sep 29 '22 07:09

Sergey Zv