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.
Mathematica has an inbuilt function CForm
which does a pretty good job. However, there are some caveats:
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.CForm
converts exponents to a form which is not compatible with C/C++. For example:CForm[x^2]
yields
Power(x,2)
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.
x^2
has completely different meaning in C++.Also, remember C++ is not for symbolic computation. So variables need to be initialized before using them.
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