Write float arrays to a text file: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 29: Line 29:


=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
with Ada.Numerics.Elementary_Functions; use Ada.Numerics.Elementary_Functions;
Line 62: Line 62:
Write_columns (File, X, Y);
Write_columns (File, X, Y);
Close (File);
Close (File);
end Write_Float_Array;</lang>
end Write_Float_Array;</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 69: Line 69:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
<lang algol68>PROC writedat = (STRING filename, []REAL x, y, INT x width, y width)VOID: (
<syntaxhighlight lang="algol68">PROC writedat = (STRING filename, []REAL x, y, INT x width, y width)VOID: (
FILE f;
FILE f;
INT errno = open(f, filename, stand out channel);
INT errno = open(f, filename, stand out channel);
Line 99: Line 99:
print((line,new line))
print((line,new line))
OD
OD
)</lang>
)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 113: Line 113:
=={{header|Amazing Hopper}}==
=={{header|Amazing Hopper}}==
Version hopper-FLOW:
Version hopper-FLOW:
<syntaxhighlight lang="amazing hopper">
<lang Amazing Hopper>
#include <flow.h>
#include <flow.h>


Line 127: Line 127:
TOK-SEP( TAB ), SAVE-MAT(f, "filename.txt" )
TOK-SEP( TAB ), SAVE-MAT(f, "filename.txt" )
END
END
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 138: Line 138:


=={{header|Applesoft BASIC}}==
=={{header|Applesoft BASIC}}==
<lang gwbasic> 100 D$ = CHR$ (4)
<syntaxhighlight lang="gwbasic"> 100 D$ = CHR$ (4)
110 F$ = "FILENAME.TXT"
110 F$ = "FILENAME.TXT"
120 READ X(0),X(1),X(2),X(3),Y(0),Y(1),Y(2),Y(3)
120 READ X(0),X(1),X(2),X(3),Y(0),Y(1),Y(2),Y(3)
Line 178: Line 178:
480 Q = NOT (O < 1)
480 Q = NOT (O < 1)
490 NEXT Q
490 NEXT Q
500 RETURN</lang>
500 RETURN</syntaxhighlight>
=={{header|AWK}}==
=={{header|AWK}}==
As usual, the order of array traversal in AWK is not necessarily the same as the input had:
As usual, the order of array traversal in AWK is not necessarily the same as the input had:
<lang awk>$ awk 'BEGIN{split("1 2 3 1e11",x);
<syntaxhighlight lang="awk">$ awk 'BEGIN{split("1 2 3 1e11",x);
> split("1 1.4142135623730951 1.7320508075688772 316227.76601683791",y);
> split("1 1.4142135623730951 1.7320508075688772 316227.76601683791",y);
> for(i in x)printf("%6g %.5g\n",x[i],y[i])}'
> for(i in x)printf("%6g %.5g\n",x[i],y[i])}'
Line 187: Line 187:
1 1
1 1
2 1.4142
2 1.4142
3 1.7321</lang>
3 1.7321</syntaxhighlight>
For the text file part of the task, just redirect stdout to it.
For the text file part of the task, just redirect stdout to it.


=={{header|BASIC256}}==
=={{header|BASIC256}}==
<lang basic256>x$ = "1 2 3 1e11"
<syntaxhighlight lang="basic256">x$ = "1 2 3 1e11"
x$ = explode(x$, " ")
x$ = explode(x$, " ")


Line 200: Line 200:
writeline f, int(x$[i]) + chr(9) + round(sqrt(x$[i]),4)
writeline f, int(x$[i]) + chr(9) + round(sqrt(x$[i]),4)
next i
next i
close f</lang>
close f</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> DIM x(3), y(3)
<syntaxhighlight lang="bbcbasic"> DIM x(3), y(3)
x() = 1, 2, 3, 1E11
x() = 1, 2, 3, 1E11
FOR i% = 0 TO 3
FOR i% = 0 TO 3
Line 224: Line 224:
NEXT
NEXT
CLOSE #outfile%</lang>
CLOSE #outfile%</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 234: Line 234:


=={{header|C}}==
=={{header|C}}==
<lang c>#include <stdio.h>
<syntaxhighlight lang="c">#include <stdio.h>
#include <math.h>
#include <math.h>


Line 251: Line 251:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


The file <tt>"floatArray"</tt> then contains the following:
The file <tt>"floatArray"</tt> then contains the following:
<lang>1 1
<syntaxhighlight lang="text">1 1
2 1.4142
2 1.4142
3 1.7321
3 1.7321
1e+11 3.1623e+05</lang>
1e+11 3.1623e+05</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>using System.IO;
<syntaxhighlight lang="csharp">using System.IO;


class Program
class Program
Line 278: Line 278:
outf.WriteLine(formatString, x[i], y[i]);
outf.WriteLine(formatString, x[i], y[i]);
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 288: Line 288:
=={{header|C++}}==
=={{header|C++}}==
Function ''writedat()'':
Function ''writedat()'':
<lang cpp>template<class InputIterator, class InputIterator2>
<syntaxhighlight lang="cpp">template<class InputIterator, class InputIterator2>
void writedat(const char* filename,
void writedat(const char* filename,
InputIterator xbegin, InputIterator xend,
InputIterator xbegin, InputIterator xend,
Line 300: Line 300:
f << std::setprecision(xprecision) << *xbegin << '\t'
f << std::setprecision(xprecision) << *xbegin << '\t'
<< std::setprecision(yprecision) << *ybegin << '\n';
<< std::setprecision(yprecision) << *ybegin << '\n';
}</lang>
}</syntaxhighlight>
Example:
Example:
<lang cpp>#include <algorithm>
<syntaxhighlight lang="cpp">#include <algorithm>
#include <cmath> // ::sqrt()
#include <cmath> // ::sqrt()
#include <fstream>
#include <fstream>
Line 332: Line 332:
}
}
return 0;
return 0;
}</lang>
}</syntaxhighlight>


{{out|Result}}
{{out|Result}}
Line 343: Line 343:


=={{header|COBOL}}==
=={{header|COBOL}}==
<syntaxhighlight lang="cobol">
<lang COBOL>
identification division.
identification division.
program-id. wr-float.
program-id. wr-float.
Line 386: Line 386:
.
.
end program wr-float.
end program wr-float.
</syntaxhighlight>
</lang>
{{out|Result}}
{{out|Result}}
<pre>
<pre>
Line 396: Line 396:


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang lisp>(with-open-file (stream (make-pathname :name "filename") :direction :output)
<syntaxhighlight lang="lisp">(with-open-file (stream (make-pathname :name "filename") :direction :output)
(let* ((x (make-array 4 :initial-contents '(1 2 3 1e11)))
(let* ((x (make-array 4 :initial-contents '(1 2 3 1e11)))
(y (map 'vector 'sqrt x))
(y (map 'vector 'sqrt x))
Line 403: Line 403:
(fmt (format nil "~~,1,~d,,G~~12t~~,~dG~~%" xprecision yprecision)))
(fmt (format nil "~~,1,~d,,G~~12t~~,~dG~~%" xprecision yprecision)))
(map nil (lambda (a b)
(map nil (lambda (a b)
(format stream fmt a b)) x y)))</lang>
(format stream fmt a b)) x y)))</syntaxhighlight>
Using [[CLISP]] I get
Using [[CLISP]] I get
1. 1.0000
1. 1.0000
Line 411: Line 411:


=={{header|D}}==
=={{header|D}}==
<lang d>import std.file, std.conv, std.string;
<syntaxhighlight lang="d">import std.file, std.conv, std.string;


void main() {
void main() {
Line 426: Line 426:


write("float_array.txt", tmp);
write("float_array.txt", tmp);
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>1 1
<pre>1 1
Line 435: Line 435:
{{libheader| System.SysUtils}}
{{libheader| System.SysUtils}}
{{libheader| System.IoUtils}}
{{libheader| System.IoUtils}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Write_float_arrays_to_a_text_file;
program Write_float_arrays_to_a_text_file;


Line 470: Line 470:


TFile.WriteAllLines('FloatArrayColumns.txt', Merge(ToString(x), ToString(y)));
TFile.WriteAllLines('FloatArrayColumns.txt', Merge(ToString(x), ToString(y)));
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>1 1
<pre>1 1
Line 478: Line 478:


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>defmodule Write_float_arrays do
<syntaxhighlight lang="elixir">defmodule Write_float_arrays do
def task(xs, ys, fname, precision\\[]) do
def task(xs, ys, fname, precision\\[]) do
xprecision = Keyword.get(precision, :x, 2)
xprecision = Keyword.get(precision, :x, 2)
Line 499: Line 499:
precision = [x: 3, y: 5]
precision = [x: 3, y: 5]
Write_float_arrays.task(x, y, fname, precision)
Write_float_arrays.task(x, y, fname, precision)
IO.puts File.read!(fname)</lang>
IO.puts File.read!(fname)</syntaxhighlight>


{{out}}
{{out}}
Line 517: Line 517:
Erlang thinks 1 is an integer. To persuade it otherwise I have to use 1.0.
Erlang thinks 1 is an integer. To persuade it otherwise I have to use 1.0.


<syntaxhighlight lang="erlang">
<lang Erlang>
-module( write_float_arrays ).
-module( write_float_arrays ).


Line 540: Line 540:
[ok = io:fwrite( IO, Format, [X, Y]) || {X, Y} <- lists:zip( Xs, Ys)],
[ok = io:fwrite( IO, Format, [X, Y]) || {X, Y} <- lists:zip( Xs, Ys)],
file:close( IO ).
file:close( IO ).
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 549: Line 549:


=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang euphoria>constant x = {1, 2, 3, 1e11},
<syntaxhighlight lang="euphoria">constant x = {1, 2, 3, 1e11},
y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}
y = {1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}


Line 558: Line 558:
printf(fn,"%.3g\t%.5g\n",{x[n],y[n]})
printf(fn,"%.3g\t%.5g\n",{x[n],y[n]})
end for
end for
close(fn)</lang>
close(fn)</syntaxhighlight>


=={{header|F Sharp|F#}}==
=={{header|F Sharp|F#}}==
<lang fsharp>[<EntryPoint>]
<syntaxhighlight lang="fsharp">[<EntryPoint>]
let main argv =
let main argv =
let x = [ 1.; 2.; 3.; 1e11 ]
let x = [ 1.; 2.; 3.; 1e11 ]
Line 572: Line 572:
let line = sprintf "%.*g\t%.*g"
let line = sprintf "%.*g\t%.*g"
List.iter2 (fun x y -> file.WriteLine (line xprecision x yprecision y)) x y
List.iter2 (fun x y -> file.WriteLine (line xprecision x yprecision y)) x y
0</lang>
0</syntaxhighlight>
Content of File, visualized with TAB=8
Content of File, visualized with TAB=8
<pre>1 1
<pre>1 1
Line 582: Line 582:
{{works with|GNU Forth}}
{{works with|GNU Forth}}


<lang forth>create x 1e f, 2e f, 3e f, 1e11 f,
<syntaxhighlight lang="forth">create x 1e f, 2e f, 3e f, 1e11 f,
create y 1e f, 2e fsqrt f, 3e fsqrt f, 1e11 fsqrt f,
create y 1e f, 2e fsqrt f, 3e fsqrt f, 1e11 fsqrt f,


Line 596: Line 596:


outfile-id stdout to outfile-id
outfile-id stdout to outfile-id
close-file throw ;</lang>
close-file throw ;</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
=== Fortran 90 ===
=== Fortran 90 ===
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
<lang fortran>program writefloats
<syntaxhighlight lang="fortran">program writefloats
implicit none
implicit none


Line 626: Line 626:
end subroutine writexy
end subroutine writexy


end program writefloats</lang>
end program writefloats</syntaxhighlight>


The arrays x and y should have same bounds (and size); this constraint is not checked.
The arrays x and y should have same bounds (and size); this constraint is not checked.


=== Fortran 77 ===
=== Fortran 77 ===
<lang fortran> program writefloats
<syntaxhighlight lang="fortran"> program writefloats
integer i
integer i
double precision x(4), y(4)
double precision x(4), y(4)
Line 642: Line 642:
open(unit=15, file='two_cols.txt', status='new')
open(unit=15, file='two_cols.txt', status='new')
write(15, '(f20.3,f21.4)') (x(i), y(i), i = 1, 4)
write(15, '(f20.3,f21.4)') (x(i), y(i), i = 1, 4)
end</lang>
end</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Dim x(0 To 3) As Double = {1, 2, 3, 1e11}
Dim x(0 To 3) As Double = {1, 2, 3, 1e11}
Line 657: Line 657:
Print #1, Using "#^^^^"; x(3);
Print #1, Using "#^^^^"; x(3);
Print #1, Spc(2); Using "##.####^^^^"; y(3)
Print #1, Spc(2); Using "##.####^^^^"; y(3)
Close #1</lang>
Close #1</syntaxhighlight>
Contents of output.txt :
Contents of output.txt :
{{out}}
{{out}}
Line 668: Line 668:


=={{header|Go}}==
=={{header|Go}}==
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 697: Line 697:
}
}
f.Close()
f.Close()
}</lang>
}</syntaxhighlight>
File contents:
File contents:
<pre>
<pre>
Line 708: Line 708:
=={{header|Haskell}}==
=={{header|Haskell}}==
Probably not very idiomatic but oh well
Probably not very idiomatic but oh well
<lang haskell>import System.IO
<syntaxhighlight lang="haskell">import System.IO
import Text.Printf
import Text.Printf
import Control.Monad
import Control.Monad
Line 716: Line 716:
-- Haskell's printf doesn't support a precision given as an argument for some reason, so we insert it into the format manually:
-- Haskell's printf doesn't support a precision given as an argument for some reason, so we insert it into the format manually:
let writeLine = hPrintf h $ "%." ++ show xprec ++ "g\t%." ++ show yprec ++ "g\n" in
let writeLine = hPrintf h $ "%." ++ show xprec ++ "g\t%." ++ show yprec ++ "g\n" in
zipWithM_ writeLine x y</lang>
zipWithM_ writeLine x y</syntaxhighlight>
Example usage
Example usage
Prelude> let x = [1, 2, 3, 1e11]
Prelude> let x = [1, 2, 3, 1e11]
Line 730: Line 730:


Alternative solution without Printf
Alternative solution without Printf
<lang haskell>import System.IO
<syntaxhighlight lang="haskell">import System.IO
import Control.Monad
import Control.Monad
import Numeric
import Numeric
Line 737: Line 737:
withFile filename WriteMode $ \h ->
withFile filename WriteMode $ \h ->
let writeLine a b = hPutStrLn h $ showGFloat (Just xprec) a "" ++ "\t" ++ showGFloat (Just yprec) b "" in
let writeLine a b = hPutStrLn h $ showGFloat (Just xprec) a "" ++ "\t" ++ showGFloat (Just yprec) b "" in
zipWithM_ writeLine x y</lang>
zipWithM_ writeLine x y</syntaxhighlight>


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang HicEst>REAL :: n=4, x(n), y(n)
<syntaxhighlight lang="hicest">REAL :: n=4, x(n), y(n)
CHARACTER :: outP = "Test.txt"
CHARACTER :: outP = "Test.txt"


Line 748: Line 748:
DO i = 1, n
DO i = 1, n
WRITE(FIle=outP, Format='F5, F10.3') x(i), y(i)
WRITE(FIle=outP, Format='F5, F10.3') x(i), y(i)
ENDDO </lang>
ENDDO </syntaxhighlight>
Alternative: Display or Edit the formatted arrays in a [http://www.HicEst.com/MatrixExplorer spreadsheet-like dialog] with a common scroll bar.
Alternative: Display or Edit the formatted arrays in a [http://www.HicEst.com/MatrixExplorer spreadsheet-like dialog] with a common scroll bar.
The menu More - Export - File writes the formatted arrays to a file:
The menu More - Export - File writes the formatted arrays to a file:
<lang HicEst>DLG(Text=x, Format='i12', Edit=y, Format='F10.2', Y=0)</lang>
<syntaxhighlight lang="hicest">DLG(Text=x, Format='i12', Edit=y, Format='F10.2', Y=0)</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Line 757: Line 757:
The following works in both languages.
The following works in both languages.


<lang unicon>link printf
<syntaxhighlight lang="unicon">link printf


procedure main()
procedure main()
Line 763: Line 763:
every put(y := [], sqrt(!x))
every put(y := [], sqrt(!x))
every fprintf(open("filename","w"),"%10.2e %10.4e\n", x[i := 1 to *x], y[i])
every fprintf(open("filename","w"),"%10.2e %10.4e\n", x[i := 1 to *x], y[i])
end</lang>
end</syntaxhighlight>


Contents of <tt>filename</tt> after running:
Contents of <tt>filename</tt> after running:
Line 794: Line 794:
The file <tt>"datafile.txt"</tt> then contains the following:
The file <tt>"datafile.txt"</tt> then contains the following:


<lang idl>1 1
<syntaxhighlight lang="idl">1 1
2 1.4142
2 1.4142
3 1.7321
3 1.7321
1E+011 3.1623E+005</lang>
1E+011 3.1623E+005</syntaxhighlight>


This is fairly ugly and un-IDLish.
This is fairly ugly and un-IDLish.
Line 807: Line 807:


=={{header|J}}==
=={{header|J}}==
<lang j>require 'files' NB. for fwrites
<syntaxhighlight lang="j">require 'files' NB. for fwrites


x =. 1 2 3 1e11
x =. 1 2 3 1e11
Line 819: Line 819:
data =. (0 j. xprecision,yprecision) ": x,.y
data =. (0 j. xprecision,yprecision) ": x,.y


data fwrites filename</lang>
data fwrites filename</syntaxhighlight>


Or, more concisely:
Or, more concisely:


<lang j>((0 j. 3 5) ": (,.%:) 1 2 3 1e11) fwrites 'whatever.txt' [ require 'fwrites'</lang>
<syntaxhighlight lang="j">((0 j. 3 5) ": (,.%:) 1 2 3 1e11) fwrites 'whatever.txt' [ require 'fwrites'</syntaxhighlight>


This loses all of the inline comments and names, and instead relies on the reader's understanding of the purpose of each of the names (for example: 3 is the precision of the first column, and 5 is the precision of the second column).
This loses all of the inline comments and names, and instead relies on the reader's understanding of the purpose of each of the names (for example: 3 is the precision of the first column, and 5 is the precision of the second column).
Line 829: Line 829:
Note that J's idea of precision here is "positions after the decimal point":
Note that J's idea of precision here is "positions after the decimal point":


<lang j> (0 j. 3 5) ": (,.%:) 1 2 3 1e11
<syntaxhighlight lang="j"> (0 j. 3 5) ": (,.%:) 1 2 3 1e11
1.000 1.00000
1.000 1.00000
2.000 1.41421
2.000 1.41421
3.000 1.73205
3.000 1.73205
100000000000.000 316227.76602</lang>
100000000000.000 316227.76602</syntaxhighlight>


=={{header|Java}}==
=={{header|Java}}==
<lang java5>import java.io.*;
<syntaxhighlight lang="java5">import java.io.*;


public class FloatArray {
public class FloatArray {
Line 868: Line 868:
} catch (IOException e) { }
} catch (IOException e) { }
}
}
}</lang>
}</syntaxhighlight>


=={{header|Joy}}==
=={{header|Joy}}==
<syntaxhighlight lang=Joy>
<syntaxhighlight lang="joy">
DEFINE write-floats ==
DEFINE write-floats ==
['g 0] [formatf] enconcat map rollup
['g 0] [formatf] enconcat map rollup
Line 890: Line 890:
=={{header|jq}}==
=={{header|jq}}==
''' Program''':
''' Program''':
<lang jq>[1, 2, 3, 1e11] as $x
<syntaxhighlight lang="jq">[1, 2, 3, 1e11] as $x
| $x | map(sqrt) as $y
| $x | map(sqrt) as $y
| range(0; $x|length) as $i
| range(0; $x|length) as $i
| "\($x[$i]) \($y[$i])"</lang>
| "\($x[$i]) \($y[$i])"</syntaxhighlight>
''' Execution''':
''' Execution''':
To write the output to "filename":
To write the output to "filename":
<lang sh>$ jq -n -r -f Write_float_arrays_to_a_text_file.jq > filename</lang>
<syntaxhighlight lang="sh">$ jq -n -r -f Write_float_arrays_to_a_text_file.jq > filename</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>xprecision = 3
<syntaxhighlight lang="julia">xprecision = 3
yprecision = 5
yprecision = 5
x = round.([1, 2, 3, 1e11],xprecision)
x = round.([1, 2, 3, 1e11],xprecision)
y = round.([1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791],yprecision)
y = round.([1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791],yprecision)
writedlm("filename", [x y], '\t')</lang>
writedlm("filename", [x y], '\t')</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


import java.io.File
import java.io.File
Line 923: Line 923:
}
}
}
}
}</lang>
}</syntaxhighlight>


Contents of 'output.txt':
Contents of 'output.txt':
Line 934: Line 934:


=={{header|Lingo}}==
=={{header|Lingo}}==
<lang lingo>on saveFloatLists (filename, x, y, xprecision, yprecision)
<syntaxhighlight lang="lingo">on saveFloatLists (filename, x, y, xprecision, yprecision)
eol = numtochar(10) -- LF
eol = numtochar(10) -- LF
fp = xtra("fileIO").new()
fp = xtra("fileIO").new()
Line 948: Line 948:
end repeat
end repeat
fp.closeFile()
fp.closeFile()
end</lang>
end</syntaxhighlight>


<lang lingo>x = [1.0, PI, sqrt(2)]
<syntaxhighlight lang="lingo">x = [1.0, PI, sqrt(2)]
y = [2.0, log(10), sqrt(3)]
y = [2.0, log(10), sqrt(3)]
saveFloatLists("floats.txt", x, y, 3, 5)</lang>
saveFloatLists("floats.txt", x, y, 3, 5)</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>filename = "file.txt"
<syntaxhighlight lang="lua">filename = "file.txt"


x = { 1, 2, 3, 1e11 }
x = { 1, 2, 3, 1e11 }
Line 970: Line 970:
end
end


io.close( fp )</lang>
io.close( fp )</syntaxhighlight>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>exportPrec[path_, data1_, data2_, prec1_, prec2_] :=
<syntaxhighlight lang="mathematica">exportPrec[path_, data1_, data2_, prec1_, prec2_] :=
Export[
Export[
path,
path,
Transpose[{Map[ToString[NumberForm[#, prec2]] &, data2], Map[ToString[NumberForm[#, prec1]] &, data1]}],
Transpose[{Map[ToString[NumberForm[#, prec2]] &, data2], Map[ToString[NumberForm[#, prec1]] &, data1]}],
"Table"
"Table"
]</lang>
]</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==


<lang Matlab> x = [1, 2, 3, 1e11];
<syntaxhighlight lang="matlab"> x = [1, 2, 3, 1e11];
y = [1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791];
y = [1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791];
fid = fopen('filename','w')
fid = fopen('filename','w')
fprintf(fid,'%.3g\t%.5g\n',[x;y]);
fprintf(fid,'%.3g\t%.5g\n',[x;y]);
fclose(fid); </lang>
fclose(fid); </syntaxhighlight>


{{out}}
{{out}}
Line 996: Line 996:


=={{header|Mercury}}==
=={{header|Mercury}}==
<lang Mercury>:- module write_float_arrays.
<syntaxhighlight lang="mercury">:- module write_float_arrays.
:- interface.
:- interface.


Line 1,024: Line 1,024:


write_dat(File, XPrec, YPrec, X, Y, !IO) :-
write_dat(File, XPrec, YPrec, X, Y, !IO) :-
io.format(File, "%.*g\t%.*g\n", [i(XPrec), f(X), i(YPrec), f(Y)], !IO).</lang>
io.format(File, "%.*g\t%.*g\n", [i(XPrec), f(X), i(YPrec), f(Y)], !IO).</syntaxhighlight>


File contents:
File contents:
Line 1,036: Line 1,036:


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang NetRexx>/* NetRexx */
<syntaxhighlight lang="netrexx">/* NetRexx */


options replace format comments java crossref savelog symbols nobinary
options replace format comments java crossref savelog symbols nobinary
Line 1,071: Line 1,071:


return
return
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,081: Line 1,081:


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang NewLISP>; file: write-float-array.lsp
<syntaxhighlight lang="newlisp">; file: write-float-array.lsp
; url: http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
; url: http://rosettacode.org/wiki/Write_float_arrays_to_a_text_file
; author: oofoe 2012-01-30
; author: oofoe 2012-01-30
Line 1,106: Line 1,106:
(print (read-file "filename.chan"))
(print (read-file "filename.chan"))


(exit)</lang>
(exit)</syntaxhighlight>


{{out}}
{{out}}
Line 1,117: Line 1,117:


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import strutils, math, sequtils
<syntaxhighlight lang="nim">import strutils, math, sequtils


const OutFileName = "floatarr2file.txt"
const OutFileName = "floatarr2file.txt"
Line 1,134: Line 1,134:
OutFileName.writeFile res
OutFileName.writeFile res
var res2 = OutFileName.readFile()
var res2 = OutFileName.readFile()
echo res2</lang>
echo res2</syntaxhighlight>
{{out}}
{{out}}
<pre>1.00 1.0000
<pre>1.00 1.0000
Line 1,142: Line 1,142:


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>let write_dat filename x y ?(xprec=3) ?(yprec=5) () =
<syntaxhighlight lang="ocaml">let write_dat filename x y ?(xprec=3) ?(yprec=5) () =
let oc = open_out filename in
let oc = open_out filename in
let write_line a b = Printf.fprintf oc "%.*g\t%.*g\n" xprec a yprec b in
let write_line a b = Printf.fprintf oc "%.*g\t%.*g\n" xprec a yprec b in
List.iter2 write_line x y;
List.iter2 write_line x y;
close_out oc</lang>
close_out oc</syntaxhighlight>
Example usage
Example usage
# let x = [1.0; 2.0; 3.0; 1e11];;
# let x = [1.0; 2.0; 3.0; 1e11];;
Line 1,170: Line 1,170:
=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.5.0 and above}}
{{works with|PARI/GP|2.5.0 and above}}
<lang parigp>f(x,pr)={
<syntaxhighlight lang="parigp">f(x,pr)={
Strprintf(if(x>=10^pr,
Strprintf(if(x>=10^pr,
Str("%.",pr-1,"e")
Str("%.",pr-1,"e")
Line 1,181: Line 1,181:
write("filename",f(x[i],xprec),"\t",f(y[i],yprec))
write("filename",f(x[i],xprec),"\t",f(y[i],yprec))
)
)
};</lang>
};</syntaxhighlight>


=={{header|Pascal}}==
=={{header|Pascal}}==
<lang pascal>Program WriteNumbers;
<syntaxhighlight lang="pascal">Program WriteNumbers;


const
const
Line 1,202: Line 1,202:
writeln (filename, x[i]:baseDigits+xprecision, sqrt(x[i]):baseDigits+yprecision);
writeln (filename, x[i]:baseDigits+xprecision, sqrt(x[i]):baseDigits+yprecision);
close (filename);
close (filename);
end.</lang>
end.</syntaxhighlight>
File contents
File contents
<pre>
<pre>
Line 1,212: Line 1,212:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>use autodie;
<syntaxhighlight lang="perl">use autodie;


sub writedat {
sub writedat {
Line 1,229: Line 1,229:
my @y = map sqrt, @x;
my @y = map sqrt, @x;


writedat("sqrt.dat", \@x, \@y);</lang>
writedat("sqrt.dat", \@x, \@y);</syntaxhighlight>
File contents
File contents
<pre>
<pre>
Line 1,240: Line 1,240:
Alternatively, with the CPAN List::MoreUtils package:
Alternatively, with the CPAN List::MoreUtils package:


<lang perl>use autodie;
<syntaxhighlight lang="perl">use autodie;
use List::MoreUtils qw(each_array);
use List::MoreUtils qw(each_array);


Line 1,258: Line 1,258:
my @y = map sqrt, @x;
my @y = map sqrt, @x;


writedat("sqrt.dat", \@x, \@y);</lang>
writedat("sqrt.dat", \@x, \@y);</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
Copy of [[Write_float_arrays_to_a_text_file#Euphoria|Euphoria]]
Copy of [[Write_float_arrays_to_a_text_file#Euphoria|Euphoria]]
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">constant</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1e11</span><span style="color: #0000FF;">},</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1e11</span><span style="color: #0000FF;">},</span>
<span style="color: #000000;">y</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1.4142135623730951</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1.7320508075688772</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">316227.76601683791</span><span style="color: #0000FF;">}</span>
<span style="color: #000000;">y</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1.4142135623730951</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">1.7320508075688772</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">316227.76601683791</span><span style="color: #0000FF;">}</span>
Line 1,271: Line 1,271:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">close</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fn</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
File contents:
File contents:
<pre>
<pre>
Line 1,282: Line 1,282:
=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
An exponential format like "1e11" is not supported
An exponential format like "1e11" is not supported
<lang PicoLisp>(setq *Xprecision 3 *Yprecision 5)
<syntaxhighlight lang="picolisp">(setq *Xprecision 3 *Yprecision 5)


(scl 7)
(scl 7)
Line 1,292: Line 1,292:
(round Y *Yprecision) ) )
(round Y *Yprecision) ) )
(1.0 2.0 3.0)
(1.0 2.0 3.0)
(1.0 1.414213562 1.732050807) )</lang>
(1.0 1.414213562 1.732050807) )</syntaxhighlight>
{{out}}
{{out}}
<pre>1.000 1.00000
<pre>1.000 1.00000
Line 1,299: Line 1,299:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang PL/I>*Process source attributes xref;
<syntaxhighlight lang="pl/i">*Process source attributes xref;
aaa: Proc Options(main);
aaa: Proc Options(main);
declare X(5) float (9) initial (1, 2, 3, 4, 5),
declare X(5) float (9) initial (1, 2, 3, 4, 5),
Line 1,311: Line 1,311:
(skip,e(19,x_precision),
(skip,e(19,x_precision),
x(2),e(24,y_precision));
x(2),e(24,y_precision));
end;</lang>
end;</syntaxhighlight>
{{out}}
{{out}}
<pre> 1.000000000E+0000 9.0000000000000000E+0000
<pre> 1.000000000E+0000 9.0000000000000000E+0000
Line 1,320: Line 1,320:


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang PowerShell>$x = @(1, 2, 3, 1e11)
<syntaxhighlight lang="powershell">$x = @(1, 2, 3, 1e11)
$y = @(1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791)
$y = @(1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791)
$xprecision = 3
$xprecision = 3
Line 1,328: Line 1,328:
}
}
($arr | format-table -HideTableHeaders | Out-String).Trim() > filename.txt
($arr | format-table -HideTableHeaders | Out-String).Trim() > filename.txt
</syntaxhighlight>
</lang>
<b>Output:</b>
<b>Output:</b>
<pre>
<pre>
Line 1,338: Line 1,338:


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>#Size = 4
<syntaxhighlight lang="purebasic">#Size = 4


DataSection
DataSection
Line 1,365: Line 1,365:
CloseFile(fileID)
CloseFile(fileID)
EndIf
EndIf
EndIf</lang>
EndIf</syntaxhighlight>
{{out}} to text file:
{{out}} to text file:
<pre>1.000 1.00000
<pre>1.000 1.00000
Line 1,374: Line 1,374:
=={{header|Python}}==
=={{header|Python}}==
{{works with|Python|2.6}}
{{works with|Python|2.6}}
<lang python>import itertools
<syntaxhighlight lang="python">import itertools
def writedat(filename, x, y, xprecision=3, yprecision=5):
def writedat(filename, x, y, xprecision=3, yprecision=5):
with open(filename,'w') as f:
with open(filename,'w') as f:
for a, b in itertools.izip(x, y):
for a, b in itertools.izip(x, y):
print >> f, "%.*g\t%.*g" % (xprecision, a, yprecision, b)</lang>
print >> f, "%.*g\t%.*g" % (xprecision, a, yprecision, b)</syntaxhighlight>
Example usage
Example usage
<lang python>>>> import math
<syntaxhighlight lang="python">>>> import math
>>> x = [1, 2, 3, 1e11]
>>> x = [1, 2, 3, 1e11]
>>> y = map(math.sqrt, x)
>>> y = map(math.sqrt, x)
Line 1,394: Line 1,394:
2 1.4142
2 1.4142
3 1.7321
3 1.7321
1e+011 3.1623e+005</lang>
1e+011 3.1623e+005</syntaxhighlight>


{{works with|Python|3}}
{{works with|Python|3}}
<lang python>def writedat(filename, x, y, xprecision=3, yprecision=5):
<syntaxhighlight lang="python">def writedat(filename, x, y, xprecision=3, yprecision=5):
with open(filename,'w') as f:
with open(filename,'w') as f:
for a, b in zip(x, y):
for a, b in zip(x, y):
print("%.*g\t%.*g" % (xprecision, a, yprecision, b), file=f)
print("%.*g\t%.*g" % (xprecision, a, yprecision, b), file=f)
#or, using the new-style formatting:
#or, using the new-style formatting:
#print("{1:.{0}g}\t{3:.{2}g}".format(xprecision, a, yprecision, b), file=f)</lang>
#print("{1:.{0}g}\t{3:.{2}g}".format(xprecision, a, yprecision, b), file=f)</syntaxhighlight>


=={{header|R}}==
=={{header|R}}==
<lang R>writexy <- function(file, x, y, xprecision=3, yprecision=3) {
<syntaxhighlight lang="r">writexy <- function(file, x, y, xprecision=3, yprecision=3) {
fx <- formatC(x, digits=xprecision, format="g", flag="-")
fx <- formatC(x, digits=xprecision, format="g", flag="-")
fy <- formatC(y, digits=yprecision, format="g", flag="-")
fy <- formatC(y, digits=yprecision, format="g", flag="-")
Line 1,414: Line 1,414:
x <- c(1, 2, 3, 1e11)
x <- c(1, 2, 3, 1e11)
y <- sqrt(x)
y <- sqrt(x)
writexy("test.txt", x, y, yp=5)</lang>
writexy("test.txt", x, y, yp=5)</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
#lang racket


Line 1,441: Line 1,441:
100000000000 316227.76602
100000000000 316227.76602
|#
|#
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
Line 1,447: Line 1,447:
===Perl 5-ish===
===Perl 5-ish===
Written in the style of the 2nd Perl 5 example.
Written in the style of the 2nd Perl 5 example.
<lang perl6>sub writefloat ( $filename, @x, @y, $x_precision = 3, $y_precision = 5 ) {
<syntaxhighlight lang="raku" line>sub writefloat ( $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 flat @x Z @y -> $x, $y {
Line 1,458: Line 1,458:
my @y = @x.map({.sqrt});
my @y = @x.map({.sqrt});


writefloat( 'sqrt.dat', @x, @y );</lang>
writefloat( 'sqrt.dat', @x, @y );</syntaxhighlight>
{{out}}
{{out}}
<pre>1 1
<pre>1 1
Line 1,466: Line 1,466:
===Idiomatic===
===Idiomatic===
Written in a more idiomatic style.
Written in a more idiomatic style.
<lang perl6>sub writefloat($filename, @x, @y, :$x-precision = 3, :$y-precision = 3) {
<syntaxhighlight lang="raku" line>sub writefloat($filename, @x, @y, :$x-precision = 3, :$y-precision = 3) {
open($filename, :w).print:
open($filename, :w).print:
join '', flat (@x».fmt("%.{$x-precision}g") X "\t") Z (@y».fmt("%.{$y-precision}g") X "\n");
join '', flat (@x».fmt("%.{$x-precision}g") X "\t") Z (@y».fmt("%.{$y-precision}g") X "\n");
}
}
my @x = 1, 2, 3, 1e11;
my @x = 1, 2, 3, 1e11;
writefloat('sqrt.dat', @x, @x».sqrt, :y-precision(5));</lang>
writefloat('sqrt.dat', @x, @x».sqrt, :y-precision(5));</syntaxhighlight>
{{out}}
{{out}}
<pre>1 1
<pre>1 1
Line 1,479: Line 1,479:


=={{header|Raven}}==
=={{header|Raven}}==
<lang Raven>3 as $xprecision
<syntaxhighlight lang="raven">3 as $xprecision
5 as $yprecision
5 as $yprecision


Line 1,498: Line 1,498:
4 each as $i
4 each as $i
$f $b $i get $a $i get print2
$f $b $i get $a $i get print2
$results "" join "results.dat" write</lang>
$results "" join "results.dat" write</syntaxhighlight>
{{out}}
{{out}}
results.dat file contains:
results.dat file contains:
Line 1,507: Line 1,507:


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/*REXX program writes two arrays to a file with a specified (limited) precision. */
<syntaxhighlight lang="rexx">/*REXX program writes two arrays to a file with a specified (limited) precision. */
numeric digits 1000 /*allow use of a huge number of digits.*/
numeric digits 1000 /*allow use of a huge number of digits.*/
oFID= 'filename' /*name of the output File IDentifier.*/
oFID= 'filename' /*name of the output File IDentifier.*/
Line 1,533: Line 1,533:
z=int || fraction || exponent /*format # (as per rules)*/
z=int || fraction || exponent /*format # (as per rules)*/
if datatype(z,'W') then return format(oz/1,,0) /*is it a whole number ? */
if datatype(z,'W') then return format(oz/1,,0) /*is it a whole number ? */
return format(oz/1,,,3,0) /*3 dec. digs in exponent.*/</lang>
return format(oz/1,,,3,0) /*3 dec. digs in exponent.*/</syntaxhighlight>
'''output''' &nbsp; when using the default (internal) data:
'''output''' &nbsp; when using the default (internal) data:
<pre>
<pre>
Line 1,543: Line 1,543:


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
# Project : Write float arrays to a text file
# Project : Write float arrays to a text file


Line 1,565: Line 1,565:
end
end
fclose(fp)
fclose(fp)
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,579: Line 1,579:
1. Direct writing of the numerical data to the file of an array using function ''writem''. Here the writing format
1. Direct writing of the numerical data to the file of an array using function ''writem''. Here the writing format
is specified using the global property that is accessible through function ''format''.
is specified using the global property that is accessible through function ''format''.
<syntaxhighlight lang="rlab">
<lang RLaB>
>> x = rand(10,1); y = rand(10,1);
>> x = rand(10,1); y = rand(10,1);
>> writem("mytextfile.txt", [x,y]);
>> writem("mytextfile.txt", [x,y]);
</syntaxhighlight>
</lang>


2. Converting the numerical data to text, and then writing the text to the file, using the same function ''writem''.
2. Converting the numerical data to text, and then writing the text to the file, using the same function ''writem''.
Here, the writing format is specified through ''text'' function, and the result is written as a plain string matrix.
Here, the writing format is specified through ''text'' function, and the result is written as a plain string matrix.
<syntaxhighlight lang="rlab">
<lang RLaB>
>> x = rand(10,1); y = rand(10,1);
>> x = rand(10,1); y = rand(10,1);
>> s = text( [x,y], "%10.8f" );
>> s = text( [x,y], "%10.8f" );
>> writem("mytextfile.txt", s);
>> writem("mytextfile.txt", s);
</syntaxhighlight>
</lang>


Please note, ''writem'' function in RLaB can operate in two-fold fashion. RLaB keeps track of the open files that were created using the built-in function ''open''.
Please note, ''writem'' function in RLaB can operate in two-fold fashion. RLaB keeps track of the open files that were created using the built-in function ''open''.
Line 1,599: Line 1,599:


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby># prepare test data
<syntaxhighlight lang="ruby"># prepare test data
x = [1, 2, 3, 1e11]
x = [1, 2, 3, 1e11]
y = x.collect { |xx| Math.sqrt xx }
y = x.collect { |xx| Math.sqrt xx }
Line 1,611: Line 1,611:


# print the result file
# print the result file
open('sqrt.dat', 'r') { |f| puts f.read }</lang>
open('sqrt.dat', 'r') { |f| puts f.read }</syntaxhighlight>
Result:
Result:
<pre>1 1
<pre>1 1
Line 1,619: Line 1,619:


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>x$ = "1, 2, 3, 1e11"
<syntaxhighlight lang="runbasic">x$ = "1, 2, 3, 1e11"
y$ = "1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791"
y$ = "1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791"


Line 1,626: Line 1,626:
print #f, using("##############.###",val(word$(x$,i,",")));"|";using("#######.#####",val(word$(y$,i,",")))
print #f, using("##############.###",val(word$(x$,i,",")));"|";using("#######.#####",val(word$(y$,i,",")))
next i
next i
close #f</lang>
close #f</syntaxhighlight>
{{out}}
{{out}}
<pre> 1.000| 1.00000
<pre> 1.000| 1.00000
Line 1,634: Line 1,634:


=={{header|SAS}}==
=={{header|SAS}}==
<lang sas>data _null_;
<syntaxhighlight lang="sas">data _null_;
input x y;
input x y;
file "output.txt";
file "output.txt";
Line 1,644: Line 1,644:
1e11 316227.76601683791
1e11 316227.76601683791
;
;
run;</lang>
run;</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}<lang scala>import java.io.{File, FileWriter, IOException}
{{libheader|Scala}}<syntaxhighlight lang="scala">import java.io.{File, FileWriter, IOException}


object FloatArray extends App {
object FloatArray extends App {
Line 1,664: Line 1,664:
case e: IOException => println(s"Running Example failed: ${e.getMessage}")
case e: IOException => println(s"Running Example failed: ${e.getMessage}")
}
}
}</lang>
}</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
The library [http://seed7.sourceforge.net/libraries/math.htm math.s7i] defines the function [http://seed7.sourceforge.net/libraries/math.htm#sqrt%28ref_float%29 sqrt]. The operators [http://seed7.sourceforge.net/libraries/float.htm#%28ref_float%29sci%28ref_integer%29 sci] and [http://seed7.sourceforge.net/libraries/float.htm#%28in_string%29exp%28in_integer%29 exp] (defined in [http://seed7.sourceforge.net/libraries/float.htm float.s7i]) support writing floating point numbers in scientific notation.<lang seed7>$ include "seed7_05.s7i";
The library [http://seed7.sourceforge.net/libraries/math.htm math.s7i] defines the function [http://seed7.sourceforge.net/libraries/math.htm#sqrt%28ref_float%29 sqrt]. The operators [http://seed7.sourceforge.net/libraries/float.htm#%28ref_float%29sci%28ref_integer%29 sci] and [http://seed7.sourceforge.net/libraries/float.htm#%28in_string%29exp%28in_integer%29 exp] (defined in [http://seed7.sourceforge.net/libraries/float.htm float.s7i]) support writing floating point numbers in scientific notation.<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
include "float.s7i";
include "math.s7i";
include "math.s7i";
Line 1,682: Line 1,682:
end for;
end for;
close(aFile);
close(aFile);
end func;</lang>{{out|Result file ''filename''}}
end func;</syntaxhighlight>{{out|Result file ''filename''}}
1.000e+00 1.00000e+00
1.000e+00 1.00000e+00
2.000e+00 1.41421e+00
2.000e+00 1.41421e+00
Line 1,690: Line 1,690:
=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Raku}}
{{trans|Raku}}
<lang ruby>func writedat(filename, x, y, x_precision=3, y_precision=5) {
<syntaxhighlight lang="ruby">func writedat(filename, x, y, x_precision=3, y_precision=5) {
var fh = File(filename).open_w
var fh = File(filename).open_w
 
 
Line 1,703: Line 1,703:
var y = x.map{.sqrt}
var y = x.map{.sqrt}
 
 
writedat('sqrt.dat', x, y)</lang>
writedat('sqrt.dat', x, y)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,713: Line 1,713:
=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
{{works with | Smalltalk/X}}
{{works with | Smalltalk/X}}
<lang smalltalk>x := #( 1 2 3 1e11 ).
<syntaxhighlight lang="smalltalk">x := #( 1 2 3 1e11 ).
y := x collect:#sqrt.
y := x collect:#sqrt.
xprecision := 3.
xprecision := 3.
Line 1,722: Line 1,722:
'%.*g\t%.*g\n' printf:{ xprecision . xI . yprecision . yI } on:fileStream
'%.*g\t%.*g\n' printf:{ xprecision . xI . yprecision . yI } on:fileStream
]
]
]</lang>
]</syntaxhighlight>
obviously, with fix precisions, the following printing expression is more readable:
obviously, with fix precisions, the following printing expression is more readable:
<lang smalltalk>'%.3g\t%.5g\n' printf:{ xI . yI } on:fileStream</lang>
<syntaxhighlight lang="smalltalk">'%.3g\t%.5g\n' printf:{ xI . yI } on:fileStream</syntaxhighlight>


=={{header|SPL}}==
=={{header|SPL}}==
<lang spl>x = [1, 2, 3, 10^11]
<syntaxhighlight lang="spl">x = [1, 2, 3, 10^11]
y = [1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791]
y = [1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791]
xprecision = 3
xprecision = 3
Line 1,735: Line 1,735:
s2 = #.str(y[i],"g"+yprecision)
s2 = #.str(y[i],"g"+yprecision)
#.writeline("file.txt",s1+#.tab+s2)
#.writeline("file.txt",s1+#.tab+s2)
<</lang>
<</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>fun writeDat (filename, x, y, xprec, yprec) = let
<syntaxhighlight lang="sml">fun writeDat (filename, x, y, xprec, yprec) = let
val os = TextIO.openOut filename
val os = TextIO.openOut filename
fun write_line (a, b) =
fun write_line (a, b) =
Line 1,746: Line 1,746:
ListPair.appEq write_line (x, y);
ListPair.appEq write_line (x, y);
TextIO.closeOut os
TextIO.closeOut os
end;</lang>
end;</syntaxhighlight>
Example usage
Example usage
- val x = [1.0, 2.0, 3.0, 1e11];
- val x = [1.0, 2.0, 3.0, 1e11];
Line 1,765: Line 1,765:
=={{header|Stata}}==
=={{header|Stata}}==


<lang stata>* Create the dataset
<syntaxhighlight lang="stata">* Create the dataset
clear
clear
mat x=1\2\3\1e11
mat x=1\2\3\1e11
Line 1,775: Line 1,775:


* Save as text file
* Save as text file
export delim file.txt, delim(" ") novar datafmt replace</lang>
export delim file.txt, delim(" ") novar datafmt replace</syntaxhighlight>


{{out}}
{{out}}
Line 1,785: Line 1,785:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>set x {1 2 3 1e11}
<syntaxhighlight lang="tcl">set x {1 2 3 1e11}
foreach a $x {lappend y [expr {sqrt($a)}]}
foreach a $x {lappend y [expr {sqrt($a)}]}
set fh [open sqrt.dat w]
set fh [open sqrt.dat w]
Line 1,795: Line 1,795:
set fh [open sqrt.dat]
set fh [open sqrt.dat]
puts [read $fh [file size sqrt.dat]]
puts [read $fh [file size sqrt.dat]]
close $fh</lang>
close $fh</syntaxhighlight>
{{out}}
{{out}}
<pre>1 1
<pre>1 1
Line 1,803: Line 1,803:


=={{header|VBA}}==
=={{header|VBA}}==
<lang vb>Public Sub main()
<syntaxhighlight lang="vb">Public Sub main()
x = [{1, 2, 3, 1e11}]
x = [{1, 2, 3, 1e11}]
y = [{1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}]
y = [{1, 1.4142135623730951, 1.7320508075688772, 316227.76601683791}]
Line 1,813: Line 1,813:
Next i
Next i
Close TextFile
Close TextFile
End Sub</lang>{{out}}
End Sub</syntaxhighlight>{{out}}
<pre>1,000E000 1,00000E000
<pre>1,000E000 1,00000E000
2,000E000 1,41421E000
2,000E000 1,41421E000
Line 1,822: Line 1,822:
=={{header|Vlang}}==
=={{header|Vlang}}==
{{incomplete|Vlang|Formatting at least currently doesn't allow variables, floating point notation `g` seems to have bugs}}
{{incomplete|Vlang|Formatting at least currently doesn't allow variables, floating point notation `g` seems to have bugs}}
<lang>import os
<syntaxhighlight lang="text">import os
const (
const (
x = [1.0, 2, 3, 1e11]
x = [1.0, 2, 3, 1e11]
Line 1,843: Line 1,843:
f.write_string('${x[i]:3}, ${y[i]:1G}\n')?
f.write_string('${x[i]:3}, ${y[i]:1G}\n')?
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre> 1, 1
<pre> 1, 1
Line 1,856: Line 1,856:


In the final example, we need to force exponential format as numbers of this size would normally be printed in decimal format.
In the final example, we need to force exponential format as numbers of this size would normally be printed in decimal format.
<lang ecmascript>import "io" for File
<syntaxhighlight lang="ecmascript">import "io" for File
import "/fmt" for Fmt
import "/fmt" for Fmt


Line 1,869: Line 1,869:
file.writeBytes(s)
file.writeBytes(s)
}
}
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 1,881: Line 1,881:


=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang Yabasic>x$ = "1 2 3 1e11"
<syntaxhighlight lang="yabasic">x$ = "1 2 3 1e11"
pr1 = 3 : pr2 = 5
pr1 = 3 : pr2 = 5


Line 1,893: Line 1,893:
next i
next i


close #f</lang>
close #f</syntaxhighlight>


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>fcn writeFloatArraysToFile(filename, xs,xprecision, ys,yprecision){
<syntaxhighlight lang="zkl">fcn writeFloatArraysToFile(filename, xs,xprecision, ys,yprecision){
f :=File(filename,"w");
f :=File(filename,"w");
fmt:="%%.%dg\t%%.%dg".fmt(xprecision,yprecision).fmt; // "%.3g\t%.5g".fmt
fmt:="%%.%dg\t%%.%dg".fmt(xprecision,yprecision).fmt; // "%.3g\t%.5g".fmt
Line 1,905: Line 1,905:
xs,ys := T(1.0, 2.0, 3.0, 1e11), xs.apply("sqrt");
xs,ys := T(1.0, 2.0, 3.0, 1e11), xs.apply("sqrt");
xprecision,yprecision := 3,5;
xprecision,yprecision := 3,5;
writeFloatArraysToFile("floatArray.txt", xs,xprecision, ys,yprecision);</lang>
writeFloatArraysToFile("floatArray.txt", xs,xprecision, ys,yprecision);</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,922: Line 1,922:
Here we write the contents of the array g() to a file:
Here we write the contents of the array g() to a file:


<lang zxbasic>SAVE "myarray" DATA g()</lang>
<syntaxhighlight lang="zxbasic">SAVE "myarray" DATA g()</syntaxhighlight>