2
$\begingroup$

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:

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

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

$\endgroup$
2
$\begingroup$

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

StringReplace[ToString[1+ 3 c+ a^b, FortranForm], "**" -> "^"]
"1 + a^b + 3*c"
$\endgroup$
0
$\begingroup$

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

Unprotect[Power];
powerPrec = Precedence[Power];

Format[Power[x_,y_],FortranForm]:=With[
    {
    xx=If[Precedence[Head[x]]<powerPrec, pform[x], x],
    yy=If[Precedence[Head[y]]<powerPrec, pform[y], y]
    },

    SequenceForm[xx, Format["^",OutputForm],yy]
]
Protect[Power];

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

Some examples:

a^b //FortranForm

a^b

(1+x)^2 //FortranForm

(1 + x)^2

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

(0.25 + a)^(2*d)

$\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.