我有一个函数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 with 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,)有人知道怎么做吗?非常感谢
发布于 2019-10-18 00:03:14
据我所知,这应该可以完成这项工作:
def F(x):
return sum(f(x, _a) for _a in a)我在sum()函数中做的事情叫做列表理解,如果你对Python编码感兴趣,请随意看看这个特性:它非常强大。
https://stackoverflow.com/questions/58436486
复制相似问题