3

Consider this snippet of code:

from numpy import *
from pylab import *

#set up constants
v_f = 4.6e5
l = 1.e-9
c = 3.0e8
g = 4*2*pi
mu_B = 9.27e-24
hbar = 1.05e-34
m = 9.e-31
alpha = v_f*hbar
e = 1.6e-19
eps = 8.85e-12 #epsilon_0
B = arange(2.5, 37.5, 2.5) #magnetic field
beta = g*mu_B*B/2
A = (16*e**2)/(hbar*eps)
k = arange(10000., 60000., 5.)
n = 1.
w = c*2*pi*k/n

def E2_func(w, beta):
    return A*((hbar*w)**2*((hbar*w)**2 + (2*beta)**2))/((hbar*w)**2 - (2*beta)**2)**2

for b in beta:
    E2 = piecewise(w, [w <= 2*b/hbar, w > 2*b/hbar], [0, lambda w: E2_func(w, b)])
    E2_alt = piecewise(w, [w <= 2*b/hbar, w > 2*b/hbar], [0, E2_func(w, b)])
    subplot(121)
    plot(w, E2)
    subplot(122)
    plot(w, E2_alt)

show()

I put all of those constants in there so you can just copy the code, run the program and have a look at the output - Sorry, I don't have enough reputation points to post the output image on here yet.

From the scale on the y-axis, and the plots themselves, it's clear that there's a difference in the output between these two piecewise functions: why? It seems like the lambda function plays a role here, but I don't understand why that is. Any insight is appreciated.

Anthony
  • 133
  • 4

1 Answers1

0

Your following line has an error:

E2_alt = piecewise(w, [w <= 2*b/hbar, w > 2*b/hbar], [0, E2_func(w, b)])

[0, E2_func(w, b)] is your funclist. It should contain a function or a scalar, but E2_func(w, b) is an array with 10000 elements.

Your first version for E2 calls the lambda function for every element of w, where the condition list is true. Your second version for E2_alt sets the first element, where the condition is true to E2_func(w, b)[0], the second one to E2_func(w, b)[1] and so on.

Following works instead:

E2_alt = piecewise(w, [w <= 2*b/hbar, w > 2*b/hbar], [0, E2_func(w, b)[where(w > 2*b/hbar)]])

but for readybility the functionlist should be a scalar or a function only.

Holger
  • 2,125
  • 2
  • 19
  • 30
  • Oh I think I see what you mean. So just to clarify, the use of the lambda function in the first version for `E2` is correct, whereas in `E2_alt` I'm just calling elements in order from the array `E2_func(w, b)`? – Anthony Jul 03 '13 at 14:02