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

[Mathematica] : Method to import C-Code to Expressions

  1. Jun 10, 2015 #1

    Hepth

    User Avatar
    Gold Member

    I have some ugly c-code that was generated from Mathematica in years past with CForm, and looks like :

    Code (Text):

    (PolyLog (2,(-1 + t)*pow (-1 + q2h,-1))*pow (q2h - t,-1)*pow (-1 + \
    t,-1)*
         (-8*pow (q2h,3)*pow (t,2) + pow (q2h,4)*(1 + pow (t,2)) -
           8*q2h*pow (t,3)*(-3 + 8*t - 5*pow (t,2) + pow (t,3)) +
           pow (q2h,2)*pow (t,2)*(-13 + 40*t - 16*pow (t,2) + pow (t,4)) +
           pow (t,4)*(-10 + 24*t - 13*pow (t,2) + pow (t,4)))*
         pow (q2h - pow (t,2),-3))/8. -
      (PolyLog (2,-((q2h - t)*(q2h + (-1 + 2*ctf)*t)*pow (ctf,-1)*pow \
    (t,-2))/2.)*
         pow (q2h - t,-1)*pow (-1 + t,-1)*
         (-8*pow (q2h,3)*pow (t,2) + pow (q2h,4)*(1 + pow (t,2)) -
           8*q2h*pow (t,3)*(-3 + 8*t - 5*pow (t,2) + pow (t,3)) +
           pow (q2h,2)*pow (t,2)*(-13 + 40*t - 16*pow (t,2) + pow (t,4)) +
           pow (t,4)*(-10 + 24*t - 13*pow (t,2) + pow (t,4)))*
         pow (q2h - pow (t,2),-3))/8.

     
    I would like to import this back into Mathematica in an automatic way, as the true expressions are many pages long.

    I tried by hand with things like : StringReplace[%, {"pow(t," ~~ Shortest[b__] ~~ ")" :> "Power[t," ~~ b ~~ "]"}];

    but it gets ugly, and sometimes makes mistakes.

    Is there a package or method that exists that would let me do this? Can Mathematica import C code at all, or convert it if its simple (like this)?

    Thanks!
    -Hepth
     
  2. jcsd
  3. Jun 10, 2015 #2
    Your string has issues; check out for backslashes (and maybe dots, if you don't want inexact numerics), for example

    Once done, try this:

    ToExpression[string, TraditionalForm, HoldComplete] /. pow -> Power

    Worked OK for me.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: [Mathematica] : Method to import C-Code to Expressions
Loading...