Introduction to Numerical Computing
Introduction to Numerical Computing CS 375
Popular in Course
Popular in ComputerScienence
This 66 page Class Notes was uploaded by Trent Dare on Wednesday September 23, 2015. The Class Notes belongs to CS 375 at University of New Mexico taught by Staff in Fall. Since its upload, it has received 8 views. For similar materials see /class/212214/cs-375-university-of-new-mexico in ComputerScienence at University of New Mexico.
Reviews for Introduction to Numerical Computing
Report this Material
What is Karma?
Karma is the currency of StudySoup.
You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!
Date Created: 09/23/15
MathCS 375 Spring 2009 Lecture 1f Introduction to Matlab Floating Point Arithmetic Chapter 0 FloatingPoint Numbers Nearly all computation on a digital computer is done in floatingpoint FP arithmetic A floatingpoint number system is a number system that uses a finite number of digits to represent the real number system that we use in exact computation Floatingpoint numbers are generally repres ented in binary in a computer The set F of FP numbers Basis 3 Significantdigits t Range U L 39 FBt U L F2 53 1021 1024 is the IEEE standard sign bit it is assumed d1 1 so only need d2d53 exponent 11 bits Machine epsilon Is the distance from 1 to the next larger float pointing number 8 2 eps 2 BH The relative error in representing a nonzero real number x in the system F is RELATIVE ROUNDOFF ERROR Measurement of Error How well a quantity is approximated is measured in two ways absolute error true value approximate value relative error true value approximate valuetrue value In the arithmetic of computers relative error is the more natural concept but absolute error may be preferable when studying quantities close to zero MATLAB DP Floating Point Every computation produces a floating point number Matlab stores floating point numbers and carries out elementary operations to an accuracy of about 16 significant decimal digits Ifthe result is larger than realmax 1797710quot308 overflow occurs and the result is Inf Ifthe result is smaller than realmin 2222510quot308 underflow occurs and the result is lnf or 0 A computation whose result is not mathematically defined produces NaN Not a Number Arithmetic Operator Precedence Precedence Operator 1 highest Exponentiation A 2 Unary plus unary minus 3 Multiplication division 4 lowest Addition subtraction MATLAB Output Formats FORMAT SHORT Scaled fixed point format with 5 digits FORMAT LONG Scaled fixed point format with 15 digits for double and 7 digits for single FORMAT SHORT E Floating point format with 5 digits FORMAT LONG E Floating point format with 15 digits for double and 7 digits for single FORMAT SHORT ENG Engineering format that has at least 5 digits and a power that is a multiple of three FORMAT LONG ENG Engineering format that has exactly 16 significant digits and a power that is a multiple of three For all output formats type help format in Matab Command Window Format Example 7 format long default for 71 pi 314159265358979 format short pi 31416 format short 6 pi 314l6e000 format long 6 pi 3141592653589793e000 Some Interesting Implications of Rounding Error Three of these examples follow The Patriot Down and out in Vancouver I shot an arrow in the air The sad story of the Ariane 5 The Patriot During the Gulf War an Iraqi Scud got through the Patriot antimissile system and hit a barracks killing 28 people To track the Scud the system had to determine the interval between tracking times by subtracting two values of a timer The times in tenths of a second were stored as integers 42 was stored as 42 in the onboard computer The Patriot cont To compute the interval timer values were converted to floatingpoint representation by multiplying by 01 01 has a nonterminating binary expansion consequently the interval was computed with error the larger the value the larger the error At the time of the incident the missile battery had been operating for over 100 hrs resulting in an error of 034 sec in the timer causing the system to look in the wrong place for the incoming Scud Down and Out in Vancouver Stock Exchange In 1982 the Vancouver Stock Exchange introduced an index with a nominal value of 1000000 After each transaction the index was recomputed and truncated to three decimal places After 22 months of transactions the index was 524881 The true value was 1098811 The sad story of the Ariane 5 On June 4 1996 Ariane was launched at Kourou and all went well for 36 sec At second 37 the rocket veered off course and selfdestructed The problem was in the Inertial Reference System The sad story of the Ariane 5 The IRS tried to convert a 64bit floating point number to a 16bit integer The number was too large which triggered an error and send a diagnostic message to the OnBoard Computer The OBC interpreted the diagnostic word as flight data Finis Solution of a Quadratic Equa on The solution to the quadratic equation xquot2 bx c 0 is x b lsqrtbquot2 4c2 Example b 0125335 c 0360551e6 using 6 digit decimal arithmetic r1 125333e1 1253321232e1 r2 25000096 287676447796 Quadratic Equation cont r1 looks pretty good but r2 does not Why Cancellation occurred in forming b sqrtbquot2 4c2 0125335 01253302 25e6 However death occurred when we formed bquot2 4c 00157089 00000144220 00157075 Cancellation and the additionsubtraction of floatingpoint numbers with differing magnitudes can cause problems Quadratic Equation the cure We must restore the information that we don t have about the coefficient c A little algebra will tell us that if r1 and r1 are real distinct roots of xquot2 bx c 0 then r1 r2 c So we compute r1 as before and compute r2 as r2 cr1 360551e6 I 125332e1 287677 2876764477e6 COMPLEX NUMBERS z x iy x Rez is the real part y mz is the imaginary part iquot2 1 is the imaginary unit polar form Z 2 pa 0cos9isin 9 complex conjugate Z x iy Matlab commands gtgt 2 3i4 gtgt Cartesian form x reaz y imagz gtgt Polar form theta anglez rho absz So 2 abszcosangez isinanglez xiy conjz The complex plane z12i 31i i compassz r 0 defines an array of complex numbers which are plotted as vectors in the xy plane Roots of complex numbers x1 xquot13 ans 05000 08660i Matlab assumes complex arithmetic and returns automatically the root with the smallest phase angle the other two roots are 1 and 05000 08660i MAICS 375 Spring 2009 Lecture 2b FZERO Use Summary of Lecture 2a We examined three methods to find a root of a real function of a real variable Bisection Robust but slow linear convergence Newton s method Less robust quadratic convergence requires derivative Secant rule Less robust almost quadratic convergence does not require a derivative Open questions Is there a way to combine these procedures to develop a method that is robust with reasonably fast convergence What is a robust stopping criterion for both Newton s method and the secant rule FZERO Usage X FZEROFUNXO X0 a scalar Attempts to find a zero of the function FUN near X0 FUN is a function handle The value X returned by FZERO is near a point where FUN changes sign if FUN is continuous or NaN if the search fails X FZEROFUNXO X0 a 2 vector Assumes that FUNXO1 and FUNXO2 differ in sign insuring a root X FZEROFUNX00PTONS Solves the equa tion with default optimization parameters replaced by values in the string OPTIONS an argument created with the OPTIMSET function FZERO Usage cont X FZEROFUNX00PTONSP1P2 allows for additional arguments which are passed to the function FFUNXP1P2 Pass an empty matrix for OPTIONS to use the default values XFVALEXTFLAG FZERO returns the value of the objective function described in FUN at X and an EXITFLAG that describes the exit condition of FZERO See help FZERO and help OPTIMSET for details FZERO Details Brent s Method erro implements a version of Brent s method along with a processing step to discover a good initial bracketing interval if one is not provided by the user Brent s method Assume we have a bracket aibi for a root First inverse quadratic inter polation is tried and the result is used to replace one of xi ai bi if the residual error improves w the bracketing interval is cut at least in half If not the secant method is used if this fails a bisection step is taken Text pg 6869 FZERO Example 1 Script fzeroEx1 FZEROEX1 determines the zeros of the function fxxquot2 2 Set options to display iterations and assign error tolerance tolx 1e6 Setup options optimset39disp39 39iter39 39tolx39 1e6 f x xquot2 2 Bracket root and call fzero Print results xrootfval fzerof 12 options fprintf39xroot 64f fresidual 84en39 xrootfva FZERO Example 1 cont gtgt fzeroEx1 Func count x fx Procedure 2 1 1 initial 3 133333 0222222 interpolation 4 141905 00136961 interpolation 5 141407 0000401762 interpolation 6 141421 685547e007 interpolation 7 141421 685547e007 interpolation Zero found in the interval 1 2 xroot 14142 fresidual 68555e007 gtgt FZERO Example 2 1st positive root of cosbetax a 0 function plotEx2 beta pi3 a 05 xpinspace015200 fpfxpbetaa npengthxp plotxpnpzeros1npxpfp xlabel39x39ylabel39cosbetaxa39 tite39Pot of cosbetaxa vs x39 function zfxbetaa zcosbetaxa cosbetaxa D 5 D 5 10 X Plot of cosbetax a vs x 15 FZERO Example 2 cont function fzeroEx2 Finds first positive root of fx cosbetaxa where parameters beta pi3 and a 05 Setup beta pi3 a 05 options x0 02 The first positive root has been bracketed from a plot of fx the interval 02 Return root residual and iflag xfvaliflag fzerofx0optionsbetaa fprintf39xroot 64f fval 64e iflag 20fn39 XfVa39i ag gtgt fzeroEx2 xroot 10000 fval 11102e016 iflag 1 gtgt function z fxbetaa z cosbetax a inclass5 A wire ways 0518 lbsft and is suspended between two towers of equal height at the same level and 500 ft apart lfthe sag in the wire is 50 ft find the maximum tension T in the wire The equations to be solved are c 50 c cosh52 00 T 0518c 50 C Solve the first equation for c then solve the second equation for T Plot the first equation to bracket the root c as a first step Download fzeroEX2 from web site and modify FZERO Example 3 Find the first n positive zeros of the function f x xix tanx Solution process Plot to isolate zeros Use of FZERO to compute zeros to desired accuracy Example 3 cont function fzeroEx3 Find the roots of 39amxcosx sinx 0 using FZERO by providing estimates for each root from a plot xstart04711141720232629 nstart engthxstart xsolzeros1 nstart ysozeros1nstart options optimset39tox39 1e8 Iamda1 for k1nstart xsokysokfzerof xstartkoptionsamda fprintf39xso 64f yso 64e n39 xsok ysok end Example 3 cont np500 xpinspace030np ypfxp1 zzeros1np axis0 30 30 301 plotxpyp3939xsoyso39o39xpz3939 titlesprintf39Solution of fxamdaxtanx Iamda 21f lamda legend39lamdaxtanx39 roots39 xlabel39x39 yabe fx function z fxamda z amdaxcosxsinx Example 3 cont gtgt Ex3 xsol 00000 ysol 00000e000 xsol 44934 ysol 17250e 008 xsol 77253 ysol 14222e 010 xsol 109041 ysol 72056e 009 xsol 140662 ysol 95231e007 xsol 172208 ysol 22821e006 xsol 203713 ysol 34095e006 xsol 235195 ysol 27519e006 xsol 266661 ysol 70829e007 XSOI 298116 ysol 48331e 010 gtgt 30 Example 3 cont Solution offxamdax tanx Iamda 10 2D 20 30 D l CI Iamdaxcosxsinx Roots A Search amp Compute Routine Let s look at this one toqether on my site fzeroEx4 x 108 Plot offtxax34 5x205gtlt1munu2 1J1rr2nu2l vs x 1 ql A xx 2 D I I I M a 2 4 5 I 1 I W 1 1 500 1000 500 0 500 1000 1500 X root 11449343 froot 00000e000 root 00323 froot 72760e 012 root 11464021 froot 00000e000 MAICS 375 Spring 2009 Lecture1d Introduction to MATLAB Plotting Ref Appendix B Buildingplotting a function of a vector 1 Create a vector x with 50 equally Mmdwmm S aced entries from new Opto 1 O x linspace 0 1 50 J f cos2pix 2 Create a vector f p39otlxl fa t with entries of w cosine evaluated at entries of 2pix 3 Plot f as a function of x using i symbols MATLAB Command Window Figure created by Matlab EEI Exle dH Window lp 5L3 X linspace O 1 50 1 f cos2pix plot X f 3939 g EFigule No 1 He gum Mndow e p Example Building and plotting two functions of a vector 1 Create a vector x with 50 Newquot Wind 5539 entries from 00 to 10 Ml EatEl le iEl X linspace O 1 50 J 2 Create a vectorI With Me cos2pix entries cos2 pi x g sin2pix 3 Create a vector 9 with entries pl0tX f1 39b39 sin2pix hold on 4 Plot f as a function of x Eligx fg39 r using a blue line O 0 I 5 On same graph plot 9 as a function of x using red symbols A gt a hold on instructs Matlab to keep the current graph window and its contents open for another plot hold off closes the figure for input Examgle MATLAB CummandWindow HIE DFigureNoJ lg gm Wmdow e p le Edit VJIndow Help 135 Li w my x linspace O 1 50 d f cos2pix g sin2pix plotx f 39b39 hold on plotx g39r39 hold off EHe Quick Reference For Plot Taken from Matlab gt help plot Various line types plot symbols and colors may be obtained with PLOTXYS where S is a character string made from one element from any or all the following 3 colunms y yellow point solid m magenta o circle dotted c cyan x xmark dashdot r red plus dashed 9 green star b blue 3 square w white d diamond k black v triangle down quot triangle up lt triangle left gt triangle right p pentagram h hexagram Adding a Title Labeling Axes and Legends Give the graph a title gtgt tite The very boring graphs39 Label the axis gtgt xlabel39x39 Label the yaxis gtgt ylabel39fg39 Set up the legend box with descriptions of each curve gtgt legend39fcos2pix39 39gsin2pix39 Example l 394 l m leumomwyflcwmasmm v J To get started select quotMATLAB Helpquot from the Help menu gtgt x inspace0 1 50 gtgt f cos2pix39 gtgt plotxf39b39 gtgt hold on plotxg39r39 hold off gtgt gtgt legend39fcos2pix39 39gsin2pix39 The labeling gtgt xlabel39x39 gtgt yIabeICtg39 commands gtgt title39The very boring graphs39 gtgt l 4 Readv Example guleN 1 EH2 mz Mew lnsevt Ian s Mndaw dew Mn HTAfUQB usa pm san pw x Defining Font SizesTypes V MATLAB EH2 mz Mew WEE Mndaw new D aw x a g v 3 n Cunemeedmy CWAYLABBp WmK J gtgt X inspaoe0133 4 gtgt f oos2pix gtgt 9 sin2pix gtgt plotxf39b39 gtgt hold on plotxg39r39 hold off gtgt title39Most boring graphs39 39FontSize39 28 39FontName 39Arial39 gtgt Xlabel39x39 39FontSize39 24 39FontName 39Arial39 gtgt ylabel39fg39 39FontSize39 24 39FontName 39Arial39 gtgt legend39f 39939 gtgt b 4 J Readv Most boring graphs J I I frifn I 08 05 14 1 2 3 4 5 6 7 lnclass2 Create two curves on the same graph f 11xquot2 g expxquot3 Plot using 33 points equally spaced between 0 and 1 Use red s for f and green s for g Label the horizontal and vertical axes Create a title including your name Create a legend Make sure the fonts are legible subplot If you wish to create a figure with two subfigures you can use the subplot func on subplot121 specifies 1 row and 2 columns of plots and requests the first plot subplot122 specifies 1 row and 2 columns of plots and requests the second plot x inspace0133 F sinpix subplot121 plotxF39r39 xlabel39x39 yabe39Fx39 G cospix subplot122 plotxG39b39 xlabel39x39 yabe39Gx39 subplot122 subplot121 05 04 tn u 2 4w 4 g 1 5 1 n UT t 1 1 1 8 PO A 2 D 2 An B 8 1 U U n D n 3 n 3 Bo W 15 n n U 1 g 8 7 E 3 2 1 U U U U U U U U 14 Plotting twodimensional data 1 Create two vectors x1d and y1d with 20 entries from 00 to 10 2 Create matrices of values using the x1d and y1d to distribute points in the unit square with 20 points in the x and y directions v 3 Plot results in a graph 0 MATLAB Command Window Eiie Edit window eip HE D ixaaainiatai x1d linspace0120 y1d linspace0120 x2dy2d meshgridx1dy1d plotx2dy2d3939 i 16 plotx2dy2d39 x1 d linspace O O 1 1 y1d linspace 2O 2O x2dy2d meshgridx1dy1d39 D gt7 t3 77v 77 r r 77vv Ewe gun rmw H w w v I w a o 0 m m E U D m U D 0 M i E K The Plot A surface plot a MATLAB Command Window IE EHe gun wwndow e p l I DiMaaaA atg D eldn mndw ep x1d linspace 10 10 40 J y1d linspace 10 10 40 x2d y2d meshgridx1dy1d f2d exp5x2dquot2 y2dquot2 surfx2dy2df2d Smoothing the Surface MATLAB Command Window EEI Bie Edn lndow Help F N 1 X maximaawmtgw DIS 0 EE x1d linspace 10 10 40 d y1d linspace 10 10 40 x2d y2d meshgridx1 dy1 d f2d exp 5x2dquot2 y2d 2 surfx2dy2df2d shading interp A Contour Plot o MATLAB Command Window HE He Edwt Wmdow He p mFiu39 391 HE Dim E f n kg 2 EC gm A ndow D p x1d linspace0120 d j y1 d linspace0120 x2dy2d meshgridx1dy1d 07 f2d exp5x2dquot2y2dquot2 M contourx2dy2df2d10 05 if j U4 if 3 A r MAICS 375 Spring 2009 Lecture 1a Introduction to MATLAB Some Basics Ref Appendix B MATLAB Tutorial MATHCS 375 Goals To learn how to effectively use compu tational methods together with the state oftheart software package MATLAB to solve problems in applied mathe matics and the sciences and To learn something about the design and analysis of these methods How To Start Matlab Under windows Click on the Start menu button Click on the Matlab menu entry Or Click on desktop icon Under linux Use SSH to log onto linuxunmedu Type Matlab in general you will interact in a text environment Overview of MATLAB Windows Mrme exla g 7 Elmr14 1n34 m 7 g I39m 1 a Classxnmn mmquot m lnslxucllnnal Ilse nnly Reseaxch and cmnnexclal use 1 mnmhnm Tn yet stalled select MATLAB 1112 at Dunn fxnm the Help mum Matlab Variables In Matlab variables are not declared by the user but are created on a needto use basis by a memory manager Moreover from MATLAB s point of view every simple variable is a complex matrix indexed from unity Scalars are 1x1 matrices A Simple Problem plotting a func on Suppose we want to plot the function fx sin27r x on the interval 0 1 To do this Set up a vector of xvalues O x1 lt x2 lt lt xn 1 Evaluate the function at these xvalues yk fxk k 1 2 n Display a plot connecting the points x1 y1 xn yn by a polygonal line
Are you sure you want to buy this material for
You're already Subscribed!
Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'