I have written some mathematica-code which allows me to compute some equation in general relativity, which I would like to solve using a C++-program. However, the equations are roughly 1000 characters long. And since simple copy and past will not work because of mathematicas output-form, I was wondering if it would be possible to convert the equations in a simple way.

  • $\begingroup$ I used Mathematica to generate code for Asymptote, which uses a syntax similar to C. My strategy was to convert Mathematica code to string, and use StringReplace and <> to join additionnal strings. It is very far from being perfect but it worked in my case. $\endgroup$ – anderstood Nov 25 '15 at 17:35
  • 1
    $\begingroup$ Have you searched the site yet? There are several related threads around. $\endgroup$ – Yves Klett Nov 25 '15 at 18:20

Mathematica has an inbuilt function CForm which does a pretty good job. However, there are some caveats:

  1. No support for Greek/special characters. Your variable names might have Greek characters, which are not supported in C/C++. Hence, you should replace all such variables. Create a list, maybe call it subsGtoCpp, put all rules which are required in list form.

  2. CForm converts exponents to a form which is not compatible with C/C++. For example:




You can define a function Power in C++ which takes in two inputs, the variable and the index to which it is raised. The Power function can be overloaded to receive int and double/float inputs for the exponent and treat them accordingly. For int inputs you might want to use a for loop and the inbuilt pow function in-case of decimal exponents. One can simply replace Power in the expression generated from CForm to pow as well.

  1. x^2 has completely different meaning in C++.

  2. Also, remember C++ is not for symbolic computation. So variables need to be initialized before using them.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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