Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Mathematica Mathematica Computation Time

  1. Jul 30, 2017 #1


    User Avatar
    Gold Member

    Hi PF!

    I am using the following code in Mathematica
    Code (Text):

    mat = {{1, Cos[2], Cos[4], Sin[2],
        Sin[4}, {1, 1, 1, 0, 0}};
    Li[x_] :=
         mat].{{1}, {Cos[x}, {Cos[
           2 x]}, {Sin[x]}, {Sin[2 x]}}];
    Li1[x_] := Li[x].{{1}, {0}, {0}};
    f[x_] :=
      Li1[x]/Sqrt[Integrate[Li1[s]^2, {s, -1, 1}]];
    Then when I want to compute something simple, say
    Code (Text):
    Integrate[f[x]^2, {x, -1, 1}]
    It takes Mathematica a very long time to compute. However, if I first do
    Code (Text):
    and then redefine ##f## in terms of the result mathematica prints and ask for the integral, Mathematica computes the integration in much less time. Does anyone know how to define ##f## to begin with in this "numeric" fashion to decrease run time?
  2. jcsd
  3. Jul 30, 2017 #2
    The main reason for the slow speed is because
    Code (Text):
    f[x_]:= (some stuff here)
    is a functional definition, so that whenever ##f(\alpha)## is called for a particular argument ##\alpha##, the sequence of instructions given in (some stuff here) will be evaluated from scratch. So, if (some stuff here) contains something relatively complicated such as an integral, you can see why the complexity builds up tremendously fast (especially when you're trying to integrate ##f(x)## itself!). That is to say, the right hand side will only be evaluated when the function is called.

    Conversely if you instead adopt the definition
    Code (Text):
    f[x_]= (some stuff here)
    where the colon has been omitted, then the right-hand-side is immediately evaluated. This greatly reduces the subsequent overhead.

    I personally almost always use the "=" (immediate definition) instead of ":=" (delayed definition) unless I need to keep the right hand side in unevaluated form for some reason.
  4. Jul 31, 2017 #3


    User Avatar
    Gold Member

    Good to know, thanks!

    This way is quicker but is still taking a significant amount of time to evaluate integrals. For example, if after running
    Code (Text):
    I redefine ##f## as
    Code (Text):
    0.9073859955296714 (0.534409621782702 -
       0.534409621782702 Cos[x] + Sin[2 x])
    subsequent operations on ##f## are computed almost instantly. But I have to manually redefine ##f## in this fashion. Since I will be performing many iterations it would be nice to automate this process. Do you have any ideas how to do this?

    Thanks for your interest!
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted

Similar Discussions: Mathematica Computation Time