1
$\begingroup$

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? Experimental`OptimizeExpression and HornerForm are some options. Any other recommendation? MathCode is much costly :D

$\endgroup$
3
$\begingroup$

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.

$\endgroup$
2
  • $\begingroup$ 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. $\endgroup$ – Boogeyman Jan 14 at 22:44
  • $\begingroup$ Now this works well with WriteString. Thanks $\endgroup$ – Boogeyman Jan 14 at 22:49

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.