如何做到在python总和(How to do a sum in python)

2019-09-21 20:11发布

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 :):)

Answer 1:

就像是:

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

或者你可以使用lambda

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


Answer 2:

你的计算公式为:

V(THETA)= SUM(i = 1-> N)[A0 *(COS(I * THETA)]

这意味着:总和的所有值a0*(cos(i*theta)对于给定的值theta在范围1到包括和N

这将成为在Python是这样的:

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

请注意,您必须通过thetaN的功能。 另外请注意,我们使用的是N + 1 ,以确保N包括(如range迭代的值,直到但不包括最后一个值)。



Answer 3:

你出例如不使用数学函数,只是基本的算术运算。 这就是为什么它的工作原理如图所示,但math.cos不支持列表中,因此不会以这种方式工作。
如果你真的想要得到周围没有任何的,你应该使用numpy的。 NumPy的的数学函数支持列表(实际上是阵列)。
这样,你可以写的东西,如:

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

如果您有做了很多这样计算的,最好是使用numpy的。



文章来源: How to do a sum in python