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

AI Thread Summary
The discussion centers around converting C code generated from Mathematica back into a format that Mathematica can understand. The original C code, produced using CForm, contains complex expressions involving PolyLog and power functions, which the user finds cumbersome to handle manually. They attempted to automate the conversion using StringReplace but encountered difficulties and inaccuracies. A suggestion was made to use the ToExpression function in Mathematica, replacing instances of "pow" with "Power" to facilitate the conversion. Additionally, the user was advised to check for formatting issues, such as backslashes and dots, which could affect the accuracy of the conversion. The conversation highlights the challenges of importing and converting code between different programming environments, particularly when dealing with complex mathematical expressions.
Hepth
Science Advisor
Gold Member
Messages
457
Reaction score
40
I have some ugly c-code that was generated from Mathematica in years past with CForm, and looks like :

Code:
(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
 
Physics news on Phys.org
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.
 

Similar threads

Replies
2
Views
1K
Replies
11
Views
2K
Replies
1
Views
1K
Replies
4
Views
2K
Replies
1
Views
2K
Replies
1
Views
6K
Back
Top