# Evaluating an expression assuming a value for a variable only in the local context

Imagine we wish to evaluate some expression like NIntegrate[x^2*q,{x,0,100}] assuming some value for q like q = x.

How can we do this such that:

MakeLocalAssignmentOrAssumption[q = x, NIntegrate[x^2*q,{x,0,100}]]
Print[q]


Returns:

2.5*10^7
q


In other words, how can we assume that q = x ONLY in the context of evaluating the NIntegrate expression?

-
NIntegrate doesn't introduce a new context. Do you mean scope rather than context? (A context in Mathematica is a name space). – m_goldberg Apr 13 '14 at 15:48
@m_goldberg Perhaps yes - I just want Mathematica to assume that "q" has some value ONLY when evaluating the NIntegrate expression, and then not to have this value assigned to "q" anywhere else. – LUMO Apr 13 '14 at 15:49
Use Block - that's exactly what it is for: Block[{q = x}, NIntegrate[x^2*q, {x, 0, 100}]]. – Leonid Shifrin Apr 13 '14 at 15:55
@LeonidShifrin Thanks! – LUMO Apr 13 '14 at 15:58
With[{q = x}, NIntegrate[x^2*q, {x, 0, 100}] ] works also – Nasser Apr 13 '14 at 16:04

Maybe this is what you are looking for.

x = 42.;
Block[{x, q}, With[{q = x}, NIntegrate[x^2*q, {x, 0, 100}]]]

2.5*10^7


q

q


The Block construct declares x ansd q in the local scope. Also note, there is no need to use Print much in Mathematica, as the result of evaluating an expression or last expression in a compound expression ("statement") is always printed unless terminated by a semicolon.

-

While m_goldberg's answer is correct*, provides a proper explanation, and uses only documented behavior, there exists a cleaner syntax for the example given:

x = 42.;

With[{q := x}, NIntegrate[x^2*q, {x, 0, 100}]]

2.5*10^7

• The use of := in With is an undocumented syntax but very useful: it prevents evaluation of x before it is substituted into the expression.

• We need not Block x as it is localized by NIntegrate.

• * It is unnecessary to Block q in any case as it is not evaluated by With.

-

Another way: use an immediate or delayed rule: NIntegrate[x^2*q /. q -> x, {x, 0, 10}]
or change the replacement q->x on the fly using a function ff[x_]:= 1/(1-x) Table[ NIntegrate[x^2 q /. q:> ff[n x] ,{x,0,10}],{n,3}]

-