joshj
joshj

Reputation: 583

how to find necessary multiplier for loop?

#include <iostream>
using namespace std;
int main() {

  float result = 50.0f;
  float multiplier = 0.5f;
  float fixed_multiplier = 1.0f - multiplier * 0.001f;
  for (int i = 0; i < 1000; ++i) {
    result *= fixed_multiplier;
  }

  cout << result << endl; // 30.322 -- want approximately 25
}

After the 1000 iterations, I want result to equal multiplier*result (result==25). How do I find what I need to modify multiplier (in fixed_multiplier) to get the desired result?

Upvotes: 1

Views: 292

Answers (2)

zneak
zneak

Reputation: 138171

Your for loop is summarized by this mathematical equation:

result * fixed_multiplier ^ 1000 = result * multiplier

You can solve this equation to find your answer.

You can get the same result in C using the pow function:

fixed_multiplier = pow(multiplier, 0.001);

Upvotes: 5

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272657

You have the following relationship:

result_out = result * fixed_multiplier^1000

where ^ denotes "to the power of". Simple algebra gives you this:

fixed_multiplier = (result_out / result) ^ (1/1000)

Upvotes: 2

Related Questions