Monte Milanuk wrote:
We save the whips and chains for the more hardened questers. Newcomers get the feathers.
There are many ways to handle this. Others have given some hints. The simplest IMHO is to set the range stride to 4 instead of 2 and then use x += 4.0/i - 4.0/(i + 2). You could also use a multiplier (let's call it m) that alternates between 1 and -1. Roughly: x = 0 m = 1 for in in range... x += 4.0/i*m m = -m For more generality and anticipating more complex algorithms: import operator ops = (operator.add, operator.sub) x = 0 m = 0 for in in range... x = ops[m](x, 4.0/i) m = 1-m And just for the heck of it you could write 2 for loops, each with a stride of 4. The first would just add all the fractions to be added and the second would add all the fractions to be subtracted, then combine them. Throwing in the sum function and generator expressions: pi = sum(4.0/i for i in range(1, n*2, 4)) - sum(4.0/i for i in range(3, n*2, 4)) Applying sum and generator expressions to my original solution you get: pi = sum(4.0/i - 4.0/(i + 2) for i in range(1, 4*n, 4)) Ah I can go on can't I? A lot more than you asked for! -- Bob Gailer Chapel Hill NC 919-636-4239 When we take the time to be aware of our feelings and needs we have more satisfying interatctions with others. Nonviolent Communication provides tools for this awareness. As a coach and trainer I can assist you in learning this process. What is YOUR biggest relationship challenge? |
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor