# Writing mathematical expression in a file

I am trying to write a mathematical expression as variable = expression in the output file.

The current method that I am doing is through WriteString as

expr = -((a*b*y^2*(-1 + z)*z*(1 + a*b + z))/(1 + a*b)^2) +
(z*(1 + a*b - a*b*z + (z + a*b*z)^2))/(1 + a*b)^2 -
(y*z*((-1 + z)^2 + a*b*(2 - 3*z + z^2) + a^2*b^2*(1 - z + z^2)))/(1 + a*b)^2
expression = CForm[expr] /. {Power->pow};
(*expression = CForm[HornerForm[expr]] /. {Power->pow};*)
str=OpenWrite["output.hh"];
WriteString[str," double variable = ", expression,";"];
(*WriteString[str," double variable = ", ExportString[expression,"Text"]];*)
Close[str];


The output is

 cat output.hh
double variable = -(a*b*(-1 + z)*z*(1 + a*b + z)*pow(1 + a*b,-2)*pow(y,2)) - y*z*pow(1 + a*b,-2)*(pow(-1 + z,2) + a*b*(2 - 3*z + pow(z,2)) + pow(a,2)*pow(b,2)*(1 - z + pow(z,2))) + z*pow(1 + a*b,-2)*(1 + a*b - a*b*z + pow(z + a*b*z,2));


I want to break the line as the original expr (or after some user-specified column say 80) i.e.

 double variable = -(a*b*(-1 + z)*z*(1 + a*b + z)*pow(1 + a*b,-2)*pow(y,2)) -
y*z*pow(1 + a*b,-2)*(pow(-1 + z,2) + a*b*(2 - 3*z + pow(z,2)) + pow(a,2)*pow(b,2)*(1 - z + pow(z,2))) +
z*pow(1 + a*b,-2)*(1 + a*b - a*b*z + pow(z + a*b*z,2));


Although this might not lead to optimized expression for numerical evaluation, however it is wanted as beautification. Also how should one optimize expression for further processing to other languages. Any suggestion? ExperimentalOptimizeExpression and HornerForm are some options. Any other recommendation? MathCode is much costly :D

I would modify CForm as follows:

Unprotect[Power];
Format[Power, CForm] := pow
Protect[Power];

Format[unquotedString[s_], CForm] := Format[s, OutputForm]


Then:

With[{e = expr},
ToString[HoldForm[unquotedString["double variable"] = e], CForm, PageWidth->80]
]

"double variable =
-((a*b*pow(y,2)*(-1 + z)*z*(1 + a*b + z))/pow(1 + a*b,2)) +
(z*(1 + a*b - a*b*z + pow(z + a*b*z,2)))/pow(1 + a*b,2) -
(y*z*(pow(-1 + z,2) + a*b*(2 - 3*z + pow(z,2)) +
pow(a,2)*pow(b,2)*(1 - z + pow(z,2))))/pow(1 + a*b,2)"


The HoldForm is needed so that the Set (=) doesn't evaluate, and the unquotedString function allows inserting explicit strings without quotes.

• Thanks. But If I save this in a text file then newline characters \n appears. PageWidth is only for Notebook display or it can be incorporated to the content of output file which is also I wanted. Like the expression inside the output file will have 80 column limit for a line. Commented Jan 14, 2021 at 22:44
• Now this works well with WriteString`. Thanks Commented Jan 14, 2021 at 22:49