0

I have taken the following snippet out of context based on a bit of debugging.

I have a lambda function called 'part' which depends on the variables theta and phi. If you cycle through the list of returned lambda functions (d4[0],d4[1],etc.) you will see that all of them return a complex number where the imaginary component is 0, regardless of the theta,phi values that I give to the function. This is not correct. Most of these functions should return complex numbers with non-zero imaginary parts for most theta,phi arguments. Any idea why this is happening??

import numpy as N
xarr,yarr,zarr = N.meshgrid(N.linspace(-0.5,0.5,32),N.linspace(-1.0,1.0,64),N.linspace(-0.0,0.0,1))
xnum,ynum,znum = xarr.shape

#d1,d2,d3,d4 are for debugging
d1,d2,d3,d4 = [],[],[],[]

for i in range(xnum):
    for j in range(ynum):
        for k in range(znum):
        x,y,z = N.float64(xarr[i,j,k]),N.float64(yarr[i,j,k]),N.float64(zarr[i,j,k])
        d1.append(x),d2.append(y),d3.append(z)
        part = lambda theta,phi: (N.cos(theta)**(0.5))*N.sin(theta)*N.exp(-1j*k*(x*N.sin(theta)*N.cos(phi) + y*N.sin(theta)*N.sin(phi) - z*N.cos(theta)))   
        d4.append(part)   
tsnitz
  • 15
  • 5

1 Answers1

1

You need to capture the current values of loop variables when the lambda is created. Otherwise the function will read the value of those variables in the scope of its creation at the time it is invoked.

It can be done via argument defaults:

part = lambda theta,phi, x=x, y=y, z=z, k=k: (N.cos(theta)**(0.5))*N.sin(theta)*N.exp(-1j*k*(x*N.sin(theta)*N.cos(phi) + y*N.sin(theta)*N.sin(phi) - z*N.cos(theta)))
Dan D.
  • 73,243
  • 15
  • 104
  • 123