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
项的泰勒级数相加。