I'm trying to have Mathematica automatically give me an equation which I can use in a different programming language. FortranForm produces output which is very similar to what the other language is expecting, except for the Power[] operator.

Basically, my problem is this - I would like to see the following output from Mathematica:

In= FortranForm[a^b]
Out= a^b

Rather than what it currently does, which is:

In= FortranForm[a^b]
Out= a**b

I think I can redefine the formatting of Power to do what I want with:

Format[Power[args__], FortranForm]:= <something here i can't figure out>

Does anyone know how to modify the formatting of Power when using FortranForm?


Don't monkey with adding definitions to Power. Try something like

StringReplace[ToString[1+ 3 c+ a^b, FortranForm], "**" -> "^"]
"1 + a^b + 3*c"
| improve this answer | |

You can accomplish what you want by making use of SequenceForm (to put elements in sequence) and OutputForm (to hide quotation marks):

powerPrec = Precedence[Power];

    xx=If[Precedence[Head[x]]<powerPrec, pform[x], x],
    yy=If[Precedence[Head[y]]<powerPrec, pform[y], y]

    SequenceForm[xx, Format["^",OutputForm],yy]

Format[pform[x_], FortranForm] := SequenceForm[Format["(", OutputForm], x, Format[")", OutputForm]]

Some examples:

a^b //FortranForm


(1+x)^2 //FortranForm

(1 + x)^2

(a+1/4)^(2 d) //FortranForm

(0.25 + a)^(2*d)

| improve this answer | |

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.