我目前正在尝试计算函数x ^(1/2)的泰勒级数之和 (这就是它在Wolfram中的表现:http://www.wolframalpha.com/input/?i=taylor+series+x%5E%281%2F2%29) 这是所需的公式:http://i.imgur.com/YvVOQIR.png
我无法计算二项式系数。我将它分为两部分(分母中的分子和阶乘)。分子总是计算为0值(除了通过初始化应该为1的一次)。
编辑:将int更改为双精度(此处也更新了代码)并且运行良好 并编辑了代码:
#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
double x;
double e;
void taylor() // taylor series
{
double result = 0;
double previous = 1;
for(double n=0; abs(previous-result) > e;n++) //cycle for caltucalting to given precision
{
double binomial=1; // variable for binomial coef
double fact=1; //variable for factorial
double topbin=1; //variable for top part of binomial coef
previous=result;
for(double k=1;k<=n;k++)
{
fact *= k; //calcucating factorial
topbin *= ((1.0/2.0)-k+1); //calculating top part of binomial coef
}
binomial=double(topbin)/double(fact); //calculating whole binomial coef
result+=binomial*(pow((-1+x),n)); // calculating taylor series
cout<<"topbin "<<topbin<<endl;
cout<<"fact "<<fact<<endl;
cout<<"binomial "<<binomial<<endl;
cout<<"taylor sum on "<<n<<" iteration: "<<result<<endl;
cout<<endl;
}
cout<<"taylor sum:"<<result<<endl;
}
void main()
{
cout<<"Enter x"<<endl;
cin>>x;
cout<<"Enter e"<<endl;
cin>>e;
taylor();
double y=1/sqrt(pow(x,2)-1);
cout<<"y= "<<y<<endl;
}