Jump to content

Write float arrays to a text file: Difference between revisions

→‎{{header|Perl 6}}: GLR fix, improved idiomatic version
(→‎{{header|Perl 6}}: GLR fix, improved idiomatic version)
Line 1,133:
 
=={{header|Perl 6}}==
===Perl 5-ish===
{{trans|Perl}}
Written in the style of the 2nd Perl 5 example.
<lang perl6>sub writedatwrite float ( $filename, @x, @y, $x_precision = 3, $y_precision = 5 ) {
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.close;
}
Line 1,147 ⟶ 1,146:
my @y = @x.map({.sqrt});
 
writedatwritefloat( 'sqrt.dat', @x, @y );</lang>
{{out}}
File contents
<pre>1 1
2 1.4142
3 1.7321
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 = 53) {
 
open($filename, :w).print(:
<lang perl6>sub writefloat($filename, @x, @y, :$x-precision = 3, :$y-precision = 5) {
join '', flat (@x>>.basefmt(10, "%.{$x-precision}g") ZX TAB"\t") Z (@y>>.basefmt(10, "%.{$y-precision}g") ZX NL"\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;
writefloat('sqrt.dat', @x, @x>>.sqrt, :y-precision(205));</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}}==
2,392

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.