Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Lets define two identical functions $f$ and $g$ in a slightly different way

f = Interpolation[Table[{i, i^2}, {i, -5, 5}]];
g = Function[x, Interpolation[Table[{i, i^2}, {i, -5, 5}]][x]];
Timing[Do[g[1], {i, 1000}]]/Timing[Do[f[1], {i, 1000}]]
{12.0023, 1}

Does the second definition calculates the interpolating function every time $g$ is evaluated?

share|improve this question
    
I see now it is because of the HoldAll attribute of the function. A workaround: g = Function[x, Evaluate@Interpolation[Table[{i, i^2}, {i, -5, 5}]][x]] –  Enredanrestos Aug 8 at 22:39

1 Answer 1

Yes! You have passed the same function f into a pure function so it is evaluated every time you calculate g. Specially you define f by = so Mathematica calculates it once and then re-use it in Do loop. For the sake of demonstration if I define f by :=:

f1 := Interpolation[Table[{i, i^2}, {i, -5, 5}]];
f2 = Interpolation[Table[{i, i^2}, {i, -5, 5}]];
Timing[Do[f1[1], {i, 1000}]]/Timing[Do[f2[1], {i, 1000}]]

The result is

 {11.91, 1}
share|improve this answer
2  
Thanks. I see , but this is not a SetDelayed issue, I think it is more related to the HoldAll attribute of Function, now I realize. –  Enredanrestos Aug 8 at 22:38
    
You are right. As the Documentation says: "Function has attribute HoldAll. The function body is evaluated only after the formal parameters have been replaced by arguments." –  Mahdi Aug 8 at 22:41

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.