gpt4 book ai didi

python - 如何在 python 中求和

转载 作者:太空宇宙 更新时间:2023-11-03 13:49:39 25 4
gpt4 key购买 nike

我想知道如何在没有像 here 这样的循环的情况下在 python 中表示总和

我们有:

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

我的函数如下:V(theta) = Sum(i=1->N)[a0*(cos(i*theta)]

预先感谢您的帮助:):)

最佳答案

你的公式是:

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 遍历值,直到但不包括最后一个值)。

关于python - 如何在 python 中求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12167660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com