How to create a sum?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Peter M

    How to create a sum?

    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..

    Code:
    import math
    a = 10
    b = 20
    c = 30
    
    
    for n in range(c):
        result = a*math.pow(b, c-n)
    
    print result
    This only gives the result of a*b though.

    Any ideas? =)
  • Peter M

    #2
    never mind.
    I solved it =)
    Code:
    import math
    a = 10
    b = 20
    c = 30
    n = 0
    
    
    while n != c:
        result += a*math.pow(b, c-n)
        n += 1
    print result

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      Why not use the ** operator? The following uses built-in function sum() and a list comprehension.
      Code:
      >>> a,b,c=10,20,30
      >>> sum([a*b**(c-n) for n in range(c)])
      11302545515789473684210526315789473684200L
      >>>

      Comment

      Working...