Question
October 10, 2010 at 11:54 PM
jfrickson

Need help with an algorithm

by jfrickson . Updated 15 years, 10 months ago

I have a function that does a calculation something like this:

for (l=1; l<=n; ++l) r += a / pow(1+x, l); The loop can be replaced by something like the following: f = 1 / pow(x, n); r = a * ((1 - f) / x); (Note, this is a MUCH simplified version of my code, so the above may not be exactly correct, but if you know about geometric progressions, you will get the idea.) For that case, I get the exact same results with both sets of code. However, I don't know if I can eliminate the loop in two other cases. One is almost identical to the one above, but the loop starts at l=3 instead of l=1. The other case, instead of pow(1+x, l), it has pow(1+x, l+c) where c is a floating-point number between 0.0 and 1.0. Can the loops in these other two cases be replaced by a single calculation like the first case?

This discussion is locked

All Comments