-1

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?

Germano Massullo
  • 2,572
  • 11
  • 40
  • 55
  • 6
    Have you tried to print the value of `a` in your `exponential()`? – Lee Duhem May 24 '14 at 10:32
  • 2
    just a comment -- this kind of forward declaration is absolutely not necessary. If you really want to do this in one file, leave the func declaration on top, and put the definition to the bottom of your code – Peter Varo May 24 '14 at 10:34

1 Answers1

6

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.

taskinoor
  • 45,586
  • 12
  • 116
  • 142
Markus Johnsson
  • 3,949
  • 23
  • 30