Search code examples
c++nanfixed-pointinfinity

implementation of isnan() function


I am a beginner to c++ programming and I am given a task of implementation of fixed point math arithmetic in c++. here I am trying to implementation a function isnan() which returns true if the number is not-a-number else will return false.

Test file

#include "fixed_point_header.h"
int main()
{
fp::fixed_point<long long int, 63> a=fp::fixed_point<long long int, 63>::positive_infinity(); // will assign positive infinity value to a from an function from header 
fp::fixed_point<long long int, 63> b=fp::fixed_point<long long int, 63>::negative_infinity(); // will assign positive infinity value to b from an function from header 
float nan=fp::fixed_point<long long int, 63>::isnan(a,b);
printf( "fixed point nan value  == %f\n", float (nan));
} 

In the header I want to do somewhat like the code shown below if positive and negative infinity values are added, the isnan function should return 1 else 0.

Header file

#include fixed_point_header
static fp::fixed_point<FP, I, F> isnan (fp::fixed_point<FP, I, F> x,fp::fixed_point<FP, I, F> y){
/*if ( x + y ) happens, ie. x and y are infinities
      {
 should return 1; }
       else {
 should return 0; }
      } */

can anyone please tell how to proceed with it? or how to solve this paradigm


Solution

  • I am trying to implementation a function isnan() which returns true if the number is not-a-number else will return false.

    That's simple enough; define a reserved value to represent nan (as you have for the infinities), and compare with that:

    bool isnan(fixed_point x) {
        return x == fixed_point::nan();
    }
    

    I want to do somewhat like the code shown below if positive and negative infinity values are added, the isnan function should return 1 else 0

    It would be the responsibility of the addition operator to check the inputs and return nan if appropriate:

    fixed_point operator+(fixed_point x, fixed_point y) {
        if (x == fixed_point::nan() || y == fixed_point::nan()) {
            return nan;
        }
        if (x == fixed_point::positive_infinity()) {
            return y == fixed_point::negative_infinity() ? fixed_point::nan() : x;
        }
        // and so on
    }
    

    then the test in main becomes:

    bool nan = fixed_point::isnan(a+b);