0
$\begingroup$

With my function $f(x)$ I would like to Plot3D

$\int_a^b f(x) dx$

with the parameter values $a \in [0,1]$ and $b \in [1,3]$. The challenging part has to do with my integrand, which is as follows

$f(x)=x$ if $a \leq b \leq 2a$,

$f(x)=x^2$ if $b > 2a$.

My Mathematica code is as follows:

f = Integrate[If[a <= b <= 2\ a, x, x^2], {x, a, b}]; Flatten[Table[{a, b, f}, {a, 0, 1, .1}, {b, 1, 3, .1}], 1]

When I run this, I get results that look correct if the condition is 'true', but if the condition is 'false' I get results with the associated integral value Undefined. I wonder if there is anything wrong with my code. Thanks!

$\endgroup$
  • $\begingroup$ Didn't realize this until just now, and this applies to the question itself, but could you double check your conditions? Because $a \leq b \leq 2b$ is always true in this region, and the condition in your code looks like you might have wanted a <= b <= 2 a. $\endgroup$ – That Gravity Guy Jul 13 at 23:06
  • $\begingroup$ @ThatGravityGuy: Yes, you are right, that was a typo! I have corrected it. Thanks so much! $\endgroup$ – ppp Jul 13 at 23:22
1
$\begingroup$

If method

You can use If to get the job done

f = If[a <= b <= 2 a, x, x^2]
ifmethod = Flatten[Table[{A, B, Integrate[f /. {a -> A, b -> B}, {x, A, B}]}, {A, 0, 1, .1}, {B,  1, 3, .1}], 1]

The key here is to tell f what a,b are with the replacement before the integration takes place so that you get the right form (e.g. $x$ or $x^2$).

Piecewise function method

f[a_, b_, x_] := Piecewise[{{x, a <= b <= 2 a}, {x^2, b > 2 a}}]
piecewisemethod = Flatten[Table[{a, b, Integrate[f[a, b, x], {x, a, b}]}, {a, 0, 1, .1}, {b, 1, 3, .1}], 1]

Comparison

ifmethod == piecewisemethod 

True

$\endgroup$
  • 3
    $\begingroup$ If is a procedural construct, mostly useful for numeric computations. Symbolic functions like Integrate and Solve have no methods to "reason" about what the result of a procedure might be. So, when using symbolic methods, avoid If and use things like Piecewise or the Heaviside functions. $\endgroup$ – John Doty Jul 13 at 20:41
  • $\begingroup$ @JohnDoty: Thanks! $\endgroup$ – ppp Jul 14 at 15:00
  • $\begingroup$ Dear That Gravity Guy, your answer was very helpful for which I really appreciate. I am applying your answer to a more complicated task. If you allow, may I ask your help once more? My question can be found here: mathematica.stackexchange.com/questions/202092/… $\endgroup$ – ppp Jul 15 at 1:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.