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);
}
使用以下代码,我尝试sin()
基于 N 项泰勒级数实现该函数,但是当我比较该函数的结果时,结果不正确,我不知道为什么。运行以下代码:
std::cout<<sin(2 * M_PI * 0.5)<<" "<<taylor_sine<13>(2 * M_PI * 0.5);
结果是1.22465e-16 -16546.9
据我所知,我正在正确计算系列,所以我不确定出了什么问题。