i working on implementation of sin() function based on taylor series using templates. code far goes follows:
template<unsigned i> struct factorial{ enum{ value = * 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 <unsigned term> inline double taylor_sine_term(double const& x) { return (power<term>(-1) / factorial<(2*term)+1>::value) * power<(2*term)+1>(x); } the issue having creating function use taylor_sine_term function expand series n number of terms.the function functionally equivalent following.
template<unsigned terms> inline double taylor_sine(double const& x){ return taylor_sine_term<1>(x)+taylor_sine_term<2>(x) + ... + taylor_sine_term<terms>(x); } basically need figure out way generate sequence of integer constants can used term number template parameter in taylor_sine_term function n number of terms , sum them together. result expand full taylor series n number of terms. problem don't know start.
any appreciated, thanks.
same way wrote other ones: recursive case , base case:
template<unsigned terms> inline double taylor_sine(double const& x) { return taylor_sine_term<terms>(x) + // current term taylor_sine<terms-1>(x); // rest of terms } template <> inline double taylor_sine<0>(const double& x) { return taylor_sine_term<0>(x); } alternatively, use index sequence trick of them:
template <unsigned terms> inline double taylor_sine(double const& x) { return taylor_sine(x, std::make_index_sequence<terms+1>{}); } template <unsigned terms, size_t... is> inline double taylor_sine(const double& x, std::index_sequence<is...> ) { double res = 0.0; (double t : {taylor_sine_term<is>(x)...}) { res += t; } return res; /* or in c++17 return (taylor_sine_term<is>(x) + ...); */ } note should change base case on power power<0>.
Comments
Post a Comment