原理是利用 arctan(x) 的泰勒展开式;同时当 x 的绝对值大于 1 时,利用arctan(x) + arctan(1/x) = pi/2 计算。
#include <iostream>
#include <cmath>
using namespace std;
const double pi = 3.1415926;
double tarctan(double x){
double sqr = x * x;
double e = x;
double r = 0;
int i = 1;
while (fabs(e / i) > 1e-15){
double f = e / i;
r = (i % 4 == 1)? r + f : r - f;
e *= sqr;
i += 2;
}
return r;
}
double arctan(double x){
if (x >= -1 && x <= 1)
return tarctan(x);
else{
if (x > 0)
return (pi/2 - tarctan(1 / x));
else
return (-pi/2 - tarctan(1 / x));
}//else
}//arctan
int main(){
double x;
cin >> x;
cout << "arctan(x): " << arctan(x) << endl;
cout << "atan(x): " << atan(x) << endl;
return 0;
}