Caterpillar Caterpillar - 1 year ago 94
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)
return 0;

I obtain:



Answer Source

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.