Write float arrays to a text file: Difference between revisions
Content added Content deleted
SqrtNegInf (talk | contribs) (→{{header|Perl 6}}: GLR fix, improved idiomatic version) |
|||
Line 1,133: | Line 1,133: | ||
=={{header|Perl 6}}== |
=={{header|Perl 6}}== |
||
===Perl 5-ish=== |
|||
{{trans|Perl}} |
|||
Written in the style of the 2nd Perl 5 example. |
|||
<lang perl6>sub |
<lang perl6>sub write float ( $filename, @x, @y, $x_precision = 3, $y_precision = 5 ) { |
||
my $fh = open $filename, :w; |
my $fh = open $filename, :w; |
||
⚫ | |||
⚫ | |||
$fh.printf: "%.*g\t%.*g\n", $x_precision, $x, $y_precision, $y; |
$fh.printf: "%.*g\t%.*g\n", $x_precision, $x, $y_precision, $y; |
||
} |
} |
||
$fh.close; |
$fh.close; |
||
} |
} |
||
Line 1,147: | Line 1,146: | ||
my @y = @x.map({.sqrt}); |
my @y = @x.map({.sqrt}); |
||
writefloat( 'sqrt.dat', @x, @y );</lang> |
|||
{{out}} |
|||
File contents |
|||
<pre>1 1 |
<pre>1 1 |
||
2 1.4142 |
2 1.4142 |
||
3 1.7321 |
3 1.7321 |
||
1e+11 3.1623e+05</pre> |
1e+11 3.1623e+05</pre> |
||
===Idiomatic=== |
|||
Written in a more idiomatic style. |
|||
In Perl 6 Real::base can be used to convert to Str with arbitrary precision and any base you like. Using the hyper-operator >>. let us strip loops, many temporary variables and is a candidate for autothreading. |
|||
⚫ | |||
⚫ | |||
⚫ | |||
⚫ | |||
constant TAB = "\t" xx *; |
|||
constant NL = "\n" xx *; |
|||
⚫ | |||
⚫ | |||
} |
} |
||
my @x = 1, 2, 3, 1e11; |
my @x = 1, 2, 3, 1e11; |
||
writefloat('sqrt.dat', @x, @x>>.sqrt, :y-precision( |
writefloat('sqrt.dat', @x, @x>>.sqrt, :y-precision(5));</lang> |
||
{{out}} |
|||
<pre>1 1 |
|||
File contents |
|||
2 1.4142 |
|||
<pre>1.000 1.00000000000000000000 |
|||
3 1.7321 |
|||
2.000 1.41421356237309510107 |
|||
1e+11 3.1623e+05</pre> |
|||
3.000 1.73205080756887719318 |
|||
100000000000.000 316227.76601683790795505047</pre> |
|||
=={{header|Phix}}== |
=={{header|Phix}}== |