6

I was wondering how one can represent a sum in python without loops like here

where we have:

def rosen(x):
    """The Rosenbrock function"""
    return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0)

My function is the following: V(theta) = Sum(i=1->N)[a0*(cos(i*theta)]

Thank you in advance for your help :):)

1
  • You mean without Numpy? How come? Commented Aug 28, 2012 at 21:22

3 Answers 3

4

Your formula is:

V(theta) = Sum(i=1->N)[a0*(cos(i*theta)]

which means: sum all values of a0*(cos(i*theta) for a given value theta in the range 1 to and including N.

This becomes something like this in Python:

def V(theta, N):
    return sum(a0*(cos(i*theta)) for i in range(1, N + 1))

Note that you have to pass theta and N to the function. Also note that we are using N + 1 to make sure N is included (as range iterates over the values until, but not including, the last value).

Sign up to request clarification or add additional context in comments.

1 Comment

Oh thank you! But then how can I save the data at each increment in a texte file? In a for loop I would have used fprintf but here I dont see how can I insert it?
3

something like:

def V(theta,N):
    return sum(a0*(cos(i*theta) for i in range(1,N+1))
print V(theta,N) 

or you can use lambda:

V =lambda theta,N : sum(a0*(cos(i*theta) for i in range(1,N+1))   
print V(theta,N) 

1 Comment

@FaycalF thank us by accepting any of these answers, just check the tick mark on the left side of the solutions.
0

Your shown example uses no math functions, just basic arithmetical operations. That's why it works as shown, but math.cos doesn't support lists and so will not work this way.
If you really want to get around without any for, you should use numpy. Numpy's math functions support lists (actually arrays).
This way you can write something like:

from numpy import *
def fun(theta):
    return a0*sum(cos(arange(1,N+1)*theta))

Should you be doing a lot of this kind of calculations, it is best to use numpy.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.