A problem in Mathematica 8 with function declaration

删除回忆录丶 提交于 2019-12-21 12:31:46

问题


This is a strange result with a function defined as "functionB" in this example. Can someone explain this? I want to plot functionB[x] and functionB[Sqrt[x]], they must be different, but this code shows that functionB[x] = functionB[Sqrt[x]], which is impossible.

model = 4/Sqrt[3] - a1/(x + b1) - a2/(x + b2)^2 - a3/(x + b3)^4;
fit = {a1 -> 0.27, a2 -> 0.335, a3 -> -0.347, b1 -> 4.29, b2 -> 0.435,
    b3 -> 0.712};
functionB[x_] := model /. fit

Show[
 ParametricPlot[{x, functionB[x]}, {x, 0, 1}],
 ParametricPlot[{x, functionB[Sqrt[x]]}, {x, 0, 1}]
 ]

functionB[x] must different from functionB[Sqrt[x]], but in this case, the 2 lines are the same (which is incorrect).


回答1:


If you try ?functionB, you'll see that it is stored as functionB[x_]:=model/.fit. Thus, whenever you now have functionB[y], for any y, Mathematica evaluates model/.fit, obtaining 4/Sqrt[3] - 0.335/(0.435 + x)^2 + 0.347/(0.712 + x)^4 - 0.27/(4.29 + x).

This has to do with using SetDelayed (i.e., :=). The rhs of functionB[x_]:=model/.fit is evaluated anew each time Mathematica sees the pattern f[_]. That you have named the pattern x is irrelevant.

What you want could be achieved by e.g. functionC[x_] = model /. fit. That is, by using Set (=) rather than SetDelayed (:=), so as to evaluate the rhs.

Hope this is clear enough (it probably isn't)...




回答2:


You might want to try defining the model inside functionB so x in both places are related:

fit = {a1 -> 0.27, a2 -> 0.335, a3 -> -0.347, b1 -> 4.29, b2 -> 0.435, b3 -> 0.712};
functionB[x_] := Module[
  {model = 4/Sqrt[3] - a1/(x + b1) - a2/(x + b2)^2 - a3/(x + b3)^4},
  model /. fit
]


来源:https://stackoverflow.com/questions/6046626/a-problem-in-mathematica-8-with-function-declaration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!