Search code examples
python-2.7equations

Summation of Equation Program


So basically I'm trying to make a program that will do equation for every value of nStart to nEnd. This is my code so far

def summation(nStart , nEnd , eqn): 
    sum = 0
    while nStart - 1 != nEnd:
        sum = sum + eqn
        nStart += 1
    return sum

print summation(1 , 5 ,  n + 1)

I get that n is not defined in the last line. I guess it's because I have n + 1 but how do I solve that? I tried making n = 0 but then that doesn't help because then eqn is just 1 and not an equation.


Solution

  • You could use a lambda function as an argument. For example:

    def summation(start, end, eqn):
        sum = 0
        # Note that the *end* value will not be used, since range stops at *end-1*
        for i in range(start, end):
            sum+=eqn(i)
        return sum
    
    print summation(0,10,lambda x: x+1)
    print summation(0,10,lambda x: x**2)
    

    Will return:

    55
    285
    

    Since

    formula

    formula2

    Hope this gives you a useful tool to explore and modify if it doesn't do exactly what you are after.