By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,100 Members | 2,846 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,100 IT Pros & Developers. It's quick & easy.

How to create a sum?

P: n/a
Hi,

I want to create a sum with a variable n that goes from 0 to a fixed value.

For example:
the sum of (a*b^(c-n)) where a, b and c are constants and n goes from 0 to the value of c.

Like this:
c
Σ (a*b^(c-n))
n=0

So it would be:
if a = 10 and b = 20 and c = 30

10*20^(30-0) + 10*20^(30-1) + 10*20^(30-2) + ... + 10*20^(30-30)

This can be done with a for sling I would assume but I can't get it to work properly..

Expand|Select|Wrap|Line Numbers
  1. import math
  2. a = 10
  3. b = 20
  4. c = 30
  5.  
  6.  
  7. for n in range(c):
  8.     result = a*math.pow(b, c-n)
  9.  
  10. print result
  11.  
  12.  
This only gives the result of a*b though.

Any ideas? =)
Nov 8 '10 #1
Share this Question
Share on Google+
2 Replies


P: n/a
never mind.
I solved it =)
Expand|Select|Wrap|Line Numbers
  1. import math
  2. a = 10
  3. b = 20
  4. c = 30
  5. n = 0
  6.  
  7.  
  8. while n != c:
  9.     result += a*math.pow(b, c-n)
  10.     n += 1
  11. print result
  12.  
  13.  
Nov 9 '10 #2

bvdet
Expert Mod 2.5K+
P: 2,851
Why not use the ** operator? The following uses built-in function sum() and a list comprehension.
Expand|Select|Wrap|Line Numbers
  1. >>> a,b,c=10,20,30
  2. >>> sum([a*b**(c-n) for n in range(c)])
  3. 11302545515789473684210526315789473684200L
  4. >>> 
Nov 10 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.