What does "-nan" mean and what causes it?

  algorithm, c++, double, floating-point, math

I know that nan means "not a number",but this code using the Gaussian elimination algorithm output "-nan" :

#include <bits/stdc++.h> 
#include <algorithm>

using namespace std;
typedef long long ll;
const int N=55;
const double eps=1e-7;
int n;

struct mat {
    int l,c;
    double p[N][N];
    double* operator [] (int i) {return p[i];}
}a;

bool flo0(double &x) {return (fabs(x)<=eps)?1:0;}

void REF() {
    for(int i=1;i<=n;i++) {
        int flag=i;
        for(int j=i;j<=n;j++) {
            if(fabs(a[j][i])>fabs(a[flag][i])) flag=j;
        }
        for(int j=1;j<=n+1;j++) swap(a[flag][j],a[i][j]);
        if(flo0(a[i][i])) continue;
        for(int j=i+1;j<=n;j++) {
            double t=a[j][i]/a[i][i];
            for(int k=i;k<=n+1;k++) {
                a[j][k]-=t*a[i][k];
            }
        }
    }
}

void RREF() {
    for(int i=n;i>=1;i--) {
        if(flo0(a[i][i])) continue;
        for(int j=n+1;j>=i;j--) a[i][j]/=a[i][i];
        for(int j=i-1;j>=1;j--) {
            double t=a[j][i];
            for(int k=n+1;k>=1;k--) {
                a[j][k]-=t*a[i][k];
            }
        }
    }
    bool no=false,many=false;
    for(int i=1;i<=n;i++) {
        int t=0;
        for(int j=1;j<=n;j++) if(flo0(a[i][j])==false) ++t;
        if(t==0 && flo0(a[i][n+1])==false) no=true;
        if(t==0 && flo0(a[i][n+1])) many=true;
    }
    if(no) printf("-1");
    else if(many) printf("0");
    else for(int i=1;i<=n;i++) {if(flo0(a[i][n+1])) a[i][n+1]=0.0;printf("x%d=%.2lfn",i,a[i][n+1]);}
}

int main() {
    scanf("%d",&n);
    for(int i=1;i<=n;i++) {
        for(int j=1;j<=n+1;j++) {
            cin>>a[i][j];
        }
    }
    REF();
    RREF();
    
    return 0;
}

I can’t get the input,but the output is

x1=-nan
x2=-nan
x3=-nan
x4=-nan
x5=-nan
x6=-nan
x7=-nan
x8=-nan
x9=-nan
x10=-nan
x11=-nan
x12=-nan
x13=-nan
x14=-nan
x15=-nan
x1...

I initially thought the reason is that I didn’t use "eps" when I determining if a double equals to 0,but after I added,the error still existed.
I can’t get any information about "-nan" from google.

Source: Windows Questions C++

LEAVE A COMMENT