How to avoid repeatedly recalculating a function that is used multiple times in another function

Example as following

g[x_]:=NIntegate[......];

f[x_]:=g[x]^2+g[x];


I need to have define f[x] through g[x], Does mathmetica NIntegrate g[x] twice when calculating f[x]? How to rewrite it to reduce calculation? My idea is to give the value of g[x] at some x to a variable and use it in f[x].

value=g[x];
f[x_]=value^2+value;


The value giving should be done inside f[x_]. How to build up the function definition in mathematica in such way?

Update:

After a bit of study myself, the new code I write is:

g[x_] := NIntegate[......];
f[x_] = #^2 + # &[g[x]]


The function definition gives correct answer. Does it calculate g[x] once or twice in this way?

• Yes, Mathematica calls g[x] twice, since you called it twice. Why not use = instead of := and this way, it will integrate once? But it is better to make a complete working small example, showing the actually integration you are doing. This way, one does not have to guess. – Nasser Oct 26 '17 at 4:53
• I usually do With[{value = g[x]}, (*some expression with value *)] but I'm not sure how well this may work in NIntegrate – LLlAMnYP Oct 26 '17 at 5:36

This is one of the situations that With is designed to handle.

g[x_] := NIntegrate[u/(1 + u), {u, 0, x}]
f[x_] := With[{u = g[x]}, u^2 + u]


Then

Plot[f[x], {x, 0, 5}]


You could also use memoization (Memoization/Caching)

When you define g as

g[x_]:=g[x]=<definition of g in terms of x>


you can make use of the fact that Mathematica 'remembers' the values of g that are already evaluated.

In the context of the question, the output of a-possibly-computationally costly function like NIntegrate will be evaluated only once for a given input.

In the following code RandomReal will be used as a substitute for the output of some costly function like NIntegrate and Pause is used to simulate the time consuming nature of g.

g[x_]:=g[x]=(Pause[1];RandomReal[])
f[x_]:=g[x]^2+g[x]


Now, the first time eg f[2] is executed, Mathematica will evaluate g[2] and then assign the value of g[2]^+g[2] to f[2].

The next time Mathematica encounters f[2], it will no longer need to evaluate the costly g[2] again because it will already have a rule saved that associates the expressiong[2] with the value that was calculated, the first time g[2] was encountered.

In short, the costly function g will be calculated once, only the first time Mathematica encounters f[value]. In all subsequent evaluations where f[value] is relevant, there will be no need to re-evaluate the costly g[value].