为什么math.h库中的tanh函数会给出错误的结果?

rh9*_*939 2 c math.h

#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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

tanh函数= 0.520737

实际值= 0.523599

为什么这两个值不同?它应该和我的理解一样.

ric*_*ici 6

你的身份完全错了.

实际的身份是

tanh -1(i /√3)= πi/6(其中i是虚数单位,√-1)

C11可以轻松验证:

#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;
}
Run Code Online (Sandbox Code Playgroud)

(住在coliru:http://coliru.stacked-crooked.com/a/f3df5358a2be67cd ):

With atanh function = 0.523599
Actual value = 0.523599
Run Code Online (Sandbox Code Playgroud)

M_PImath.h在任何Posix兼容系统中.显然,在Windows上使用

#define _USE_MATH_DEFINES
Run Code Online (Sandbox Code Playgroud)

但我不知道Visual Studio是否支持complex.h.