gpt4 book ai didi

c++ - 基于泰勒级数的基于模板的 Sin() 实现产生不正确的结果 C++

转载 作者:行者123 更新时间:2023-11-28 00:14:20 26 4
gpt4 key购买 nike

template<unsigned I>
struct factorial{
enum{

value = I * factorial<I -1>::value
};

};
template<>
struct factorial<0>
{
enum{ value = 1};
};

template<unsigned pow>
inline double power(double const& value){
return value * power<pow-1>(value);
}
template<>
inline double power<1>(double const& value){
return value;
}
template<>
inline double power<0>(double const& value){
return 1;
}

template<unsigned term>
inline double taylor_polynomial(double const& x){
return power<term>(x) / factorial<term>::value;
}

template <unsigned term>
inline double taylor_sine_term(double const& x) {
return (power<term>(-1) / factorial<(2*term)+1>::value) * power<(2*term)+1>(x);
}

template<unsigned terms>
inline double taylor_sine(double const& x){
return taylor_sine_term<terms-1>(x) + taylor_sine_term<terms>(x);
}
template <>
inline double taylor_sine<0>(double const& x) {
return taylor_sine_term<0>(x);
}

使用下面的代码,我尝试基于 N 项泰勒级数实现 sin() 函数,但是当我比较函数的结果时,结果不正确,我不是确定为什么。运行以下代码:

std::cout<<sin(2 * M_PI * 0.5)<<"   "<<taylor_sine<13>(2 * M_PI * 0.5);

结果在 1.22465e-16 -16546.9

据我所知,我正在正确计算系列,所以我不确定出了什么问题。

最佳答案

你调用了错误的函数来递归:

template<unsigned terms>
inline double taylor_sine(double const& x){
return taylor_sine_term<terms-1>(x) + taylor_sine_term<terms>(x);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}

您要添加项 n 和项 n-1 而不是添加项 nn- 的泰勒级数1 条款。

关于c++ - 基于泰勒级数的基于模板的 Sin() 实现产生不正确的结果 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31323961/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com