I'm trying to construct a 'normal' function (with formal parameter) from the FindFit result within a Module context.
While this works on a global level:
In :=
points = Table[{x, 2 x^2 + 3 x + 4 + RandomReal[]}, {x, 1, 10}];
model = a x^2 + b x + c;
fit = FindFit[points, model, {a, b, c}, x];
f[x_] = Evaluate[model /. fit];
f[2]
Out :=
18.473
the same trick in a Module doesn't work.
In :=
Module[{points, model, fit, a, b, c, x, f},
points = Table[{x, 2 x^2 + 3 x + 4 + RandomReal[]}, {x, 1, 10}];
model = a x^2 + b x + c;
fit = FindFit[points, model, {a, b, c}, x];
f[x_] = Evaluate[model /. fit];
f[2]
]
Out :=
4.1934 + 3.25034 x$30780002 + 1.97626 x$30780002^2
Looks that the trick with Evaluate
doesn't work in a Module context - the argument x
of the f
is a new variable that is unurelated to the module-scoped x
. I would not expect it to work even on a global level. Yet it works.
So the question/problem is: how to get the same effect in Modules in a Wolfram-idiomatic way?
Maybe I've missed the essence of Modules. I just want to protect the outside world from any leakage of assigned variables via lexical scoping, because I found that it is too easy to mess the global environment and destroy symbolical computations in unrelated parts of the script.