Message Boards Message Boards

0
|
8849 Views
|
3 Replies
|
1 Total Likes
View groups...
Share
Share this post:

How can Fortran format numbers be output?

Posted 11 years ago

I am trying to output numbers to a file to be read by another program. What I want is always of the format d.dddddddded. I got close using ScientificForm with the NumberFormat option.

fortran[n_] := 
 ScientificForm[n, 9, NumberFormat -> (Row[{#1, "e", #3}] &)]

But there is one issue: When the ScientificForm would have exponent = 0, the exponent (read by #3 in NumberFormat) apparently returns nothing instead of 0, so a number like 1.23 prints outputs the string 1.23e instead of 1.23e0. Any ideas?

Thanks, David

POSTED BY: David Keith
3 Replies
Posted 11 years ago

It's not elegant, but this works.

f[n_] := ScientificForm[n, 
  NumberFormat -> (Row[{#1, "e", If[#3 == "", "0", #3]}] & )]
POSTED BY: David Keith
Posted 11 years ago

I like it. A slight modification, and it works for symbolic constants, too.

f[n_] := ScientificForm[N[n], NumberFormat -> (Row[{#1, "e", If[#3 == "", "0", #3]}] & )]

f[E] = 2.71828e0
POSTED BY: Glenn Carlson
Posted 11 years ago

Thanks, Glenn. I think using N is a good idea.

In the versions below, I also convert the output to a string. The form with the second argument always outputs n digit precision, regardless of the true precision of x.

I still think my solution less than elegant. Considering the need to interface with antiquated programming methods, it would be nice if WL offered built-in functions to emulate the behavior of Fortran formatted IO and also printf and scanf from C and its derivatives.

(* String reprsenting x in E format *)
fForm[x_] := 
 ScientificForm[N[x], 
   NumberFormat -> (Row[{#1, "e", If[#3 == "", "0", #3]}] & )] // 
  ToString

(* The same, with n digits *)
fForm[x_, n_Integer] := 
 ScientificForm[SetPrecision[N[x], n], n, 
   NumberFormat -> (Row[{#1, "e", If[#3 == "", "0", #3]}] & )] // 
  ToString
POSTED BY: David Keith
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract