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$ Jan 14, 2021 at 11:28
  • $\begingroup$ Kinda works but kinda not since mathematica dont uses ^ to write a power. $\endgroup$
    – Arji
    Jan 14, 2021 at 11:29
  • $\begingroup$ You can first use ToString@InputForm[expr] to get a string with powers written in ^ notation $\endgroup$
    – Hausdorff
    Jan 14, 2021 at 11:40
  • 2
    $\begingroup$ Or you can look at this previous post: Post $\endgroup$ Jan 14, 2021 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$ Jan 14, 2021 at 17:37

2 Answers 2

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$
    – Arji
    Jan 14, 2021 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$ Jan 14, 2021 at 14:41
  • 2
    $\begingroup$ also x^2 + y^3 /. Power -> Apply[Inactive @ Times] @* ConstantArray $\endgroup$
    – kglr
    Jan 14, 2021 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 and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.