log function misbehaviour!!! Any clue?
I am writing some program in C. It has a part where it does some probability calculations, where I am using log function. normal library function log()...
The code is something like this
double somevalue = 0.29558101472995091;
temp = log(somevalue)
And guess what? The temp gets value -1856.0000000000000!!!
As the value given开发者_Go百科 for log was inside some struct I wrote this test code too, and got the same results...
int main()
{
double somevalue;
double temp;
somevalue = 0.29558101472995091;
temp = log(somevalue);
return 0;
}
Results:
Somevalue = 0.29558101472995091
temp = -1856.0000000000000
Isn't it crazy. Anyone has some clue on whats going on here.
And I am using Visual Studio 2005 for this. Can't get my hands on someother compiler now.
Thanks,
Microkernel :)
You need to #include <math.h>
so the compiler will call log()
correctly.
Using VC10, I get the following result from printf ("log(%lf) = %lf\n", somevalue, temp )
when math.h
is included:
log(0.295581) = -1.218812
If math.h
isn't included, I get:
log(0.295581) = -1856.000000
What's probably happening is that the compiler expects the returned value from the call to log()
to be int
which is then converted to a double
to store in temp
. I don't know off the top of my head how floating point results are returned by the compiler, but I'd guess they're returned in the FP(0) register, while an int result is returned in EAX (assuming an x86 Win32 platform). So the value to compiler gets in this case might not even have any relationship with the value the log()
function tries to return.
If you set the warning level to /W3
you'll get a warning about the problem:
C:\TEMP\test.c(10) : warning C4013: 'log' undefined; assuming extern returning int
In my opinion, unless you're working with a really old codebase that doesn't take advantage of function prototypes, it might make good sense to turn that warning into an error (of course, when compiled as C++ this is already an error):
#pragma warning( error : 4013) // or use the `/we4013` compiler option
Here's the compilable test:
#include <stdio.h>
//#include <math.h>
int main()
{
double somevalue;
double temp;
somevalue = 0.29558101472995091;
temp = log(somevalue);
printf ("log(%lf) = %lf\n", somevalue, temp);
return 0;
}
Looks like your syntax is correct. How are you printing your results? If you're using a printf statement, make sure you have your format string correct.
It should go like in this example:
printf ("log(%lf) = %lf\n", somevalue, temp );
精彩评论