基于泰勒级数的基于模板的Sin()实现在c++中产生不正确的结果
template based Sin() implementation based on taylor series produces incorrect results C++
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
项相加而不是将n
项和n-1
项的泰勒级数相加。
相关文章:
- 使用2个键的cpp-stl::优先级队列排序不正确
- 正弦级数方程计算不正确
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 密码登录程序将永远循环并显示不正确的结果
- 在C++中返回不正确的楼层函数值
- 形状对象的旋转和缩放不正确C++
- C++ 读取文件读取文件不正确
- 关于类的 Python 文档 - 对C++的引用不正确
- 特征 LLT 模块给出不正确的结果?
- glibcxx STL 在实现 std::valarray::sum() 时是否不正确?
- 如果语句逻辑不正确
- 来自逆 vp 矩阵和相机位置的光线方向不正确
- 不正确的操作数类型 MSVC
- 数组填充了不正确的值
- 我是否不正确地集中了这些字符数组?
- 为什么除非我使用 cout,否则我的值不正确?
- 计算幂级数的数学结果不正确
- 为什么 sizeof 在 C++ 中给出不正确的字节数?
- atoi() 在应用于大型命令行参数时会产生不正确的值
- 不正确的比较和交换计数器输出用于快速排序功能