用泰勒展開式求數學量(三角函式,e^x)
阿新 • • 發佈:2019-01-28
arctanx
arctanx=x-x^3/3+x^5/5-x^7/7+.......
#include<iostream> using namespace std; double arctan(double x){ double sqr=x*x; double e=x; double r=0; int i=1; while(e/i>1e-15){ double f=e/i; r=(i%4==1)? r+f : r-f ; e=e*sqr; i+=2; } return r; } int main(){ double a=arctan(1/5.0);//注意要寫成5.0,否則取整為0 cout<<a<<endl; return 0; }
sinx
sinx=x/1!-x^3/3!+x^5/5!-x^7/7!;
不過,c++系統函式中有sin,cos,tan#include<iostream> #include<cmath> using namespace std; double sin(double x){ double g=0; double t=x; int n=1; do{ g+=t; n++; t=-t*x*x/(2*n-1)/(2*n-2); } while(fabs(t)>=1e-6); return g; } int main(){ double a; cin>>a; cout<<sin(a)<<endl; return 0; }