2
$\begingroup$

I'm trying to use Mathematica for building complex derivatives for my Fortran code. Therefore I have to do some wild string replacements to make that work. Anyway, I got quite far already but now it would come in handy if I could automatically overwrite let's say the Power method.

What I want is that Mathematica should replace e.g. x^(1/4) with x**z14 on FortranForm. What does work is this:

i=1; j=4; Unprotect[Power]; Power /: Format[Power[x_, i/j], FortranForm]:=x^ToExpression["z" <> ToString[i] <> ToString[j]] Protect[Power]; ToString[Power[x, i/j], FortranForm] 

This will give x**z14 as expected.

If I try to automate the process for more fractions

Unprotect[Power]; For[i = 1, i <= 9, i++, For[j = 1, j <= 9, j++, If[j > 1 && j != i && Mod[i, j] != 0, Power /: Format[Power[x_, i/j], FortranForm]:=x^ToExpression["z"<> ToString[i] <> ToString[j]]; ,Null ] ] ] Protect[Power]; ToString[Power[x, i/j], FortranForm] 

I get x**z1010 instead?

Can anyone help me and tell me what I'm doing wrong? Or is this even possible?

Thanks!

$\endgroup$

1 Answer 1

4
$\begingroup$

The problem is that the variables i and j on the RHS of the definition are not being bound to the input. A simpler example:

i=1; j=4; foo[i/j] := {i, j} DownValues[foo] 

{HoldPattern[foo[1/4]] :> {i, j}}

You could workaround this by using With to inject the values of i and j into the RHS, but why aren't you using patterns instead? For example:

Unprotect[Power]; Format[Power[x_, Rational[i_, j_]], FortranForm] := x^ToExpression["z"<>ToString[i]<>ToString[j]] Protect[Power]; 

Then:

ToString[x^(3/4), FortranForm] ToString[x^(1/7), FortranForm] 

"x**z34"

"x**z17"

$\endgroup$
1
  • $\begingroup$ Wow! Thanks for this! I already thought that my approach is a bit weird. I’ll test it for my case but from the looks this is what I was looking for. I’ll rate your answer as soon as I’ve completed the tests. $\endgroup$ Commented Mar 7, 2018 at 16:57

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.