Caterpillar Caterpillar - 3 months ago 26
C Question

nan when executing printf

When I execute program

#include <stdio.h>
#include <math.h>
#include <unistd.h>

double exponential(double u);

double exponential(double u)
{
double a = (double)rand();
return (-u * log(1.0 - a));
}

int main(void)
{
printf("%e\n",exponential(2.3));
return 0;
}


I obtain:

nan


Why?

Answer

Because rand() returns an integer (between 0 and RAND_MAX), most often this integer is larger than 1 and your log expression will be negative. log returns NaN (not a number) for negative inputs.

Comments