c - Stirling approximation producing a different output than expected -
so new c , learning syntax. have come across problem though. trying prove stirlings approximation where
ln (n!) = n ln (n) - (n)
so when make print statements within code test whether each element of array producing output of array number want be. it's far it.
#include <stdio.h> #include <stdlib.h> #include <math.h> double * natural_log (); /* obtain natural log of 0 100 , store each value in array */ double * approximation (); /* use sterling approximation caluculate numbers 0 - 100 , store in array */ double * difference (); /* calculate difference between arrays */ double * percentage (); /* calculate percentage of difference , return array */ int main () { natural_log (); /* approximation (); */ return 0; } double * natural_log () { static double natural_array[101]; /* set array */ int i; /* set integer increase array value */ natural_array[0] = 0.0; /* set first value in array */ natural_array[1] = log(2); double x; x = natural_array [1]; (i = 2; <=100; i++) { /* set loop increment */ natural_array[i] = x + log(1 + i); x = natural_array[i]; **printf ("element[%d] = %d\n", i, x);** } return natural_array; } double * approximation () { static double approximation_array[99]; /* set array */ int i; /* set integer increase array value */ (i = 0; <=100; i++) { approximation_array[i] = (i) * log(i) - (i); } return approximation_array; }
with print statement in bold produces output
element[2] = 688 element[3] = 2048 element[4] = 1232 element[5] = 688 ..... ..... element[100] = 544
i these numbers it's not supposed spitting out on output can explain why is? thank you!
you not printing right data type with
printf ("element[%d] = %d\n", i, x);
which wants print int
type. please try
printf ("element[%d] = %e\n", i, x);
you must declare array thus
static double natural_array[101];
either that, or reduce loop limit. better tie 2 perhaps this
#define elements 100 ... static double natural_array[elements]; ... (i = 2; < elements; i++) { ...
Comments
Post a Comment