3
$\begingroup$

Say I have some test function, which evaluates an integral, such as

test[a_, b_] := 
 Integrate[Exp[-(a^2/2) x^2]*Sqrt[x^2 + b^2], {x, 0, \[Infinity]}, 
  Assumptions -> a > 0 && b > 0]

and in this case returns a confluent hypergeometric function

$$\mathrm{test}(a, b) = \frac{\sqrt{\pi}}{a^2} U \left( -\frac{1}{2}, 0, \frac{a^2 b^2}{2} \right) \, .$$

I would like to plot the result as a function of $b$ for some value of $a$, e.g. I set $a=1$ and try to plot with

Plot[test[1, b], {b, 0, 1}, AxesLabel -> {"b", "test"}, 
 PlotRange -> All, ImageSize -> 480]

but this takes a very long time to evaluate since Mathematica is repeatedly solving the integral.

This can easily be solved by wrapping an Evaluate around my test function. But now, if I want to manipulate the parameter $a$, things evaluate much slower than if I had just substituted the result, i.e.

Manipulate[
 Plot[Evaluate[test[a, b]], {b, 0, 1}, AxesLabel -> {"b", "test"}, 
  PlotRange -> All, ImageSize -> 480], {{a, 0.5, "a"}, 0.0001, 1, 
  Appearance -> {"Labeled", "Open"}}]

is slower than

Manipulate[
 Plot[(Sqrt[\[Pi]] HypergeometricU[-(1/2), 0, (a^2 b^2)/2])/
  a^2, {b, 0, 1}, AxesLabel -> {"b", "test"}, PlotRange -> All, 
  ImageSize -> 480], {{a, 0.5, "a"}, 0.0001, 1, 
  Appearance -> {"Labeled", "Open"}}]

Is there a fast way to plot and manipulate the test function without having to substitute the resulting expression by hand?

$\endgroup$

1 Answer 1

6
$\begingroup$

Does this work better for you?

enter image description here

ClearAll[a, b, x]
test[a_, b_] = 
 Integrate[Exp[-(a^2/2) x^2]*Sqrt[x^2 + b^2], {x, 0, \[Infinity]}, 
  Assumptions -> a > 0 && b > 0]

Manipulate[
 Module[{b},
  Plot[test[a0, b], {b, 0, 1},
   AxesLabel -> {"b", "test"},
   PlotRange -> All, ImageSize -> 480]
  ],
 {{a0, 0.5, "a"}, 0.0001, 1, Appearance -> {"Labeled", "Open"}},
 TrackedSymbols :> {a0}
 ]
$\endgroup$
2
  • $\begingroup$ Yes, that's perfect! Thank you! $\endgroup$ Sep 1, 2022 at 2:35
  • 1
    $\begingroup$ I just noticed that the important change here is the change from SetDelayed to Set in defining the test function (see e.g. stackoverflow.com/questions/5320330/…). $\endgroup$ Sep 1, 2022 at 4:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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