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).
Asked
Active
Viewed 1,100 times
1
-
you are not asking anything. – Aug 12 '15 at 15:16
-
I'm looking for help with code to generate this array. – Zachary Russell Heineman Aug 12 '15 at 15:18
-
you are not asking for help, you are asking for the code. What have you done? Where do you have problems? StackOverflow is not for others do your homework. – Aug 12 '15 at 15:19
-
It's not my homework. I'm a designer working on a visualization. I have defined the problem I am trying to solve but I don't have any experience translating math to code (or much experience with math). – Zachary Russell Heineman Aug 12 '15 at 15:28
2 Answers
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()
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
-
Great. Thank you. Is there an easy implementation without NumPy? – Zachary Russell Heineman Aug 12 '15 at 16:38
-
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