Why does evaluating an integral within a Plot expression take so long? [duplicate]

This question already has an answer here:

Using Evaluate and Evaluated -> True in Plot

1 answer

I want to evaluate

Plot[Integrate[Sin[((1 + 1/2) x)] (1/(2 Sin[(x/2)]) – 1/x), {x, 0, t}], {t, 0, 5}]

but it takes ages to load on Corei3 computer with Mathematica 9.

I’m still a novice when it comes to using Mathematica. Is there a way to get this expression to be evaluated faster? (I’m not used to waiting more than a minute while computing, that’s why it feels odd to me).

=================

=================

1 Answer
1

=================

Oska nailed it in the comments before me

The trick here is to evaluate the integral only once. In your code it is being evaluated once for every point. You can evaluate the following

Integrate[Sin[((1 + 1/2) x)] (1/(2 Sin[(x/2)]) – 1/x), {x, 0, t}]

The outcome of this is

ConditionalExpression[1/2 (t + 2 Sin[t] – 2 SinIntegral[(3 t)/2]),
t \[Element] Reals]

You know that t will always be a real number (at least in your plot), so you can just copy paste the first argument of this ConditionalExpression and make a function out of it.

func[t_] := 1/2 (t + 2 Sin[t] – 2 SinIntegral[(3 t)/2])

We can then do

Plot[func[t], {t, 0, 5}]

which gives

To define the function “automatically”, you could use the code in Oska’s answer. I slightly prefer the following

func[t_] := Evaluate@
Integrate[Sin[((1 + 1/2) x)] (1/(2 Sin[(x/2)]) – 1/x), {x, 0, t},
Assumptions -> t \[Element] Reals]

Which gets rid of the ConditionalExpression and uses SetDelayed rather than Set. The code only works if t does not have value, so watch out.