Chapter 2 =Introduction to Mathematica.pptx

esraelman182 61 views 35 slides Jun 20, 2024
Slide 1
Slide 1 of 35
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35

About This Presentation

Good


Slide Content

Chapter 2 Introduction to Mathematica

Getting Started Types of interfaces used: Notebook and Text-Based Interfaces Notebook interface - interactive documents Text-based interface - text from the keyboard To start Mathematica on Windows : (Notebook interface) Start -> Wolfram Mathematica -> Wolfram Mathematica 9 To start Mathematica Kernel ( text-base interface) on Windows: Start -> Wolfram Mathematica -> Wolfram Mathematica 9 Kernel

Using a Notebook Interface A purely graphical interface  double-click the Mathematica icon to start Mathematica. A textually based operating system  type the command Mathematica to start. An empty notebook with a blinking cursor  by default will interpret your text as input  type Shift+Enter to make Mathematica process your input. Shift+Enter tells Mathematica that you have finished your input. If numeric keypad  its Enter key instead of Shift+Enter . After you send Mathematica input from your notebook, Mathematica will label your input with In[n]:=. It labels the corresponding output Out[n]=. Labels are added automatically. In[1]:= 2 + 2 Out[1]= 4 notebooks are part of the "front end" to Mathematica. 3

Getting Started Notebook and Text-Based Interfaces Three main activities Notebook Interface Text-Based Interface Start Mathematica Math Execute command Shift-Enter Enter Exit Choose the Quit menu item Cntr -D or Quit[]

Numerical Calculations x+y+z add x -y subtract x /y divide x y z or x*y* z multiply x^y power x *( y+z ) control grouping by parentheses Note : You can use space or a * sign for multiplication

Numerical Calculations You get exact result with Mathematica unless you request otherwise. In[1] := 2 ^ 100 (* get exact result *) Out[1] := 1267650600228229401496703205376 In[2] := 2 ^ 100 //N (* get approximation *) Out[2] := 1.26765x10 30 In[3] := 1/3 + 2/7 (* get exact result *) Out[3] := In[4] := 1/3 + 2/7 // N (* get approximation *) Out[4] := 0.619048  

Numerical Calculations If an input number contains an explicit decimal point, Mathematica produces an approximate numerical result. In[5] := 11/3 + 2/7 (* exact result *) Out[5] := In[6] := 1 . 1/3 + 2/7 (* approximation *) Out[6] := 0.652381  

Numerical Calculations Sqrt [x] Exp [x] e x Log[x] ln x Log[ b,x ] log b x Sin[x], Cos[x], Tan[x] trigonometric functions ArcSin [x], ... inverse trigonometric functions n! factorial FactorInteger [n] prime factors of n Abs[x] |x| Round[x] closest integer to x Max[ x,y ,...], Min[ x,y ,...] maximum and minimum of a set Mod[ n,m ] remainder of division of n by m Random[] random number between and 1 Sqrt [x] Exp [x] e x Log[x] ln x Log[ b,x ] log b x Sin[x], Cos[x], Tan[x] trigonometric functions ArcSin [x], ... inverse trigonometric functions n! factorial FactorInteger [n] prime factors of n Abs[x] |x| Round[x] closest integer to x Max[ x,y ,...], Min[ x,y ,...] maximum and minimum of a set Mod[ n,m ] remainder of division of n by m Random[] random number between and 1 Common Mathematical Functions

Numerical Calculations Functions in Mathematica The arguments of ALL Mathematica functions are enclosed in square brackets ; The names of built-in Mathematica functions begin with capital letters ; Unless //N option or decimal point is present, Mathematica tries to output exact value

Numerical Calculations Pi E e Degree I i = Infinity ∞ Pi E e Degree I Infinity ∞ Common Mathematical Constants The names of all built-in constants begin with capital letters .

Numerical Calculations Specify the degree of precision In[1] := N[Pi, 30] (* approximation *) Out[1] := 3.14159265358979323846264338328 In[2] := N[ Sqrt [7], 10] Out[2] := 2.645751311

Numerical Calculations Using Previous Results - use with care! In[1] := 7 + 3 Out[1] := 10 In[2] := % + 1 Out[2] := 11 % the last result generated %% the next-to-last result %n the result on output line Out[n] Note: % is always defined to be the last result that Mathematica generated. It can be anywhere in the script!

How to Create Definitions for Variables and Functions Here is a simple transformation rule. It says: whenever you see x, replace it by 3: In[31]:= x = 3 Out[31]= 3 The variable x has a value of 3. In[32]:= x^2 Out[32]= 9 Functions in Mathematica are defined by rules that act on patterns. f[x_] := x^2 The rule says: if you have f of any expression, replace it by that expression squared: In[46]:= f[expr] Out[46]= expr ² 13

g[x_, y_] := f[x] + f[y] In[49]:= g[3, 4] Out[49]= 25 Always use := to define functions, otherwise the variables on the right-hand side may not represent the associated expressions on the left-hand side, since they will be evaluated before the rule is defined. 14

How to Clear Definitions When you set a value to a symbol, that value will be used for the symbol for the entire Mathematica session. Assign values to two symbols (x and y) and observe their sum: In[3]:= x = 5; y = 7; x + y Out[3]= 12 Use Clear to clear the definitions for x and y: Clear[x, y] Observe that x and y no longer have values associated with them: In[5]:= Expand[(x + y)^2] Out[5]= x ² + 2 x y + y ² 15

This command clears all the definitions made during the current Mathematica session: Clear["Global`*"] Use ClearAll to clear not only the values and definitions of symbols but also the attributes and messages associated with them. You can also use Unset (=.) to clear any values or definitions made to a symbol: In[20]:= x = 5 Out[20]= 5 x =. ?x Remove will remove a symbol completely until it is referenced again: Remove[x] ?x Information::notfound: Symbol x not found. >> 16

Numerical Calculations Variables definition x = value assign a value to the variable x x = y = value assign a value to both x and y x = . or Clear[x] remove any value assigned to x Notes: Mathematica is case-sensitive; To avoid confusion with built-in functions, choose names that start with lower-case letters; x y means x times y; xy with no space means variable name xy ; 5x means 5 times x;

Numerical Calculations Lists of Objects List is a collection of several objects in Mathematica In[1] := vec = {2, 4, 1.8} Out[1] := {2, 4, 1.8} In[2] := vec^2 Out[2] := {4, 16, 3.24} In[3] := vec /(vec-1) Out[3] := {1, , 2.25} In[4] := vec [[2]] (* extract second element *) Out[4] := 4 In[5] := Part[vec,1] (* extract first element *) Out[5] := 2  

A matrix in Mathematica is a list of lists. Use RandomInteger to create a 4 Χ 4 matrix of random integers between 0 and 10 (stored as m): In[13]:= m = RandomInteger[10, {4, 4}] Out[13]= {{5, 0, 2, 5}, {3, 2, 8, 6}, {9, 9, 8, 0}, {2, 2, 3, 4}} Use MatrixForm to see m as a 2D matrix: MatrixForm[m] Out[14]//matrixform= You can directly apply math functions to a list: In[15]:= Sqrt[{1, 2, 3, 4}] Out[15]= {1, √ 2, √ 3, 2} 19

In[16]:= 1 + {{a}, {a, b}, {a, b, c}}^2 Out[16]= {{1 + a ² }, {1 + a ² , 1 + b ² }, {1 + a ² , 1 + b ² , 1 + c ² }} In[17]:= Max[{1, 2, 3, 4}] Out[17]= 4 In[18]:= Length[{a, b, c}] Out[18]= 3 This uses Map to apply Length to each sublist: In[20]:= Map[Length, {{a}, {a, b}, {a, b, c}}] Out[20]= {1, 2, 3} 20

21

How to Enter Ranges and Options for Functions Here, Sin[x] is the first argument in Plot, while the second argument {x,0,2π} gives the variable and the range for the plot: In[7]:= Plot[Sin[x], {x, 0, 2π }] Out[7]= When plotting functions of two variables, the ranges for each variable are entered in the second and third arguments: In[6]:= Plot3D[Sin[x + y^2], {x, -3, 3}, {y, -2, 2}] Out[6]= 22

23

Graphics Partial list of Mathematica’s graphs Graphics, Graphics3D Plot, Plot3D ListPlot , ListLinePlot , ListContourPlot , ListPlot3D ListLogPlot , ListPolarPlot , ListSurfacePlot3D, ListContourPlot3D PrarametricPlot , PolarPlot , RevolutionPlot3D, SphericalPlot3D, DensityPlot , ReliefPlot GraphPlot , ArrayPlot RegionPlot , ContourPlot , RegionPlot3D

Graphics Partial List of Graphics Options option name default value AspectRatio 1/ GoldenRatio the height-to-width ratio for the plot; Axes True whether to include axes AxesLabel None labels to be put on the axes Frame False draw a frame around the plot GridLines None what grid lines to include PlotLabel None an expression to be printed as a label for the plot PlotRange Automatic the range of coordinates to include in the plot Ticks Automatic what tick marks to draw if there are axes

Graphics Basic Features for Visualization Functions Feature Classes: Styles Colors, thickness, pointsize, opacity, … Element appearance and shape Labels Textual labels and tooltips Legends Interactions Built-in highlighting effects Use elements for buttons, popup windows and other events Metadata Wrapper used to include additional information ChartElementFunction [] for custom appearances

Data Visualization Basic Statistics Plots Bar Chart, PieChart , BubbleChart Histogram, SmoothHistogram , Density Histogram, Histogram3D QuantilePlot , ProbabilityPlot , ProbabilityScalePlot BoxWhiskerChart , DistributionChart

Functions Function Definition Use underscore _ after a variable name (function argument) f([x_] := x^2 + 4 x + 4 To execute a function, simply call it with a given value: f[1] Mathematica’s built-in functions start with upper-case letter. Start with lower case letter for the user defined function.

Functions Using Functions Show function definition: ?f Expand function: Expand[f[x + y + 1]] Find derivative of a function: D[f[x], x] Find integral of a function: Integrate[f[x] ,x] Find definite integral of a function: Integrate[f[x ] ,{x,0,1}] Clear the definition of a function: Clear[f]

Equations Solving equations Define equation using double equal sign == Solve[4 x^2 + 4 x + 1 == 0] Mathematica can solve an equation for one variable in terms of another Solve[5 x^2 -2 Log[y] == 3 x,y ] Solve system of equations: Solve [{x + 2 y == 5, 7 x – 5 y == -3},{ x,y }]

Equations Solving equations Mathematica can solve algebraic equations in one variable for power less than 5 and sometimes even higher. But there are some equations for which it is impossible to find the root(s) algebraically. Mathematica will use Root object to represent the solution. Use N[%] to evaluate the solution numerically. In some cases Mathematica can solve equations involving other functions: In[1] := Solve[Sin[x] == a, x] Out[1] := {{ x -> ArcSin [a]}}

Equations Solving equations You can also find an approximate numerical solution using FindRoot[] : In[1] := FindRoot[Cos[x] == x, {x,0}] Out[1] := { x -> 0.739085} Mathematica can solve system of simultaneous equations. It can eliminate a variable in a system, using Eliminate[] function, or simplify the system using Reduce[] function.

Programs Programming Constructs Assignments: = += ++ *= AppendTo Loops : Do While For Table Nest Conditionals: If Which Switch And(&&) Equal(==) Less(<) … Flow Control: Return Throw Catch TimeConstrained Scope Constructs: Module With Block I/O: Print Input Pause Import OpenRead …

Code Optimization How to speedup Mathematica code Use Timing and AbsoluteTiming commands to measure the time of execution: In[1] := Module[{x = 1/Pi}, Do[x = 3.5 x (1 - x), { 10^6}]; x ] // AbsoluteTiming

HPC: GPU Programming Image Processing CUDALink In[1] := swan = Import ["swan.JPG "] Out[1] := In[2] := CUDAImageConvolve [swan , GaussianMatrix [16]] (* Convolution *) Out[2] :=