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.

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?

share|improve this question
    
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 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 at 15:49
1  
Use Block - that's exactly what it is for: Block[{q = x}, NIntegrate[x^2*q, {x, 0, 100}]]. –  Leonid Shifrin Apr 13 at 15:55
    
@LeonidShifrin Thanks! –  LUMO Apr 13 at 15:58
1  
With[{q = x}, NIntegrate[x^2*q, {x, 0, 100}] ] works also –  Nasser Apr 13 at 16:04

3 Answers 3

up vote 2 down vote accepted

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.

share|improve this answer

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.

share|improve this answer

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}]

share|improve this answer

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.