Message Boards Message Boards

Get FortranForm of fraction?


Hi, i have some analytical expressions to pass to python program. Therefor i just used FortranForm and save it into a text file.

Now i wonder if there is any way the function FortranForm leave expressions like 1/3 in the fraction representation and do not approximate it.

In[9]:= FortranForm[2/3]
Out[9]:= 0.6666666666666666

(Its a differential equation and its highly stiff so i dont want to get problems just because of that)

Many Thank in advance!

1 year ago


There is no easy way to change FortranForm to do that (to the best of my knowledge), however, I think that you can get the accuracy you need by doing either of the approaches below:

Set the number of digits supported by python

Lookup the maximum number of digits supported by Python and set the number of digits in the equations to that maximum number.

For example:

eqn = 2/3 x^2 + 3 y^2 + 4/9 z

Can be converted to Fortran Form with 30 digits by doing the following:

In[2]:= N[eqn, 30] // FortranForm

0.666666666666666666666666666667*x**2 + 3.*y**2 + 0.444444444444444444444444444444*z


Create a special function in Python

Another alternative is to write some code to replace the Rational numbers with functions (like rational[2,3]) (lowercase so as not to confuse with the Rational in Mathematica) and then define a python function "rational" to do your division.

To do this:

eqn /. x_Rational :> rational[Numerator[x], Denominator[x]]

which gives you

3 y^2 + x^2 rational[2, 3] + z rational[4, 9]

Now make a function rational(x,y) in python to return x/y to the machine precision.

I hope this helps.

POSTED BY: Neil Singer
1 year ago

Group Abstract Group Abstract