89
Mathematica as a Calculator You can use Mathematica just like a calculator: you type in questions, and Mathematica prints back answers. Here is a simple computation. Press to tell Mathematica to evaluate the input you have given. 6^20 3656158440062976 Mathematica automatically handles numbers of any size. 6^200 42682522381202740079697489151877373234298874535448942949547907893511292954961973901907213934075709729681281546667612983095446524051759524238401 5591919845376 You can enter computations in standard mathematical notation, using palettes or from the keyboard. How this works is discussed below. 6 200 42682522381202740079697489151877373234298874535448942949547907893511292954961973901907213934075709729681281546667612983095446524051759524238401 5591919845376 This tells Mathematica to work out the eigenvalues of a matrix. Eigenvalues 1 2 3 4 5 6 7 8 9 0, 3 2 5 33 , 3 2 5 33

Mathematica as a Calculator

Embed Size (px)

DESCRIPTION

These are the examples from mathematica.

Citation preview

Page 1: Mathematica as a Calculator

Mathematica as a Calculator

You can use Mathematica just like a calculator: you type in questions, and Mathematica prints back answers.

Here is a simple computation. Press to tell Mathematica to evaluate the input you have given.

6^20

3656158440062976

Mathematica automatically handles numbers of any size.

6^200

42682522381202740079697489151877373234298874535448942949547907893511292954961973901907213934075709729681281546667612983095446524051759524238401

5591919845376

You can enter computations in standard mathematical notation, using palettes or from the keyboard. How this works is discussed below.

6200

42682522381202740079697489151877373234298874535448942949547907893511292954961973901907213934075709729681281546667612983095446524051759524238401

5591919845376

This tells Mathematica to work out the eigenvalues of a matrix.

Eigenvalues1 2 34 5 67 8 9

0, 3

25 33, 3

25 33

Page 2: Mathematica as a Calculator

An important feature of Mathematica is its ability to handle formulas as well as numbers.

This asks Mathematica to solve an equation. The answer is a formula that depends on a parameter.

Solvex a 2x, xx 1

81 4a 1 8a,x 1

81 4a 1 8a

This asks Mathematica to evaluate an integral.xa xxa xax4 x322

1

4a2Logx a x

You can use Mathematica to make 2D and 3D graphics.

Here is a 2D plot of a simple function.

PlotSinx Sin1.6x,x, 0, 40

Graphics

Page 3: Mathematica as a Calculator

Here is a 3D plot. The space between the x and y indicates multiplication. PlotPoints30 specifies the mesh to use.

Plot3DSinxy,x, 0, 4,y, 0, 4, PlotPoints 30

SurfaceGraphics

You can access many of the calculator features of Mathematica just by pushing buttons in standard palettes. Click this hyperlink to check out the Basic Calculations palette.

Power Computing with Mathematica

Even though you can use it as easily as a calculator, Mathematica gives you access to immense computational power.

This creates a 100×100 matrix of random numbers. The semicolon at the end tells Mathematica not to print the matrix.

m TableRandom,100,100;

Page 4: Mathematica as a Calculator

On most computers it takes Mathematica under a second to compute all the eigenvalues of the matrix and plot them.

ListPlotAbsEigenvaluesm

Graphics

Page 5: Mathematica as a Calculator

Mathematica can handle numbers of any size. On most computers Mathematica takes under a second to compute the exact factorial of

1000.

1000

40238726007709377354370243392300398571937486421071463254379991042993851239862902059204420848696940480047998861019719605863166687299480855890132

3829669944590997424504087073759918823627727188732519779505950995276120874975462497043601418278094646496291056393887437886487337119181045825783

6478499770124766328898359557354325131853239584630755574091142624174743493475534286465766116677973966688202912073791438537195882498081268678383

7455973174613608537953452422158659320192809087829730843139284440328123155861103697680135730421616874760967587134831202547858932076716913244842

6236131412508780208000261683151027341827977704784635868170164365024153691398281264810213092761244896359928705114964975419909342221566832572080

8213331861168115536158365469840467089756029009505376164758477284218896796462449451607653534081989013854424879849599533191017233555566021394503

9973628075013783761530712776192684903435262520001588853514733161170210396817592151090778801939317811419454525722386554146106289218796022383897

1476088506276862967146674697562911234082439208160153780889893964518263243671616762179168909779911903754031274622289988005195444414282012187361

7459926429565817466283029555702990243241531816172104658320367869061172601587835207515162842255402651704833042261439742869330616908979684825901

2545832716822645806652676995865268227280707578139185817888965220816434834482599326604336766017699961283186078838615027946595513115655203609398

8180612138558600301435694527224206344631797460594682573103790084024432438465657245014402821885252470935190620929023136493273497565513958720559

6542287497740114133469627154228458623773875382304838656889764619273838149001407673104466402598994902222217659043399018860185665264850617997023

5619389701786004081188972991831102117122984590164192106888438712185564612496079872290851929681937238864261483965738229112312502418664935314397

0137428531926649875337218940694281434118520158014123344828015051399694290153483077644569099073152433278288269864602789864321139083506217095002

5973898635542771967428222487575867657523442202075736305694988250879689281627538488633969099598262809561214509948717012445164612603790293091208

8908694202851064018215439945715680594187274899809425474217358240106367740459574178516082923013535808184009699637252423056085590370062427124341

6909004153690105933983835777939410970027753472000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

00000000000

Page 6: Mathematica as a Calculator

Mathematica can do numerical computations to any precision you specify. Here is pi to 500 digits of precision.

N, 5003.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725

3594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133

9360726024914127372458700660631558817488152092096282925409171536436789259036001133053054882046652138414695194151160943305727036575959195309218

61173819326117931051185480744623799627495673518857527248912279381830119491

Mathematica routinely handles algebraic calculations that would have taken years by hand. Here is a polynomial factoring problem.

Factorx99 y99x yx2 xy y2x6 x3y3 y6x10 x9y x8y2 x7y3 x6 y4 x5y5 x4 y6 x3 y7 x2y8 xy9 y10x20 x19y x17y3 x16 y4 x14 y6 x13y7 x11 y9 x10y10 x9y11 x7 y13 x6y14 x4 y16 x3 y17 xy19 y20x60 x57y3 x51 y9 x48y12 x42y18 x39 y21 x33y27 x30 y30 x27 y33 x21y39 x18 y42 x12y48 x9y51 x3 y57 y60Mathematica calls on sophisticated algorithms to simplify formulas. The % symbol stands for the previous result.

Simplify%x99 y99

Mathematica has achieved world records—for both size and speed—in many kinds of computations.

Here is a computation in number theory; larger versions of this computation, which took Mathematica only a few minutes, had never been done before.

PartitionsP800078360264351568349490593145013364599719010769352985864331118600209417827764524450990388402844164

Page 7: Mathematica as a Calculator

Accessing Algorithms in Mathematica

Whenever you use Mathematica, you are accessing the world's largest collection of computational algorithms.

Mathematica automatically chooses appropriate algorithms for each computation.

FindRootCosx x Logx,x, 1x 0.840619NIntegrateLogx Sinx,x, 0, 20.555889

NSolvex^5 6x^3 8x 1 0, xx 2.05411,x 1.2915,x 0.126515,x 1.55053,x 1.9216Mathematica uses state-of-the-art algorithms for factoring integers. The result is given as a list of factors and exponents.

FactorInteger2^105 17, 2,31, 1,71, 1,127, 1,151, 1,337, 1,29191, 1,106681, 1,122921, 1,152041, 1This generates a 2D table corresponding to a matrix.

m Table2^i x^j,i, 3,j, 42 x, 2 x2, 2 x3, 2 x4,4 x, 4 x2, 4 x3, 4 x4,8 x, 8 x2, 8 x3, 8 x4

Page 8: Mathematica as a Calculator

This displays the table in matrix form.

MatrixFormm2 x 2 x2 2 x3 2 x4

4 x 4 x2 4 x3 4 x4

8 x 8 x2 8 x3 8 x4

This computes the null space of the matrix.

NullSpacemx x2, 1 x x2, 0, 1,x, 1 x, 1, 0Mathematica can solve differential equations both symbolically and numerically.

Here Mathematica solves a nonlinear differential equation numerically. The answer is an interpolating function that implicitly represents the whole solution.

NDSolvex''t xt3 Sint, x0 x'0 0,x,t, 0, 50x InterpolatingFunction0., 50.,

Here is a parametric plot of the solution. The /. tells Mathematica to substitute the solution for x.

ParametricPlotEvaluatext, x't.%,t, 0, 50

Graphics

Page 9: Mathematica as a Calculator

Mathematical Knowledge in Mathematica

Mathematica incorporates the knowledge from the world's mathematical handbooks — and uses its own revolutionary algorithms to go much further.

Mathematica knows about all the hundreds of special functions in pure and applied mathematics.

LegendreQ3, x2

35x2

23

4x1 5x2

3

Log1 x1 x

Mathematica can evaluate special functions with any parameters to any precision.

NMathieuC1 I, 2I, 3, 403.925131137412519864349764616815837920363 1.898823911543347241105274797143911577679I

Mathematica is now able to do vastly more integrals than were ever before possible for either humans or computers.x ArcTanxx4x3

1

32 ArcTan2 2x2 1

32 ArcTan2 2x2 2

3x32ArcTanx Log1 2x x

32 Log1 2x x

320

LogxExpx3x

1

54Gamma1

36EulerGamma 3 9Log3

0

Sinx2Expxx

1

22 Cos142 HypergeometricPFQ1,3

4,5

4,

1

64 Sin1

4

Page 10: Mathematica as a Calculator

Mathematica can also evaluate finite and infinite sums and products.k1

n 1k6

6

945

1

120PolyGamma5, 1 n

Look at the Integrals demo to see more examples.

Mathematica can solve a wide range of ordinary and partial differential equations.

DSolvey''x y'x xyx 0, yx, xyx Ex2AiryBi113 1

4 xC1 AiryAi113 1

4 xC2

Mathematica's algorithms can generate a huge range of mathematical results.

FullSimplifyn1

5Gamma2n

5

12 2

255Log2 Zeta32True

TrigReduceCosx41

83 4Cos2x Cos4x

This finds the billionth prime number, using a mixture of algorithms and built-in tables.

Prime10922801763489

Page 11: Mathematica as a Calculator

Building Up Computations

Being able to work with formulas lets you easily integrate all the parts of a computation.

Here are the eigenvalues of a matrix of numbers.

Eigenvalues3, 1,2, 6129 17, 1

29 17

Mathematica can still compute the eigenvalues even when symbolic parameters are introduced. The following expression is a compact representation of the eigenvalues for any

value of b.

v Eigenvalues3, 1,2, b123 b 17 6b b2, 1

23 b 17 6b b2

Mathematica's functions are carefully designed so that output from one can easily be used as input to others.

This takes the formula for the eigenvalues and immediately plots it.

PlotEvaluatev,b, 10, 10

Graphics

Page 12: Mathematica as a Calculator

You can solve for the value of b at which the first eigenvalue is zero...

SolveFirstv 0, bb 2

3

or find the integral from 0 to c.

int0

cFirstvb

317

4 2ArcSinh3

22 1

4

c2 317 6c c2 c6 17 6c c2 8ArcSinh3 c22This finds the series expansion of the result.

Series%,c, 0, 51

46 217c 1

4

1 317c2 2c3

5117 3c4

57817 14c5

2456517 Oc6This searches numerically for a root.

FindRootint 1 c,c, 1c 0.554408Being able to work with formulas is also important in summarizing data.

This generates a table of the first 40 primes.

TablePrimei,i, 402, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,

73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173

Page 13: Mathematica as a Calculator

Fit produces an approximate formula.

Fit%,Logx, x, x2, x3.91288x 0.0244903x2 5.98809LogxThis computes the sum of the first 40 primes using the approximate formula.

Sum%,x, 1, 403090.16

Here is the exact result.

SumPrimei,i, 1, 403087

The plot puts everything together and makes a plot of the difference between exact and approximate results for sums of up to 50 primes.

ListPlotTableSumEvaluateFitTablePrimei,i, imax,Logx, x, x2, x,x, imaxi1

imaxPrimei,imax, 2, 50,

PlotJoined True

Graphics

Page 14: Mathematica as a Calculator

Handling Data

Mathematica lets you import data in any format, then manipulate it using powerful and flexible functions.

Click here to change to the directory that contains the data files used in this section.

This reads image data from the file image.dat. The semicolon tells Mathematica not to print the result.

data ReadList"image.dat", Number, RecordLists True;This visualizes the data as a density plot.

ListDensityPlotdata, Mesh False, FrameTicks None

DensityGraphics

Page 15: Mathematica as a Calculator

You can apply any Mathematica function to the data.

ListDensityPlotExpSqrtdata, Mesh False, FrameTicks None, ColorFunction Hue

DensityGraphics

Here the data is successively shifted to the right.

ListDensityPlotMapIndexedRotateRight, data, Mesh False, FrameTicks None, ColorFunction Hue

DensityGraphics

Page 16: Mathematica as a Calculator

Here is a contour plot of the data.

ListContourPlotdata, ContourShading False, Contours 6, FrameTicks None

ContourGraphics

This plots the data keeping only some Fourier components.

ListDensityPlotReInverseFourierMapIndexedIfMax#2 60, #, 0&, Fourierdata,2, Mesh False, FrameTicks None

DensityGraphics

Page 17: Mathematica as a Calculator

This is the distribution of gray levels in the data.

ListPlotSortFlattendata

2000 4000 6000 8000

50

100

150

200

Graphics

Here is a 3D plot based on the data.

ListPlot3Ddata, ColorFunction Hue,

Mesh False, ViewPoint 0.2, 2, 5

20 40 60 80 100

20

40

60

80

050

100150200

20 40 60 80 100

20

40

60

80

SurfaceGraphics

Page 18: Mathematica as a Calculator

Mathematica can work with data of any kind — not just numbers.

Click here to change to the directory that contains the data files used in this section.

This reads in all the words in a dictionary.

data ReadList"dictionary.dat", String;Here are the first 40 words in the dictionary.

Takedata, 40a, AAA, AAAS, Aarhus, Aaron, ABA, Ababa, aback, abacus, abalone, abandon, abase, abash, abate,

abbas, abbe, abbey, abbot, Abbott, abbreviate, abc, abdicate, abdomen, abdominal, abduct, Abe, abed, Abel,

Abelian, Abelson, Aberdeen, Abernathy, aberrant, aberrate, abet, abetted, abetting, abeyance, abeyant, abhorredThis selects words that are palindromes with length more than 2.

Selectdata,# StringReverse#&& StringLength# 2&AAA, ABA, ala, AMA, ana, bib, bob, bub, CDC, civic, dad, deed, did, DOD, dud, eke, ere, eve, ewe, eye, gag, gig, gog, huh, iii, level, madam, minim, mum,

non, noon, nun, pap, PDP, peep, pep, pip, poop, pop, pup, radar, refer, rever, rotor, sis, s's, tat, teet, tenet, tit, TNT, toot, tot, wowThis finds the lengths of all the words in the dictionary.

wordLengths MapStringLength, data;This counts the total number of words of each length.

TableCountwordLengths, i,i, MaxwordLengths26, 131, 775, 2152, 3093, 3793, 3929, 3484, 2969, 1883, 1052, 542, 260, 102, 39, 15, 6, 4, 0, 1, 2, 1

Page 19: Mathematica as a Calculator

Here is a plot of the length distribution.

ListPlot%, PlotStyle PointSize0.02

5 10 15 20

1000

2000

3000

4000

Graphics

Page 20: Mathematica as a Calculator

Visualization with Mathematica

Mathematica makes it easy to create stunning visual images.

This creates a 3D parametric plot with automatic choices for most options.

ParametricPlot3DuCosu4 Cosv u, uSinu4 Cosv u, uSinv u,u, 0, 4 ,v, 0, 2 , PlotPoints 60, 12

Graphics3D

Here is the same plot with a variety of specific choices for options.

Show%, PlotRange10, 0, FaceGrids All, BoxRatios1, 1, .5, FaceGrids0, 0, 1,0, 1, 0,1, 0, 0, ViewPoint1, 3, 2,Ticks None, AxesLabel1, 1, 1

Graphics3D

Page 21: Mathematica as a Calculator

Mathematica includes primitives from which you can build up 2D and 3D graphics of any complexity.

This generates a long list of point primitives.

gr FlattenTablePointpq, Denominatorp

q,q, 100,p, q 1;

Here are the first five elements in the list.

Take%, 5Point12, 2, Point1

3, 3, Point2

3, 3, Point1

4, 4, Point1

2, 2

This shows the graphics corresponding to the list of primitives.

ShowGraphicsgr, Frame True

Graphics

This generates a list of 3D cuboid primitives.

gr FlattenTableIfModMultinomialx, y, z, 2 1,Cuboid1.2x, y, z,,x, 0, 15,y, 0, 15,z, 0, 15;

Page 22: Mathematica as a Calculator

Here are the first five elements in the list.

Take%, 5Cuboid0, 0, 0, Cuboid0, 0, 1.2, Cuboid0, 0, 2.4, Cuboid0, 0, 3.6, Cuboid0, 0, 4.8This shows the graphics corresponding to the list of primitives.

ShowGraphics3Dgr

Graphics3D

Page 23: Mathematica as a Calculator

Mathematica lets you produce animated movies as well as static graphics.

Double click the graphic to start the animation.

DoPlot3DSin2xSin2yCost,x, 0, ,y, 0, , PlotRange1, 1, BoxRatios1, 1, 1, Ticks None,t, 0, , 6;

Page 24: Mathematica as a Calculator

Here is another animation.

DoParametricPlot3DCosi

50CosSini

50Sin, Sin, Cos,, 0, 2 ,, 0, 2 , Axes None, Boxed False,

PlotPoints 20, PlotRange1.5, 1.5,1.1, 1.1,1.1, 1.1,i, 0, 25;

Page 25: Mathematica as a Calculator
Page 26: Mathematica as a Calculator
Page 27: Mathematica as a Calculator
Page 28: Mathematica as a Calculator
Page 29: Mathematica as a Calculator

Mathematica also lets you generate sound.

This plays a sound with the specified waveform. Assuming that your computer supports sound output, you can hear the sound immediately by double clicking the graphic.

Page 30: Mathematica as a Calculator

PlaySin t2

024 If

12 t

1214,

124

1363224t2

Sin1625 t 13000t, 0,t, 0, 2, PlayRange All Sound

For more examples of sounds, look at the Sound Gallery.

Mathematica has made possible many new kinds of scientific, technical and artistic images.

Follow these links to see more examples:

• 2D Graphics

• 3D Graphics

• Art Images

• Animations

• Diagrams and Objects

Page 31: Mathematica as a Calculator

Mathematica Notebooks

Every Mathematica notebook is a complete interactive document combining text, tables, graphics, calculations, and other elements.

This document is a notebook.

Your notebooks are automatically organized in a hierarchy of cells.

You can close groups of cells so you see only their headings.

You can use hyperlinks to jump within a notebook or between notebooks.

You can assign each cell a style from a style sheet.

Your Mathematica notebooks are automatically retargeted for screen or printout—optimizing fonts and layout for each medium.

Mathematica provides hundreds of options that allow you to give notebooks any look you want and to generate full publication-quality documents.

Everything in the Mathematica Help Browser is a notebook — including the complete online Mathematica Book.

Here is some ordinary text. It can be in any font, face, size, color, and so on. You can have special characters such as as well as formulas such as

1

x51 x

embedded in text.

Mathematica makes it easy to set up tables and arrays.

2 2 3

3 3 2 2 2Mathematica lets you set up spacing and justification for text.

Like other objects in Mathematica, the cells in a notebook, and in fact the whole notebook itself, are all ultimately represented as Mathematica expressions. With the

standard notebook front end, you can use the command Show Expression to see the text of the Mathematica expression that corresponds to any particular cell.

Like other objects in Mathematica, the cells in a notebook, and in fact the whole notebook itself, are all ultimately represented as Mathematica expressions. With the

standard notebook front end, you can use the command Show Expression to see the text of the Mathematica expression that corresponds to any particular cell.

Page 32: Mathematica as a Calculator

The Mathematica language can be used to specify all aspects of notebooks.

Here is a typical cell in a notebook.

This is a typical cell.

This is how Mathematica represents the cell.

Cell["This is a typical cell.", "Text",

CellFrame->True,

FontWeight->"Bold",

FontSlant->"Italic",

Background->RGBColor[0, 1, 1],

CellTags->"T.8"]

Mathematica notebooks can be built up using explicit commands as well as interactively.

This tells Mathematica to print three cells in subsubsection style.

DoStylePrintStringJoin"Heading ", ToStringi, "Subsubsection",i, 3Heading 1

Heading 2

Heading 3

Page 33: Mathematica as a Calculator

Palettes and Buttons

Palettes and buttons provide a simple but fully customizable point-and-click interface to Mathematica.

Mathematica comes with a collection of ready-to-use standard palettes.

Here is part of the Basic Calculations palette.

.Cross,

Outer, , ListConvolve, ListCorrelate,

TrDet

InverseTransposeEigenvaluesEigenvectorsLinearSolve, RowReduce

Here is the International Characters palette for European characters.

à á â ã ä å æ çè é ê ë ì í î ïð ñ ò ó ô õ öø ù ú û ü ý ÿ þ

ß À Á Â Ã Ä Å Æ

Ç È É Ê Ë Ì Í Î

Ï Ð Ñ Ò Ó Ô Õ

Ö Ø Ù Ú Û Ü Ý Þ€ £ ¥ « » ¿ ¡

Page 34: Mathematica as a Calculator

Palettes work like extensions to your keyboard.

In a palette like this, clicking the button inserts an into the notebook.

2121 Here is a working version of the palette.

In a palette like this, the indicates where the current selection should be inserted. Log2 Exp

Clicking the button takes the highlighted selection and wraps a square root around it.

1 Sinx Cosx1Sinx Cosx

Here is a working version of the palette. Log

2 Exp

Page 35: Mathematica as a Calculator

It is easy to create your own custom palettes.

You can create a blank palette using the Create Table/Matrix/Palette item in the Input menu.

DarkenLightenEdgeSelect

You can create custom palettes to do any function or manipulate any expression.

ExpandFactorSimplify

Clicking the button immediately factors in place the expression you have selected.

1 a^2 2a b b^2 pq21a b2p q2Here is a working version of the palette:

ExpandFactorSimplify

Follow this link to see other examples of palettes.

Page 36: Mathematica as a Calculator

Mathematical Notation

Mathematica notebooks fully support standard mathematical notation—for both output and input.

Mathematica combines the compactness of mathematical notation with the precision of a computer language.

Here is an integral input using only ordinary keyboard characters.

IntegrateLog1 xSqrtx, x4x 4ArcTanx 2x Log1 xHere is the same integral entered in 2D form with special characters. You can enter this form using a palette or directly from the keyboard.Log1

4 4ArcTan 2 Log1 This shows the keys you need to type to get the input above. The symbol stands for the key.

intLog1 x 2x ddx

Mathematica always lets you edit output—and use it again as input.

4 4ArcTan 2 Log1 4 4ArcTan2 2 Log1

Mathematica can generate output in traditional textbook form. Note that Mathematica's StandardForm is precise and unambiguous whereas TraditionalForm requires heuristics for

interpretation. This asks Mathematica to compute the integral and display the result in TraditionalForm.Log1

TraditionalForm4tan1 2

log 1 4

Page 37: Mathematica as a Calculator

Mathematica produces top-quality output for formulas of any size or complexity.

0

Cos4

22 2 TraditionalForm 1F2; 1, 1

;1

4 1F2; 1,

1;1

4 1F2 ; 1, 1

;1

4 1F2 ; 1,

1;1

44 1F2; 1, 1

;134 1F2; 1,

1;1341F2 ; 1, 1

;134 1F2 ; 1,

1;1344

Look at the Formula Gallery for other examples of mathematical formulas generated by Mathematica.

Mathematica makes it easy to work with abstract notation.

Tablei i i

6i,i, 6 1 1

1

5, 2 2

2

4, 3 3

3

3, 4 4

4

2, 5 5

5

1, 6 6

6

0Mathematica supports over 700 special characters with new fonts optimized for both screen and printer. You can find all these characters in the Complete Characters palette. All of

them have consistent full names; some also have aliases, as well as TeX and SGML names.

Page 38: Mathematica as a Calculator

Mathematica and Your Computing Environment

Mathematica runs compatibly across all major computer systems, and lets you exchange data in many standard formats.

The standard Mathematica system consists of two parts:

The kernel—which actually does computations.

The front end—which handles user interaction and notebooks.

Mathematica notebooks are completely compatible across computer systems.

From within one notebook you can run several Mathematica kernels—on local or remote computers.

Page 39: Mathematica as a Calculator

Mathematica notebooks allow importing and exporting of many formats.

You can export graphics and formulas to other programs in EPS, GIF, and so on, and then manipulate them.

Complete Mathematica notebooks can be exported in formats such as HTML, TeX, and RTF.

Page 40: Mathematica as a Calculator

Notebook files contain only plain text and are completely portable.

Choose Show Expression from the Format menu to see the expression form of cells in this notebook.

Here is a typical cell in a Mathematica notebook.Log1

This is what you get when you copy the integral into an external text application such as email.

\!\(\[Integral]\(Log[1 +

\[Xi]]\/\@\[Xi]\)\[DifferentialD]\[Xi]\)

Mathematica uses the Unicode standard to ensure portability of international character sets.

Mathematica provides system-independent functions for file manipulation.

This finds a list of all notebook files in your home directory.

files FileNames".nb", $HomeDirectory

Page 41: Mathematica as a Calculator

The Unifying Idea of Mathematica

Mathematica is built on the powerful unifying idea that everything can be represented as a symbolic expression.

All symbolic expressions are built up from combinations of the basic form:

headarg1, arg2, …A list of elementsa, b, cLista, b, cAn algebraic expression

x2 xPlusPowerx, 2, SqrtxAn equation

x SinxEqualx, SinxA logic expression

p&& q

Andp, NotqA command

m1 aAddToPartm, 1, a

Page 42: Mathematica as a Calculator

Graphics

GraphicsCircle1, 0, 2,Circle1, 0, 2

Abstract mathematical notation

a b c

TildeCirclePlusa, b, Subscriptc, InfinityA button

Presshere

ButtonBox"Press here"A cell in a notebook

A cell containing text

Cell"A cell containing text", "Text"The uniformity of symbolic expressions makes it easy to add to Mathematica any construct you want.

A chemical compound

HNO3

ChemicalHydrogen, 1,Nitrogen, 1,Oxygen, 3

Page 43: Mathematica as a Calculator

An electric circuit

CircuitResistor"R",Capacitor"C"

All operations in Mathematica are ultimately transformations of symbolic expressions. Mathematica has a uniquely powerful pattern

matcher for applying transformation rules.

The /. tells Mathematica to apply the simple transformation rule b1+x.a, b, c, d. b 1 xa, 1 x, c, dx_ and y_ each stand for any expression, so the pattern x_+y_ stands for a sum of terms.a b, c d, a c. x_y_ x2 y2a2 b2, c2 d2, a2 c2a b, c d, a c. ax_ x3b3, c d, c3Mathematica uses patterns to generalize the notion of functions.

This is an ordinary function definition to be used for any x.

fx_: 2x

Page 44: Mathematica as a Calculator

Here is a special case that overrides the general definition.

f0: eHere is an example of the use of f.

f6 fa bf01

3

2

a b e

This clears the definitions given for f.

ClearfAn important feature of using patterns is that they allow "functions" to take arguments in any structure.

This defines a value for g with an argument that is a list of two elements.

gx_, y_: xyg4, a b4 ab

CleargThis specifies the value for the "function" area when given a Circle object as an argument.

areaCircle_, _, r_: r2

areaCircle2, 3, u u2

This implements a logic reduction rule.

reducep_ && q_p_: p

Page 45: Mathematica as a Calculator

Mathematica as a Programming Language

Mathematica is an unprecedentedly flexible and intuitive programming language.

Mathematica includes advanced programming methods from modern computer science —and adds a host of new ideas of its own.

Mathematica incorporates a range of programming paradigms—so you can write every program in its most natural way.

Procedural Programming

z a;

DoPrintz z i,i, 3a1 aa1 a2 a1 aa1 a2 a1 a3 a1 a2 a1 aClearzList-based Programming

Many operations are automatically threaded over lists.

1a, b, c21 a2, 1 b2, 1 c2Tableij,i, 4,j, i1,2, 4,3, 9, 27,4, 16, 64, 256This flattens out sublists.

Flatten%1, 2, 4, 3, 9, 27, 4, 16, 64, 256This partitions into sublists of length 2.

Page 46: Mathematica as a Calculator

Partition%, 21, 2,4, 3,9, 27,4, 16,64, 256Functional Programming

NestListf, x, 4x, fx, ffx, fffx, ffffxThe

1 #2 &

is a "pure function". The argument is inserted into the # slot.

NestList1 #2 &, x, 3x,1 x2,1 1 x22,1 1 1 x222Rule-Based Programming

px_ y_: px pypa b cpa pb pcThe _ stands for a single expression; __ stands for any sequence of expressions.

sx__, a_, y__, a_:a, x, x, y, ys1, 2, 3, 4, 5, 6, 44, 1, 2, 3, 1, 2, 3, 5, 6, 5, 6Clearp, sObject-Oriented Programming

Here are three definitions to be associated with the object h.

Page 47: Mathematica as a Calculator

h: hx_ hy_: hplusx, yh: phx_, x_: hpxh: f_hx_: fhf, xThis uses the definitions made for h.

ha hb fhrhhxfhf, r fhh, x hplusa, bClearhString-Based Programming

StringReplace"aababbaabaabababa","aa" "", "ba" ""baaMixed Programming Paradigms

Many of Mathematica's most powerful functions mix different programming paradigms.

Position1, 2, 3, 4, 52, _Integer2,4MapIndexedPower,a, b, c, da,b2,c3,d4FixedPointListIfEvenQ#1, #1

2, #1&, 105100000, 50000, 25000, 12500, 6250, 3125, 3125

ReplaceLista, b, c, d, e,x__, y__x,y

Page 48: Mathematica as a Calculator

a,b, c, d, e,a, b,c, d, e,a, b, c,d, e,a, b, c, d,eMathematica gives you the flexibility to write programs in many different styles.

Here are a dozen definitions of the factorial function.

f Factorial

fn_: n

fn_: Gamman 1fn_: n fn 1; f1 1

fn_: Producti,i, nfn_: Modulet 1, Dot ti,i, n; tfn_: Modulet 1, i, Fori 1, i n, i, t i; tfn_: ApplyTimes, Rangenfn_: FoldTimes, 1, Rangenfn_: Ifn 1, 1, nfn 1f If#1 1, 1, #1#0#1 1&fn_: Fold#2#1&, 1, ArrayFunctiont, #t&, nAfter you have finished with definitions for f, you must clear them.

ClearfWriting Programs in Mathematica

Mathematica's high-level programming constructs let you build sophisticated programs more quickly than ever before.

Page 49: Mathematica as a Calculator

Single-line Mathematica programs can perform complex operations.

This program produces a one-dimensional random walk.

RandomWalkn_: NestList#1RandomInteger&, 0, nHere is a plot of a 200-step random walk.

ListPlotRandomWalk200, PlotJoined True

50 100 150 200

-5

-2.5

2.5

5

7.5

Graphics

The directness of Mathematica programs makes them easy to generalize. This program produces a random walk in d dimensions.

RandomWalkn_, d_: NestList#1TableRandomInteger,d&, Table0,d, nHere is a plot of a 3D random walk.

ShowGraphics3DLineRandomWalk1000, 3

Page 50: Mathematica as a Calculator

Graphics3D

The richness of Mathematica's programming language makes it easy to implement sophisticated algorithms.

Here is a direct program for a single step in the Life cellular automaton.

LifeStepa_List:MapThreadIf#1 1 && #2 4#2 3, 1, 0&,a, SumRotateLefta,i, j,i, 1, 1,j, 1, 1, 2

Here is an alternative highly optimized program, which operates on lists of live cells.

LifeSteplist_:Withu SplitSortFlattenOuterPlus, list, N9, 1, 1,

UnionCasesu,x_, _, _ x,IntersectionCasesu,x_, _, _, _ x, list

N9 FlattenArrayList,3, 3, 1, 1;Mathematica makes it easy to build up programs from components. This sets up components for a cellular automaton simulation system.

CenterListn_Integer: ReplacePartTable0,n, 1, Ceilingn2

Page 51: Mathematica as a Calculator

ElementaryRulenum_Integer: IntegerDigitsnum, 2, 8CASteprule_List, a_List: rule8 RotateLefta 2a 2 RotateRightaCAEvolveListrule_List, init_List, t_Integer: NestListCASteprule, #&, init, tCAGraphicshistory_List: GraphicsRaster1 Reversehistory,

AspectRatio AutomaticThis runs an example.

ShowCAGraphicsCAEvolveListElementaryRule30, CenterList101, 50

Mathematica has a compiler for optimizing programs that work with lists and numbers. This sets up a compiled definition for CAStep.

CAStep Compilerule, _Integer, 1,a, _Integer, 1, rule8 RotateLefta 2a 2 RotateRightaMathematica programs are often a direct translation of material in textbooks. Here are definitions for impedance in a circuit.

ImpedanceResistorr_, _: rImpedanceCapacitorc_, _: 1

c

ImpedanceInductorl_, _: l

ImpedanceSeriesElemente_, _: ApplyPlus, MapImpedance#, &, eImpedanceParallelElemente_, _: 1ApplyPlus, 1MapImpedance#, &, e

Page 52: Mathematica as a Calculator

This uses the definitions that have been given.

ImpedanceSeriesElementTableParallelElementTableSeriesElementResistorRn,n,n, 1, 4, SimplifyR1

1

126R2 4R3 3R4

Here is a picture of the circuit, generated from its symbolic specification.

Mathematica programs provide unprecedentedly clear ways to express algorithms.

Both of these programs approximate the Golden Ratio to k digits.

1k_: 1 FixedPointN11 #1

, k&, 12k_: FixedPointN1 #1, k&, 1120, 220, NGoldenRatio, 201.61803398874989484821, 1.6180339887498948482, 1.6180339887498948482Mathematica programs allow a unique combination of mathematical and computational notation.

These definitions correspond to a recently-discovered approximation to the number of primes.

n_: ApplyPlus, MapLast, FactorIntegernn_: MoebiusMunx_:

k1

Log2,xk

n2

x1knnx1kn; x 0

Page 53: Mathematica as a Calculator

This compares the approximation with the built-in PrimePi function.1000, PrimePi10001229, 1229Mathematica programs can mix numerical, symbolic, and graphics operations. This short program solves a sophisticated quantum model.

These definitions set up a Kohmoto model for the energy spectrum of a quantum particle in a one-dimensional quasiperiodic potential.

FareySequenceq_: ApplyUnion, ArrayRange#1#&, qTransferMatrix_, _, p_: If1 Modp, 1 1, 1, 0, 1,1, 0TransferMatrixList_, _: TableTransferMatrix, , p,p, 0, Denominator 1TransferMatrixProduct_, _: FoldExpandDot##&, First#, Rest#&TransferMatrixList, EnergyPolynomial_, _: PlusTransposeTransferMatrixProduct, ,1, 1Spectrum_, _: . NSolve# 2# 2, &EnergyPolynomial, SpectrumData_: MapLine, PartitionThread, SortSpectrum, , 2This runs the model, generating symbolic eigenvalue equations from transfer matrices and then solving them numerically.

ShowGraphicsSpectrumData FareySequence20

Page 54: Mathematica as a Calculator

Graphics

Look at the Programming Sampler demo to see more examples of Mathematica programs.

Building Systems with Mathematica

Mathematica has everything you need to create complete systems for technical and non-technical applications.

Combinatorica is a system for doing discrete mathematics that comes as a standard add-on package with Mathematica.

This loads the Combinatorica system.

DiscreteMath Combinatorica

This uses functions set up by the package.

ShowGraphLineGraphLineGraphCirculantGraph5, Range1, 3

Graphics

WorldPlot is another standard add-on package that comes with Mathematica.

Page 55: Mathematica as a Calculator

Miscellaneous WorldPlot

WorldPlotWorld, WorldProjection N#2AbsSin# Degree60 1

2, #&, WorldBackground Hue.5

WorldGraphics

Optica is a large Mathematica package for doing optical engineering.

Optica

DrawSystemConeOfRays10, NumberOfRays 10,MovePlanoConvexLens100, 50, 10,100, 0, 0,MovePlanoConvexCylindricalLens100,50, 50, 10,130, 0, 0,MoveBeamSplitter50, 50,50, 50, 10,180, 0, 45,Boundary100, 100, 100,250, 100, 200;

Page 56: Mathematica as a Calculator

Mathematica has made possible a new generation of notebook-based educational courseware.

Follow this link to see a simple example.

Technical Trader is a Mathematica system for financial analysis.

Technical Trader uses palettes and buttons to build a custom user interface.

ACAD Autodesk, Inc.

BORL Borland International

INGR Intergraph Corp.

INTU Intuit

MSFT Microsoft

NOVL Novell, Inc.

ORCL OracleSystem Corp.

SYBS Sybase

Clicking on a button in Technical Trader can generate a notebook of data.

Page 57: Mathematica as a Calculator

Historical Daily Data for Microsoft (MSFT)

High-Low-Open-Close

111595 1128 128 1220 1396 115 12575

80

85

90

95111595 1128 128 1220 1396 115 125Microsoft

Summary StatisticsMax Min Average Volatility

Close 94.5 80.1875 88.4865 2.83299Volume 14215. 711.1 5784.41 2879.6

Any system you build in Mathematica will run unchanged across all computer platforms.

Mathematica as a Software Component

Mathematica has a modular architecture that makes it easy to use as a highly powerful software component.

Page 58: Mathematica as a Calculator

Here is some input and output in the standard notebook front end to Mathematica.Logxx1

2 ErfiLogx xLogx

You can also access the Mathematica kernel directly from a raw terminal.

Integrate[Sqrt[Log[x]], x]

1

2 ErfiLogx xLogx

MathLink provides a general program-level interface between Mathematica and external programs.

Here is C code for sending an expression from an external program to Mathematica.

/* Integrate[Sqrt[Log[x]], x] */

MLPutFunction( stdlink, "EvaluatePacket ", 1);

MLPutFunction( stdlink, "Integrate", 2);

MLPutFunction( stdlink, "Sqrt", 1);

MLPutFunction( stdlink, "Log", 1);

MLPutSymbol( stdlink, "x", 1);

MLPutSymbol( stdlink, "x");

MLEndPacket( stdlink);

Click here to load the kernel and set the working directory to one that contains prebuilt examples for your computer system.

This installs a compiled external C program that does bitwise operations on integers.

link Install"bitops";This executes the external code for the BitAnd function.

Page 59: Mathematica as a Calculator

BitAnd22222, 33333516

This uninstalls the external program.

Uninstalllink;You can use MathLink to access the Mathematica kernel from many kinds of programs.

Here is the Microsoft Word front end to Mathematica.

Here is a web site that calls Mathematica.

Page 60: Mathematica as a Calculator

Here, Microsoft Excel is linked to Mathematica.

Page 61: Mathematica as a Calculator

Under Microsoft Windows, you can click this button to start a simple example of a Visual Basic front end to Mathematica.

MathLink can also be used to access other programs from within the Mathematica kernel.

MathLink allows you to set up templates to specify how external programs should be called. This defines a link to a C subroutine library.

:Begin:

:Function: anneal

:Pattern: TSPTour[r:{{_, _}..}]

:Arguments: {First[Transpose[r]], Last[Transpose[r]],

Length[r], Range[Length[r]]}

:ArgumentTypes: {RealList, RealList, Integer, IntegerList}

:ReturnType: Manual

:End:

Here is a 3D graphic generated within Mathematica.

ParametricPlot3D2 Cosu2Sinv Sinu

2Sin2vCosu,2 Cosu

2Sinv Sinu

2Sin2vSinu,

Sinu2Sinv Cosu

2Sin2v,v, 0, 2Pi,u, 0, 2Pi, PlotPoints 30, Boxed False, Axes None

Page 62: Mathematica as a Calculator

Graphics3D

This image was generated by sending a description of the graphic from Mathematica, via a MathLink connection, to an external photorealistic renderer.

You can use MathLink to control the Mathematica front end from within the kernel.

This tells the front end to bring up the color selector dialog box.

FrontEndTokenExecute"ColorSelectorDialog"You can use MathLink to communicate between Mathematica kernels — on one computer or several.

On most computer systems (typically excluding Macintosh) this launches a subsidiary Mathematica kernel on your computer.

Page 63: Mathematica as a Calculator

link LinkLaunch"MathKernel mathlink";This reads data from the subsidiary Mathematica kernel.

LinkReadlinkInputNamePacketIn1:This writes a command to the subsidiary kernel.

LinkWritelink, Unevaluated$SessionIDThis reads back the $SessionID from the subsidiary kernel.

LinkReadlinkReturnPacket20002811790628968292The $SessionID in your main kernel will be different.

$SessionID

20000841219624707995

This closes down the subsidiary kernel.

LinkCloselink;The World of Mathematica

With over a million users worldwide, a vast array of Mathematica products and services now exists.

There are now hundreds of books in over a dozen languages about Mathematica.

Page 64: Mathematica as a Calculator

Several print and electronic periodicals are devoted to Mathematica.

Page 65: Mathematica as a Calculator

There is a growing library of professional applications based on Mathematica.

Hundreds of courses have been developed in Mathematica.

Page 66: Mathematica as a Calculator

Wolfram Research's MathSource is a vast repository of Mathematica material.

A wide range of products use Mathematica in their development or implementation.

Page 67: Mathematica as a Calculator

The Wolfram Research Mathematica web site contains thousands of pages of material, and is constantly being updated.

Page 68: Mathematica as a Calculator