开发者

mathematica function of two parameters becomes listable by wrong parameter?

I can construct a list of values of a function evaluated at a set of values, as in simplelist below

Clear[f, g, simplelist, d, dlist1, dlist2]
f[x_] := Exp[ -x^2]
g[n_] := f[x] (-1)^n
simplelist = g[{0, 1, 2, 3, 4}]

d[n_] := Derivative[n][f][x] 
dlist1 = d[{0, 1, 2, 3, 4}]
dlist2 = {d[0], d[1], d[2], d[3], d[4]}

This gives me

{E^-x^2, -E^-x^2, E^-x^2, -E^-x^2, E^-x^2}

as expected.

If I build up a function (d) that implicitly has two parameters, n and x, I think my attempt to evaluate it with a list of values for [n], ends up evaluated with that list used for the values [x], because I get all zeros for the result as if the derivative of a constant was taken:

{0, 0, 0, 0, 0}

compare this to the dlist2 value, where I am explicit, but use a clumsy method of constructing the list, and get:

{E^-x^2, -2 E^-x^2 x, -2 E^-x^2 + 4 E^-x^2 x^2, 12 E^-x^2 x - 8 E^-x^2 x^3, 12 E^-x^2 - 48 E^-x^2 x^2 + 16 E^-x^2 x^4}

This question really has two parts:

1) Can somebody confirm that this function ends 开发者_Python百科up implicitly listable using [x] instead of [n], and perhaps elaborate on how this works.

2) I suspect I'm approaching this in a way that is probably whacked, so while it may be possible to force something like this to do what I'd tried, I really only want a good way to build up a list of values

{ h[0], h[1], ... h[n] }

I assume this can be done with a for loop and an Append function, but with the rich syntax available there must be a better way.


Regarding 1. - your guess is not correct. What really happens is that Derivative has a special interpretation when the first argument (n) is a list, so that Derivative[{1,2}][f][x] will attempt to differentiate once over the first argument of f (which is x), and twice over the second (missing!) - it is this differentiation that gives zero. When, in addition, f is also Listable and of a single argument, it becomes a bit more complex, but the idea is the same.

Regarding 2.:

SetAttributes[d, Listable]

will fix it. The reason why Listable attribute helps is that the threading over a list associated with it happens before d gets evaluated on a particular argument, therefore in this way, you never supply a list to Derivative, which is then only called on all members of the list separately - which is what you needed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜