我有一个函数 f(x,a),其中“x”是变量,“a”是参数。我想创建一个函数 F(x),它是一系列参数“a”的 f(x,a) 之和,例如: F(x) = f(x,a1) + f(x,a2) + f(x,a3) + ... + f(x,aN) 但是我如何有一个大范围的 'a' (a= [a1,a2,a3,...,aN]) 我想为此编写一个程序,但我现在不知道如何编写。例如:
import numpy as np
# Black-Body radiation equation: 'x' is related to frequency and 'a' is related to temperature
def f(x,a):
return x**3/(np.exp(a*x) - 1)
# range for parameter a:
a = [1000,2000,3000,4000,5000,6000]
# Superposition of spectrum
def F(x):
return f(x,a[0]) + f(x,a[1]) + f(x,a[2]) + f(x,a[3]) + f(x,a[4]) + f(x,a[5])
函数 F(x) 的最后一行不是很聪明,所以我尝试使用 sum() 函数在上面的总和中创建一个循环
def F(x):
spectrum = []
for i in a:
spectrum = sum(f(x,i))
return spectrum
但是由于我没有太多使用 Python 的经验,所以这不起作用,并且出现了错误:
import matplotlib.pyplot as plt
x = np.linspace(0,100,500)
plt.plot(x,F(x))
plt.show()
# ValueError: x and y must have same first dimension, but have shapes (500,) and (1,)
有人知道该怎么做吗?非常感谢
最佳答案
据我了解,这应该可以完成工作:
def F(x):
return sum(f(x, _a) for _a in a)
我在 sum()
函数中所做的事情称为列表理解,如果您对 Python 编码感兴趣,请随意查看这个 Python 功能:它非常强大。
关于python - Python 中的函数求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58436486/