1
$\begingroup$

I have a long function composed of polynomials and exponentials that I would like to convert to an appropriate form to cut and paste as an equation into SolidWorks. FortranForm gets me close and with a few substitutions I have the correct syntax. However the output displays 16 digits of precision. This is fine for a short function but for longer polynomial functions it causes the text to be too long for the equation input window. I would like to reduce the precision of the output to 4 or 5 significant digits.

Here is a simplified example:

ToString[FortranForm[1/0.123456789 x^2 + E^(-z^2/0.123456789)]];
StringReplace[%, {"E**" -> "exp", "**" -> "^"}]

(* "exp(-8.100000073710001*z^2) + 8.100000073710001*x^2" *)

I haven't been able to get NumberForm or Round to work, for example the input below still has 16 digits of precision in the fortran output.

NumberForm[1/3. x^2, 4]
FortranForm[%]

and Round doesn't seem to work with expressions.

Round[1/3. x^2, 0.001]

(* Round[0.333333 x^2, 0.001] *)
$\endgroup$
2
  • $\begingroup$ Would it make a difference if you set a narrower page width, so FortranForm generates appropriate line breaks? Something like: Internal`InheritedBlock[{$Output}, SetOptions[$Output, PageWidth -> 32]; FortranForm[N[Pi, 100]] ]. $\endgroup$
    – MarcoB
    Jun 11, 2018 at 17:49
  • $\begingroup$ I did have to set the PageWidth to eliminate the line breaks but that did not seem to affect the precision. $\endgroup$ Jun 11, 2018 at 18:14

1 Answer 1

3
$\begingroup$

I think CForm and FortranForm both produce the same format for decimal and scientific numbers, so you could do:

fortranString[expr_]:=Internal`InheritedBlock[{Real},
    Unprotect @ Real;
    Format[r_Real,FortranForm] := Format[SetPrecision[r,5], CForm];
    ToString[expr, FortranForm]
]

Your example:

fortranString[1/0.123456789^50 x^2 + E^(-z^2/0.123456789)]

(*
"E**(-8.1*z**2) + 2.6561e45*x**2"
*)
$\endgroup$
1
  • $\begingroup$ That did it, Thanks! (My attempt applying SetPrecision turned all the E^ into 2.7^ but yours does not.) $\endgroup$ Jun 11, 2018 at 18:21

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.