#include <iostream> #include <cmath>
using namespace std;
const double epsilon = 1E-14; const double PI = 3.141592653589793;
double factorial(int n); double dbl_factorial(int n); double arcsin(double x); double rad2deg(double x); double max(double x,double y); bool approx_equal(double x,double y);
int main() { //测试驱动 for (double i = -1 ; i <= 1; i += 0.2) { cout << rad2deg(arcsin(i)); if (approx_equal(i,sin(arcsin(i)))) { cout << " approx equal!" << endl; } else { cout << " not equal!" << endl; } } return 0; }
double factorial(int n) { //阶乘 double result = 1; if (n == 0) return 1;
for (int i = 1 ; i <= n; i++) { result *= i; }
return result; }
double dbl_factorial(int n) { //奇数的双阶乘 double result = 1; int i = n; if (n % 2 == 0) return 0; if (n == 1) return 1;
do { i -= 2; result *= i; } while ( i > 1);
return result; }
double arcsin(double x) { //反正弦函数的泰勒级数公式 double xnew; int i = 1; double result = 0;
if (x < -1 || x > 1) return -255; do { xnew = (pow(x,i) * pow(dbl_factorial(i),2)) / (1.0 * factorial(i)); result += xnew; i += 2; } while (xnew > epsilon);
return result; }
double rad2deg(double x) { //弧度转成角度 return x / PI * 180; }
double max(double x,double y) { //两数最大值 //数学库中居然没有,真是晕。。。。 return x > y ? x : y; }
bool approx_equal(double x,double y) { if (x == 0 && y != 0) return fabs(y) <= epsilon; if (y == 0 && x != 0) return fabs(x) <= epsilon; if (x == 0 && y == 0) return true; return fabs(x - y) / max(fabs(x),fabs(y)) <= epsilon; } 为什么有一半以上的计算得的反正弦值不能精确的用sin函数还原???为什么精度差那么多。。。。请高手赐教,谢谢。。。。。。