[英]Create a 2D array that is the product of two functions
我正在进行可视化工作,并尝试创建一个二维数组,该数组是X轴上的标准化高斯函数和Y轴上的标准化指数函数(使用Python)的乘积。
I would use NumPy for this. 我会为此使用NumPy 。 You can use np.meshgrid
to create the (X, Y)
axes and use NumPy's vectorized functions to create the function on these coordinates. 您可以使用np.meshgrid
创建(X, Y)
轴,并使用NumPy的矢量化函数在这些坐标上创建函数。 The array f
below is your two-dimensional array, here containing the product of exp(-X/4)
and exp(-((Y-2)/1.5)**2)
. 下面的数组f
是您的二维数组,这里包含exp(-X/4)
和exp(-((Y-2)/1.5)**2)
。 (Substitute your own normalized functions here.) (在这里替换您自己的规范化函数。)
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,10,100)
y = np.linspace(0,5,100)
X, Y = np.meshgrid(x, y)
f = np.exp(-X/4.) * np.exp(-((Y-2)/1.5)**2)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(f)
plt.show()
If you can't or don't want to use NumPy, you'll have to loop by hand and use conventional math
functions: 如果您不能或不想使用NumPy,则必须手动循环并使用常规的math
函数:
import math
dx, dy = 0.1, 0.05
nx, ny = 101, 101
f = [[None]*nx for i in range(ny)]
for ix in range(nx):
x = xmin + dx*ix
for iy in range(ny):
y = ymin + dy*iy
f[iy][ix] = math.exp(-x/4.) * math.exp(-((y-2)/1.5)**2)
I would use numpy for this, because numpy makes it very simple to do what you want. 我将为此使用numpy,因为numpy使执行所需操作非常简单。 If you can't use it, then something like the following should work: 如果您无法使用它,则应执行以下操作:
import math
def gauss(x, mu=0.0, sigma=1.0):
return 1.0 / math.sqrt(2.0*math.pi*sigma**2) * math.exp(-0.5*(x-mu)**2/sigma**2)
def exponential(x, lam=1.0):
return lam * math.exp(-lam * x)
# X values from -10 to 10 with 0.01 step size
xvals = [x * 0.01 for x in range(-1000, 1001)]
# Y values from 0 to 10 with 0.01 step size
yvals = [y * 0.01 for y in range(0, 1001)]
# Calculate your function at the grid points
f = [[gauss(x)*exponential(y) for x in xvals] for y in yvals]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.