Write float arrays to a text file: Difference between revisions

Content added Content deleted
(→‎{{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 writedat ( $filename, @x, @y, $x_precision = 3, $y_precision = 5 ) {
<lang perl6>sub write float ( $filename, @x, @y, $x_precision = 3, $y_precision = 5 ) {
my $fh = open $filename, :w;
my $fh = open $filename, :w;
for flat @x Z @y -> $x, $y {

for @x Z @y -> $x, $y {
$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});


writedat( 'sqrt.dat', @x, @y );</lang>
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.
<lang perl6>sub writefloat($filename, @x, @y, :$x-precision = 3, :$y-precision = 3) {

open($filename, :w).print:
<lang perl6>sub writefloat($filename, @x, @y, :$x-precision = 3, :$y-precision = 5) {
join '', flat (@x>>.fmt("%.{$x-precision}g") X "\t") Z (@y>>.fmt("%.{$y-precision}g") X "\n");
constant TAB = "\t" xx *;
constant NL = "\n" xx *;

open($filename, :w).print(
flat @x>>.base(10, $x-precision) Z TAB Z @y>>.base(10, $y-precision) Z NL);
}
}
my @x = 1, 2, 3, 1e11;
my @x = 1, 2, 3, 1e11;
writefloat('sqrt.dat', @x, @x>>.sqrt, :y-precision(20));</lang>
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}}==