TransWikia.com

Compute this once, not twice

Mathematica Asked on May 27, 2021

I have two questions.

So, I have a function g defined in terms of another function, f:

g[z_] := Product[f[z][[i]], { i, 1, Length [f[z] ] }];

My problem is that f[z_] takes a while to compute.

Question 1: When I call g, does it compute f twice?

Question 2: If so, is there a way to make it not do that?

Note: I simplified my code a little bit. g is actually defined in terms of two parameters, so I cannot generate a table of f and have it call the parts of the table.

One Answer

BobHanlon gives a good answer for 2. For question 1, Here's an easy way to test. Define f[z_] using Echo and have it return a known result. Then evaluate g[z].

In[1]:= f[z_]:=(Echo@"f[z] was called";{1,2,3});
In[2]:= g[z_]:=Product[f[z][[i]],{i,1,Length[f[z]]}];
In[3]:= g[1]
>>f[z] was called
>>f[z] was called
>>f[z] was called
f[z] was called
Out[3]= 6

Correct answer by Mat on May 27, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP