15.   Output and Input

2014-06-13

$Version

Clear[a,b,c,x]

15.1  Printing Data and Expressions

Print[expr1,expr2,...]		print the  expri with no spaces 						inbetween, but with a newline at the end. 
					The output of Print[] is not a string

Print[a,b]; Print[c]

Do[Print[i, "  ", i^2], {i, 5}]

Print[TableForm[{{11, 2}, {3.141, 444}}]]

Print[MatrixForm[{{11, 2}, {3.141, -444}}]]

Print[Column[{11,3.141,444}]]

Print[Column[{11,3.141,444},Left]]

Print[Column[{11,3.141,444},Center]]

Print[Column[{11,3.141,444},Right]]

15.1.0	Tables and Matrices

Column[list]		Typeset as a column of elements
	Grid[list]		Typeset as a grid of elements
	TableForm[list]	Print in tabular form

??Grid

Much more information can be found through the link given above.

Grid[{{a,b,c},{x,y,z}}]

Grid[{{a,b,c},{x,y^2,z^3}},Frame->All]

Table[(i+44)^j,{i,3},{j,3}]

TableForm[%]

Grid[%]

Column[Range[1,15,3]]

15.1.1 Formats for  outputs

ColumnForm[list]	Prints the elements of list  one below the other with 			left justification

ColumnForm[list,horiz]		horiz 	specifies the justification.

horiz:  	Left, Center, Right  		are the specifications for the justification

Print[StringForm["x = ``, y = ``", a^2, b^2]]

StringForm["controlstring", exp(Subscript[r, i]) , … ] 	prints as the text  controlstring, 											          with the printed forms of the  exp(Subscript[r, i])   embedded.

Print[Row[{"x = ",(a^2),", y = ",(b^2)}]]

p=Print["Evaluating this won't make p into a string."]

Information["p"]

ou = {6.7^-4, 6.7^6, 6.7^8}

NumberForm[ou]

ScientificForm[ou]

ScientificForm[ou,3]

EngineeringForm[ou]

NumberForm[expr,tot] 		print at most tot digits of all aproximate 					real numbers in  expr
NumberForm[expr,{n,d}]		print at most n  digits with  d  decimal 					digits

ScientificForm[expr,tot]  	use scientific nottation with at most   						tot  digits

EngineeringForm[expr,tot]	use engineering nottation with at most   					tot  digits

pp = N[(π^10),25]

NumberForm[pp,12]

NumberForm[pp, {9,2}]

EngineeringForm[%%,12]

ScientificForm[%%%,5]

NumberForm[N[π^4,20], DigitBlock -> 5]
NumberForm[N[π^4,20], DigitBlock -> 5, NumberSeparator -> " "]

NumberForm[17345652.29876, DigitBlock -> 5]

l1 = {7.99 10^12,5.3, 9.2 * 10^-6,2.44 10^-15};

NumberForm[l1, ExponentFunction -> (If[-10 < # < 10, Null, #]&)]

NumberForm[l1,NumberFormat->(Row[{#1,"E",#3}]&)]

There are additionl options :

??NumberPadding

Default format without padding :

NumberForm[1234567.89,10]

Pad with a tab on the left:

NumberForm[1234567.89,10,NumberPadding->{"\t",""}]

PaddedForm[12345678.9,10,NumberPadding->{"\t",""}]

EngineeringForm[12345678.9,10,NumberPadding->{"\t",""}]

ScientificForm[12345678.9,10,NumberPadding->{"\t",""}]

?SignPadding

The default pads before signs :

NumberForm[{-1.23,2.46},5,NumberPadding->{" "," "}]

Pad between signs and numbers instead:

NumberForm[{-1.23,2.46},5,SignPadding->True,NumberPadding->{" "," "}]

15.1.1.2  Printing Tables with numbers having decimal points

Grid[] has the Option Alignment -> "." effecting alignment w.r.t. the decimal point.
Below an example provided by Robert Nowak.

Table[{x,100 Sin@x}//N//NumberForm[#,{6,3},NumberPadding->{" ","0"}]&/@#&,{x,-π,π-π/8,π/8}]//Prepend[#,{Style["x",Bold],Style["100 Sin x",Bold]}]&//Grid[#,Frame->All,Alignment->Center]&

15.1.2	Output for other programming languages

FortranForm[expr]  	prints  expr  in FORTRAN language

CForm[expr]  		prints  expr  in C  language

TeXForm[expr]  		prints  expr  in TEX language

Clear[a,b,c]

FortranForm[f = a b /c^2]

Column[FortranForm/@l1]

CForm[f = a b /c^2]

TeXForm[f = a b /c^2]

ma = 
{{(1/4) (-2 (Subscript[α, 0])+(Subscript[α, 2])),-((3 (Subscript[α, 2]))/(4 (Sqrt[10])))},{-((3 (Subscript[α, 2]))/(4 (Sqrt[10]))),(1/10) (-5 (Subscript[α, 0])-2 (Subscript[α, 2]))}};
MatrixForm[ma]

This matrix can be tranferred  to a Latex F ile in the following way. Use TeXForm[MatrixForm[]] and copy the output into the LatexFile.

TeXForm[MatrixForm[ma]]

\begin{eqnarray*}
m_a= \left(
\matrix{ \frac{-2\,{{\alpha }_0} + {{\alpha }_2}}{4} &   \frac{-3\,{{\alpha }_2}}{4\,{\sqrt{10}}} \cr     
            \frac{-3\,{{\alpha }_2}}{4\,{\sqrt{10}}} & \frac{-5\,{{\alpha }_0} - 2\,{{\alpha }_2}}{10} \cr  }
 \right)
 \end{eqnarray*}

15.1.3  Traditional Form

Mathematica  outputs polynomials with increasing order of the powers. The ordering of the printout my be changed by the command: TraditionalForm

Clear[t,x]
f = x^3+ 5 x^2 -  2x+ 4

f//TraditionalForm

Derivatives may be written in traditional form:

Clear[f]
f[x_,t_]= ( (x^3)+5 (x^2)-2 x+4)Sin[ω t]

D[f[x,t],x]//TraditionalForm

D[f[x,t],t]//TraditionalForm

Dt[f[x,t],t]//TraditionalForm

HoldForm[D[f[x,t],t]]//TraditionalForm

15.2  Writing into Files

Export["file.ext", expr] 	exports data to a file, converting it to a format 				    corresponding to the file extension ext.

Export["file", expr, "format"] exports data to a file, converting it to the 				        specified format.

As formats one may use: 

({{"Lines", list of strings to be placed on separate lines }, {"List", list of numbers or strings, to be placed on separate lines }, {"Table", list of lists of numbers or strings, to be placed in a two-dimensional array}, {"Text", single string of ordinary characters (.txt)}, {"Words ", list of strings to be separated by spaces }})

A =  {{a1, b1, c1, d1}, {a2, b2, c2, d2}, {a3, b3, c3, d3}}; 
B = Transpose[A];

Export["test1.txt", 
                   Prepend[B, {"Spalte1", "Spalte2", "Spalte3"}],"Table"];

In your main directory you will find the file test1.txt with the following content:

Spalte1	Spalte2	Spalte3
a1	a2	a3
b1	b2	b3
c1	c2	c3
d1	d2	d3

Export["test2.txt",B,"List"];

In your main directory you will find the file test2.txt with the following content:
{a1, a2, a3}
{b1, b2, b3}
{c1, c2, c3}
{d1, d2, d3}

i1 = y[x]';  i2 = Sin[x];

i3 = Hold[(∫_1^2)(x^2)\[DifferentialD]x]  ;

Export["test3.txt",{i1,i2,i3},"Lines"];

In your main directory you will find the file test3.txt with the following content:
Derivative[1][y[x]]
Sin[x]
Hold[Integrate[x^2, {x, 1, 2}]]

zz=RandomReal[{-99,99},{3,5}]

Export["zz.txt",zz, "Text"]

In your main directory you will find the file  zz.txt with the content  zz  as given above but with more decimal places.

Export["zzt.txt",zz, "Table"]

In your main directory you will find the file  zzt.txt with the following content   zz  as given above but with more decimal places.

zzs=(({{-40.26066849685475`, -97.16586911187056`, -95.38992712488499`, 78.01086305551189`, 26.209569354568146`}, {98.24543561601837`, -38.442614834196036`, -69.85730459204922`, 26.28483009122988`, 0.6726973742467521`}, {-56.24646417038906`, -67.59242501805886`, -63.07203919468884`, 89.04416998904975`, 30.49052856339341`}}))

FullForm[zzs]

Export["zzs.txt",zzs]

The file  zss.txt in the main director contains three lines as:

{-40.26066849685475, -97.16586911187056, -95.38992712488499, 78.01086305551189, 26.209569354568146}
{98.24543561601837, -38.442614834196036, -69.85730459204922, 26.28483009122988, 0.6726973742467521}
{-56.24646417038906, -67.59242501805886, -63.07203919468884, 89.04416998904975, 30.49052856339341}

15.2.1  Exporting pictures

The most convenient way to include pictures or drawings into a LateX document is to use pdf LateX and to store the 
pictures as pdf-files.  One way is to export the pictures as pdf-files.

??BaseStyle

plo=Plot[{Sin[x],Sin[2 x]},{x,0,2 π},Ticks->{{{π/2,"(π/2)"},{π,"π"},{3π/2,"((3  π)/2)"},{2π,"2π"}},0.5` Range[-2,2]},AxesLabel->{"x","y"},PlotStyle->{Hue[0],Hue[0.6`]}, BaseStyle -> {FontSize -> 16}]

Export["pic.pdf",plo]

The file pic.pdf is stored in the main directory of the user.

In Mathematica on a MacIntosh one may also mark the figure in the notebook, use the command "print selection" and then the selection PDF;
this leads to a menue, where one chooses "Save as PDF"; then one may select the directory, where the file should be stored.

A selection of graphics formats is:
Raster Image Formats:		"GIF",	"JPEG",  "TIFF", "JPG", ....
Vector Graphics Formats:	"EPS", "PDF", "WMF", ...
Tabular and Spreadsheet Formats: "Table", "XLS", ....
Document Formats:		"PDF", "EPS", "TEX", "Text", ...
Print Formats:			"PDF", "EPS", "TEX", ...
Web Formats:			"HTML", "XHTML", "GIF", "JPEG", ...
Compression and Archive Formats:  "ZIP", "GZIP", "TAR", ....
Binary Formats:		"Bit", "Byte", ......

15.3  Reading Files

Import["name.ext"]   imports data from a file assuming that it is in the format indicated by 
		   		the file extension ext, and converts it to a Mathematica expression.
 Import["file", "format"]		imports data in the specified format from a file.

Formats are the same as for  Export[] .

i1 = Import["test1.txt"]

i1 = Import["test1.txt","Table"]

FullForm[i1]

Drop[Drop[i1,1],-1]//MatrixForm

Det[%]

FullForm[%]

This shows that the elements of the above list are not expressions; they are strings,
which may be transformed to expressions by the command ToExpression[ ] .The commands involving Map are explained in Chap.21.

FullForm[i2]

i3= MapAll[ToExpression,Drop[i1,1]]

FullForm[%]

i2 = Import["test1.txt","Words"]

i2 = Import["test2.txt","Lines"]

MatrixForm[i2]

FullForm[i2]

i2e = MapAll[ToExpression, i2]

FullForm[i2e]

MatrixForm[i2e]

Import["pic.pdf"]

15.4  Free-Form Linguistic Input

Beginning with Mathematica 8 it is possible to give Mathematica commands
in linguistic form. This is explained with a number of examples.
Before starting the examples given below you must activate the input surface by 
clicking at the button “activated dynamics” !

(== at beginning of input) — use free-form linguistics to generate Mathematica output

(Ctrl+==) — enter free-form linguistics for conversion to inline Mathematica input

15.4.1  Basic Input

15.5  Locating Files

Up to now we did not care in which directory files sare stored or to which directory they are saved. Below
this point is treated in different subscections for PC's running under UNIX (including Macintosh computrrs)
 or Windows computers.

15.5.1	UNIX Computers

On my home computer where I installed Mathematica 9  my user ID is Bernhard.

$Path

This shows the directories and subdirectories where the files are saved on  a  PC under Unix. This output indicates
how to the define the path for your file in your computer. 
One way is to type the complete  path as e.g.:

Export["/Users/Bernhard/test15.txt",{{2.5, 5, 8.}, {3., 4, 7.}},"Table"]

The subdirectory selected above now contains  the  file test15.txt.

ip = Import["/Users/Bernhard/test15.txt"]

ipp = ReadList["/Users/Bernhard/test15.txt",{Number, Number, Number}]

SetDirectory["/Users/schnizer"]

Export["testsch.txt",{{x1, x2, x3}, {y1, y2, y3}},"Table"]

The filepath may also be selected by choosing "FilePath" in the menue  "Insert".

15.5.2 Windows

The examples below are rather old. So present-day Windows may give a somewhat different picture.
Unfortunately,  I have no facility to make tests. When you are using Mathematica under windows
you should run the commands given below to see how they are working.

$Path

The directories listed above are used to store files under Windows. Under Windows the file path must be specified according to rules 
differing from those used by the Unix (including Macintosh computers):

"L:\\symb_rech\\schnizer\\iowin.nb"

Note that the backslash must be typed twice. Following this rule, the export command looks as follows:

Export["schnizer\\test15.txt", {{2.5,5,8},{3,4,7}},"Table"]

"schnizer\\test15.txt"

To avoid the typing of the file path, you can use the point "Get File Path..." in the menu "Input". A directory where files should be saved by default is selected by following command:

Export["test2.txt",{{x1,x2,x3},{y1,y2,y3}},"Table"]

15.6 Accuracy and Precision

??Accuracy

??Precision

Accuracy[x]   	gives the effective number of digits to the right of the 			decimal point in the number x.
Precision[x]	gives the effective number of digits of precision in the 			number  x.

Accuracy gives Infinity when applied to exact numbers,such as integers.
Accuracy assumes a precision of $MachinePrecision when applied to machine-precision numbers.

Map[Accuracy,{123,(123/2),(Sqrt[123]),π,E,I}]

The Accuracy of a machine real number depends on the value of $MachinePrecision on your computer.

$MachinePrecision

Map[Accuracy,{1.618034,21.618034,321.618034}]

Map[Precision,{1.618034,21.618034,321.618034}]

However, the Accuracy of arbitrary-precision real numbers is machine-independent.

Map[Accuracy,{1.12345678901234567890123456789,21.12345678901234567890123456789,321.12345678901234567890123456789}]

Map[Precision,{1.12345678901234567890123456789,21.12345678901234567890123456789,321.12345678901234567890123456789}]

Accuracy  can yield zero  or a negative result:

Map[Accuracy,{23451234567834987678.}]

Here is an approximate real number.

xp=234.389879479373987397;

This gives the total number of digits entered to specify the real number.

Precision[xp]

This evaluates (π^25) using numbers with 30 digits of precision.

N[(Pi^25),30]

The result has 30 digits of precision.

Precision[%]

Mathematica treats 3.0 as a machine-precision number.

Precision[3.]

$MachinePrecision

Giving anything less than $MachinePrecision digits yields a machine-precision number.

Precision[3.]

This evaluates Γ[(1/7)] using 30-digit precision numbers.

N[Gamma[(1/7)],30]

In this case, the result has a precision of exactly 30 digits.

Precision[%]

If you give input only to a few digits of precision, Mathematica cannot give you high-precision output.

N[Gamma[0.142],30]

Precision[%]

If you want Mathematica to assume that 0.142 is exact, then you have to show this explicitly.

N[Gamma[(142/1000)],30]

Precision[%]

({{SetPrecision[expr,n]    , create a number with  n   decimal digits of precision,   padding with binary  zeros  if necessary}})

SetAccuracy[expr, n]	yields a version of  expr  in which all numbers have been  set to have accuracy  n

$MinPrecision

$MaxPrecision

lst=RandomReal[{0,1},10]

lplst=SetPrecision[#,20]&/@lst

This creates a number with a precision of 50 decimal digits. The extra digits come from conversion to base 10.

SetPrecision[0.300000000000000, 40]

x = SetPrecision[0.3000000000000000000000000000000000000000, 40]

x^2

Accuracy[%]

Precision[%%]

By making the global assignment $MinPrecision = n, you can effectively apply SetPrecision[expr, n] at every step in a computation.This means that even when the number of correct digits in an arbitrary-precision number drops below n, the number will always be padded to have n digits. If you set $MaxPrecision = n as well as $MinPrecision = n, then you can force all arbitrary-precision numbers to have a fixed precision of n digits.In effect,what this does is to makeMathematica treat arbitrary-precision numbers in much the same way as it treats machine numbers—but with more digits of precision. Fixed-precision computation can make some calculations more efficient, but without careful analysis you can never be sure how many digits are correct in the results you get.

Here is a small number with 20-digit precision.

k = N[Exp[-60], 20]

With Mathematica's usual arithmetic, this works fine.

k1 = Evaluate[1 + k] - 1

This tells Mathematica to use fixed-precision arithmetic.

$MinPrecision = $MaxPrecision = 20

k2 = Evaluate[1 + k] - 1

k1 - k2

$MinPrecision = $MaxPrecision = 40

k = N[Exp[-60], 40]

k3 = Evaluate[1 + k] - 1

k1 - k3

$MinPrecision = $MaxPrecision = 50

xn = SetPrecision[0.30000000000000000000000000000000000000000000000000, 50]

Precision[%]

xn^2

Accuracy[%]

Precision[%%]