我的麦克劳林级数扩展代码做错了什么?

问题描述 投票:0回答:2

(https://i.stack.imgur.com/3LgGA.png) 我一直在尝试用 c++ 为 sin(x) 的 Mclaurin 级数展开编写代码,作为我的编程入门课程的复习,但我的结果始终不等于示例运行。我几个小时以来一直试图解决这个问题,但无济于事。请帮忙。

#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
double factorial(int num);
double sum(double number, int n);
int main() {
double number, sin;
int n;
    cout<<"Enter the value of x: ";
    cin>>number;
    cout<<"Enter the number of terms: ";
    cin>>n;
    sin=sum(number,n);
    cout<<"sin("<<number<<") = "<<fixed<<showpoint<<setprecision(6)<<sin<<endl;

    return 0;
}
double factorial(int num){
    double sum=1;
    for(int x=num; x>=1;x--){
        sum*=x;
    }
    return sum;
}
double sum(double number, int n){
    int count=3;
    double term,term1, sum=0, sum2=0, totalSum;

    for(int i=1;i<n-1;i+=2 ){
        term1=(pow(number, count))/ factorial(count);
        sum+=term1;
        count+=4;
        }
    for(int j=0;j<n-2;j+=2){
            term=pow(number, count)/ factorial(count);
            sum2+=term;
            count+=4;
        }
    totalSum=number+sum+sum2;
    return totalSum;
    }

c++ c++11 math series
2个回答
0
投票

我不知道你的有什么问题 - 它看起来过于复杂。

这里有更简单的事情:

double fact(unsigned n)
{
    double result = 1;
    do
    {
        result *= n;
    }
    while(--n);
    return result;
}

double msin(double x, unsigned n)
{
    double result = x;
    for(unsigned i = 0; i < n; i++ )
    {
        result += (i % 2 ? 1 : -1) * pow(x, 3 + 2 * i) / fact(3 + 2 * i);
    }
    return result;
}

int main(void)
{
    for(unsigned n = 2; n < 10; n++)
        printf("%.30f\n%.30f\n\n", msin(1.4, n), sin(1.4));
}

https://godbolt.org/z/o3Wc8e8GY


0
投票

您不需要幂函数或阶乘函数。它应该看起来更像这样:

def sine(t, n):
    result = 0.0
    term = t
    sign = 1.0
    for i in range(1, n):
        result += sign*term
        sign *= -1.0
        term *= t*t/(2*i)/(2*i+1)
    return result

这是 Python,但您应该能够轻松地弄清楚如何将其移植到 C++。

另一件事需要考虑:标准化输入角度。级数展开仅对接近展开点 0 的 x 值正确。您需要利用正弦函数的周期性。

© www.soinside.com 2019 - 2024. All rights reserved.