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

Mathematica: f[a,b,c] = a*g[b,c], force evaluate

  1. Mar 14, 2014 #1

    Say I have a function f[a,b,c] which depends on another function g[b,c] such that:

    f[a,b,c] = a*g[b,c]

    If I input, f[a,1,2], mathematica spits out a*g[1,2] rather then actually evaluating what g[1,2] is. Is there a way I can force mathematica to evaluate g[1,2] so instead, e/g if g = b/c, mathematica will give:

    f[a,1,2] = a/2

    This is just a simple example, in what I am doing this lack of evaluating causes a significant increase to the computation time.

  2. jcsd
  3. Mar 14, 2014 #2
    You want to tell Mathematica that your functions are to be treated as functions,
    g[b_, c_] := b/c
    f[a_, b_, c_] := a*g[b, c]
    Note the underscores after the function variables.

    Also see the tutorial.
  4. Mar 14, 2014 #3

    Thanks for your reply.

    Sorry I omitted the formal code for the sake of explaining. I found the source of my problem, I didn't include it here because I didn't think it was the problem.

    The problem was that I was using the If function, e.g.

    f[a,b,c] = If[a>x,a*g[b,c],100*a*g[b,c]]

    (omitting the _'s and :)

    Mathematica would choose not to evaluate the two conditions until it decided if a>x or not. To fix it I put in Evaluates[..] around each of the conditions.

    On the down side, this wasn't the reason for the increase computation time, still looking for that, but I won't bring up that problem here.

    Thanks again,
  5. Mar 14, 2014 #4
    Glad you solved it.

    I find optimizing Mathematica code tricky, as there generally is several ways of doing the same thing, and it's often not obvious why one should be quicker than the other. Anyway, there's this guide 10 tips for writing fast Mathematica code. You might find it helpful too.
  6. Mar 15, 2014 #5
    The reason behind the low performance is probably utilising symbolic manipulations where numerical would suffice.

    Why would you omit anything? With underscores and := this would be an entirely different definition.

    The way it's written here it looks alarming for several reasons. Don't omit anything because it makes it unnecessary hard to understand what's happening.
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook