# Converting expression to C

I have an expression of the form

    -0.0000289725287527177708 - 2.52403420408155732 x +
138.677105376831122 x^2 - 3402.37981527828424 x^3 +
34440.8443628217428 x^4 + 158064.877964911022 x^5 -
8.04498826077845134*10^6 x^6


that I would like to convert over to an expression that can be used in C++. In C++ I have defined some functions for taking powers and the syntax is that $x^3=third()$, $x^4=fourth()$ and so on.

Besides this, I to convert $*10^6$ to $e6$. Is there an easy way to do these things?

• Are you aware of CForm? – Yves Klett Jun 8 '14 at 9:39
• @YvesKlett Yes That will take care of the exponents. BUt I still need to convert something like "Power(x, 6)" to sixth(x). – BillyJean Jun 8 '14 at 9:42
• expr /. {x^3 -> third[x], x^6 :> sixth[x]} // CForm etc.? – Yves Klett Jun 8 '14 at 9:45

Using CForm and some prior replacements:

expr = -0.0000289725287527177708 - 2.52403420408155732 x +
138.677105376831122 x^2 - 3402.37981527828424 x^3 +
34440.8443628217428 x^4 + 158064.877964911022 x^5 -
8.04498826077845134*10^6 x^6;

expr /. {x_^3 :> third[x], x_^6 :> sixth[x]} // CForm


-0.000028972528752717771 - 2.5240342040815573*x + 138.67710537683112*Power(x,2) + 34440.844362821743*Power(x,4) + 158064.87796491102*Power(x,5) - 8.0449882607784513e6*sixth(x) - 3402.3798152782842*third(x)

Perhaps a bit more universally applicable:

expr /. {x_^y_ :> ToExpression["power" <> ToString[y]][x]} // CForm


-0.000028972528752717771 - 2.5240342040815573*x + 138.67710537683112*power2(x) - 3402.3798152782842*power3(x) + 34440.844362821743*power4(x) + 158064.87796491102*power5(x) - 8.0449882607784513e6*power6(x)