【发布时间】:2018-02-19 06:36:01
【问题描述】:
我正在尝试计算 x_0 = 1 处 e^x 的泰勒级数展开式。我很难理解我真正要寻找的是什么。我很确定我正在尝试找到当 x_0 = 1 时 e^x 时的十进制近似值。但是,当我在 x_0 = 0 时运行此代码时,我得到了错误的输出。这让我相信我计算不正确。
这是我的课程 e.hpp
#ifndef E_HPP
#define E_HPP
class E
{
public:
int factorial(int n);
double computeE();
private:
int fact = 1;
int x_0 = 1;
int x = 1;
int N = 10;
double e = 2.718;
double sum = 0.0;
};
这是我的 e.cpp
#include "e.hpp"
#include <cmath>
#include <iostream>
int E::factorial(int n)
{
if(n == 0) return 1;
for(int i = 1; i <= n; ++i)
{
fact = fact * i;
}
return fact;
}
double E::computeE()
{
sum = std::pow(e,x_0);
for(int i = 1; i < N; ++i)
{
sum += ((std::pow(x-x_0,i))/factorial(i));
}
return e * sum;
}
在 main.cpp 中
#include "e.hpp"
#include <iostream>
#include <cmath>
int main()
{
E a;
std::cout << "E calculated at x_0 = 1: " << a.computeE() << std::endl;
std::cout << "E Calculated with std::exp: " << std::exp(1) << std::endl;
}
输出:E calculated at x_0 = 1: 7.38752E calculated with std::exp: 2.71828
当我更改为 x_0 = 0.E calculated at x_0 = 0: 7.03102 E calculated with std::exp: 2.71828
我做错了什么?我是否错误地执行了泰勒级数?我的逻辑在某处不正确吗?
【问题讨论】:
-
投反对票的人能解释一下他们的理由吗?
-
您的阶乘函数容易溢出。并且不要首先计算它:而是计算一个运行除数。计算更稳定,速度更快。
-
另外,你为什么使用
e的硬编码值,并用std::pow来提高它,而不是使用std::exp? -
@Bathsheba,你能给我一个运行除数的例子吗?
-
@AlgirdasPreidžius,我试图在 x_0 等于 1 时逼近 e^x。我需要事先知道 e,因为 x_0 等于 1 时的泰勒级数展开式是:e^x_0 * n=0 到 inf (x-x_0)^n/n! 的总和。我提出它,所以我已经有了第一个任期。
标签: c++ math taylor-series