Reputation: 55
#include<stdio.h>
#include<math.h>
#define PI 2*acos(0.0)
int main(void)
{
double theta;
theta=tanh(1/(sqrt(3.0)));
printf("With tanh function = %lf\n",theta);
printf("Actual value = %lf\n",PI/6.0);
return 0;
}
Output:
With tanh function = 0.520737
Actual value = 0.523599
Why are these two values different? It should me same as my understanding.
Upvotes: 2
Views: 346
Reputation: 241881
You've got that identity completely wrong.
The actual identity is
tanh-1(i ⁄ √3) = πi ⁄ 6 (where i is the imaginary unit, √-1)
C11 can easily validate that:
#define _XOPEN_SOURCE 700
#include<stdio.h>
#include<math.h>
#include<complex.h>
int main(void)
{
complex double theta=catanh(I/sqrt(3.0));
printf("With atanh function = %lf\n",cimag(theta));
printf("Actual value = %lf\n",M_PI/6);
return 0;
}
(Live on coliru: http://coliru.stacked-crooked.com/a/f3df5358a2be67cd):
With atanh function = 0.523599
Actual value = 0.523599
M_PI
will be in math.h
in any Posix compliant system. Apparently, on Windows you use
#define _USE_MATH_DEFINES
but I have no idea whether Visual Studio supports complex.h
.
Upvotes: 6
Reputation: 263507
Your program has a couple of minor flaws, but none that cause it to misbehave.
Your PI
macro should be parenthesized:
#define PI (2*acos(0.0))
but you happen to get away without the parentheses because of the way you use it.
The correct format for printing a double
value is actually %f
, but %lf
is accepted as well. (%Lf
is for long double
. %f
also works for float
, because float
arguments to variadic functions are promoted to double
). This also doesn't affect your program's behavior.
In fact, your program is working correctly. I've confirmed using an HP 42S emulator that tanh(1/(sqrt(3.0)))
is approximately 0.520737 (I get 0.520736883716).
The problem is your assumption that the result should be π/6.0. It isn't.
Upvotes: 3