4
$\begingroup$

I use mathematica compute functions I need for some external coding. However I can't use terms like x^2+y^3 since my programming language needs this term written as x*x+y*y*y. I would love to copy and paste the results from mathematica so how do I convert these terms?

$\endgroup$
6
  • $\begingroup$ Something like StringReplace["x^2+y^3", a : LetterCharacter ~~ "^" ~~ n : DigitCharacter :> StringRiffle[ConstantArray[a, FromDigits[n]], "*"]]? $\endgroup$ – J. M.'s torpor Jan 14 at 11:28
  • $\begingroup$ Kinda works but kinda not since mathematica dont uses ^ to write a power. $\endgroup$ – Arjihad Jan 14 at 11:29
  • $\begingroup$ You can first use ToString@InputForm[expr] to get a string with powers written in ^ notation $\endgroup$ – Hausdorff Jan 14 at 11:40
  • 2
    $\begingroup$ Or you can look at this previous post: Post $\endgroup$ – Pino Savana Jan 14 at 11:42
  • 1
    $\begingroup$ I asked a similar question ten years ago (!!!) about tweaking the output of "CForm" (to change Power to repeated multiplication); Leonid Schifrin wrote a great reply that solved my problem. So it is really quite interesting to me to see the approaches mentioned to this question. $\endgroup$ – Daniel Chisholm Jan 14 at 17:37
8
$\begingroup$

If you want it in string form you can do it like this

x^3 /. Power -> (StringRiffle[#, "*"] &@ConstantArray[#1, #2] &)

"x * x * x"

This makes use of the fact that x^3 is internally written as Power[x,3].

$\endgroup$
3
  • 1
    $\begingroup$ Works. Thank you! $\endgroup$ – Arjihad Jan 14 at 12:00
  • 8
    $\begingroup$ x^3 /. Power[a_, n_] :> Inactive[Times] @@ ConstantArray[a, n] is another way to do it. This makes it easy to convert back as well with Activate. $\endgroup$ – Sjoerd Smit Jan 14 at 14:41
  • 2
    $\begingroup$ also x^2 + y^3 /. Power -> Apply[Inactive @ Times] @* ConstantArray $\endgroup$ – kglr Jan 14 at 19:55
7
$\begingroup$

Since you mention another language, here's a method using CForm:

Unprotect[Power];

Power /: Format[x_Symbol^n_Integer?Positive, CForm] := SequenceForm @@ Riffle[
    ConstantArray[x, n],
    Format["*", OutputForm]
]

Protect[Power];

Example:

x^2+y^3 //CForm

x*x + y*y*y
$\endgroup$

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.