Group Abstract Group Abstract

Message Boards Message Boards

0
|
2.6K Views
|
5 Replies
|
1 Total Like
View groups...
Share
Share this post:

How to get a numerical value of the result returned by Integrate?

Posted 1 year ago

Hi, I need to get a numerical value of the result returned by Integrate. The following simple example does not work as I would expect, however:

a=Integrate[x,x];
With[{x=10},a]

The returned result is x^2/2 instead of the expected 50. How can I make this work? Lesław

POSTED BY: Leslaw Bieniasz
5 Replies
Posted 1 year ago

Use Block instead of With

In[1]:= a = Integrate[x, x];

In[2]:= Block[{x = 10}, a]
Out[2]= 50
POSTED BY: Hans Milton

You can define a function:

Clear[a, x];
a[x_] = Integrate[x, x]
a[1]
POSTED BY: Gianluca Gorni

Hello, I think these suggestions are not what I really need; I need a way to evaluate the integration result for a concrete value of x, but without permanently changing the formula for the integration result by substituting this x value. It seems that the following construct does what I need, but I have a feeling that it is not elegant; I presume there must be a more adequate (more efficient?) way:

a=Integrate[x,x];
With[{y=10},ReplaceRepeated[a,{x->y}]]

In contrast, the approaches using Block[] or /. seem to permanently modify the expression "a". Lesław

POSTED BY: Leslaw Bieniasz

Two responses show how one might do this. Here is a third, and it shows what went awry in the original attempt.

First note that With holds all its arguments.

In[298]:= Attributes[With]

(* Out[298]= {HoldAll, Protected} *)

The practical consequence is that there is no x in the second argument until after it is evaluated. And this happens (as it happens) after the macro-style substitution of 10 for x in that second argument. To force the expression in the second argument to be x^2/2, simply use Evaluate.

In[299]:= With[{x = 10}, Evaluate@a]

Out[299]= 50

This next shows a bit more detail about the evaluation sequence for the example.

In[302]:= a = Integrate[x, x];
Trace[With[{x = 10}, a]]
Trace[With[{x = 10}, Evaluate@a]]

(* Out[303]= {HoldForm[With[{x = 10}, a]], HoldForm[a], HoldForm[x^2/2]}

Out[304]= {{HoldForm[a], HoldForm[x^2/2]}, 
   HoldForm[With[{x = 10}, x^2/2]], HoldForm[10^2/2], 
   {HoldForm[10^2], HoldForm[100]}, HoldForm[100/2], HoldForm[50]} *)

I will remark that similar issues arise with Plot and related functions that hold their arguments.

POSTED BY: Daniel Lichtblau

Or Replace:

a = Integrate[x, x];
a /. x -> 10

With[{x=10},a] replaces only lexical occurrences of the variable x in the unevaluated a.

POSTED BY: Gianluca Gorni
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard