Mathematica 8 problem with function declaration

This is a strange result with a function defined as "functionB" in this example. Can someone explain this? I want to build functionB[x] and functionB[Sqrt[x]] , they should 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] should be different from functionB[Sqrt[x]] , but in this case the two lines are the same (which is wrong).

+6
source share
2 answers

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

This is due to the use of SetDelayed (i.e := ). Rhs functionB[x_]:=model/.fit is re-evaluated each time Mathematica sees the pattern f[_] . What you called the pattern x does not matter.

What you want can be achieved, for example, functionC[x_] = model /. fit functionC[x_] = model /. fit . That is, using Set ( = ) rather than SetDelayed ( := ) to evaluate rhs.

Hope this is clear enough (probably not)

+10
source

You can try to define a model inside function B, so that x is connected in both places:

 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 ] 
+3
source

Source: https://habr.com/ru/post/888429/


All Articles