1

I am working on a visualization and trying to create a 2D array that is the product of a normalized Gaussian function on the X axis and a normalized exponential function on the Y axis (using Python).

2 Answers2

3

I would use NumPy for this. You can use np.meshgrid to create the (X, Y) axes and use NumPy's vectorized functions to create the function on these coordinates. The array f below is your two-dimensional array, here containing the product of exp(-X/4) and 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()

enter image description here

If you can't or don't want to use NumPy, you'll have to loop by hand and use conventional math functions:

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)
xnx
  • 24,509
  • 11
  • 70
  • 109
0

I would use numpy for this, because numpy makes it very simple to do what you want. 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]
Alok--
  • 724
  • 3
  • 10