0

我目前正在尝试计算函数 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;

}
4

0 回答 0