Gregory Hildstrom Projects Publications Resume Links Contact About Google+ Facebook Youtube Donate




nantest

nantest is a simple demo program that shows how to test for calculations resulting in Not a Number (nan), positive infinity (inf), and negative infinity (-inf) in c++. nantest uses the finite() function call. sqrt(-1.0) would result in nan. 1/0 would result in inf. -1/0 would result in -inf.
//nantest.cpp
//simple program to demonstrate testing of non-finite values

//built and tested with
//g++ -o nantest nantest.cpp
//on Red Hat Linux gcc 3.2.2 kernel 2.4.22 on i686

#include <iostream>
using namespace std;


int main(){


	float denominator = 0;

	float plusinfinity = 1/denominator;
	float minusinfinity = -1/denominator;

	float nanumber = sqrt(-1.0);



	cout << "denominator: " << denominator;
	if(!finite(denominator))
		cout << " is not finite.\n";
	else
		cout << " is finite.\n";


	cout << "plusinfinity: " << plusinfinity;
	if(!finite(plusinfinity))
		cout << " is not finite.\n";
	else
		cout << " is finite.\n";


	cout << "minusinfinity: " << minusinfinity;
	if(!finite(minusinfinity))
		cout << " is not finite.\n";
	else
	 	cout << " is finite.\n";


	cout << "nanumber: " << nanumber;
	if(!finite(nanumber))
		cout << " is not finite.\n";
	else
	 	cout << " is finite.\n";


	return 0;
}//end main