c++ - How do I express this? -
i'm trying work out how write following:
total = (value * 0.95 ^ 0) + (value * 0.95 ^ 1) + (value * 0.95 ^ 2) ...
or:
x = (y * z ^ 0) + (y * z ^ 1) + (y * z ^ 2) + (y * z ^ 3) ...
this expresses how calculate x 4 iterations, how can express work variable number of iterations? create loop , add values together, i'd find single equation solves this.
i'm using c++ guess isn't language specific problem (sorry literally don't know else ask question!).
any ideas?
thanks, chris.
equation-wise solving, geometric series , can therefore calculated with
double geometric_series(double y, double z, int n) { return y * (std::pow(z, n) - 1.0) / (z - 1.0); }
but same result can obtained fun c++ metaprogramming: if know number of iterations in advanced , you're allowed use c++17 features , fold expressions follows
template<std::size_t... n> double calculate_x(double y, double z, std::index_sequence<n...>) { // [0;n[ auto f = [](double y_p, double z_p, double exp) { return y_p * std::pow(z_p, exp); }; return (f(y, z, n) + ...); } template <std::size_t n> auto calculate_x(double y, double z) { return calculate_x(y, z, std::make_index_sequence<n>{}); }
alternatively can done pre-c++17 templates
template <int n> double calculate_x(double y, double z) { return calculate_x<n-1>(y, z) + (y * std::pow(z, n - 1)); } template <> double calculate_x<0>(double, double) { return 0; }
otherwise simpler solution use loop
double calculate_x_simple(double y, double z, int n) { double ret = 0.0; (int = 0 ; < n ; ++i) ret += y * std::pow(z, i); return ret; }
driver code above
int main() { // x = (y * z ^ 0) + (y * z ^ 1) + (y * z ^ 2) + (y * z ^ 3) double y = 42.0; double z = 44.5; std::cout << (calculate_x<3>(y, z) == calculate_x_simple(y, z, 3)); // 1 }
Comments
Post a Comment