+ All Categories
Home > Documents > First Course in Scientific Computing Table of...

First Course in Scientific Computing Table of...

Date post: 24-Jun-2020
Category:
Upload: others
View: 1 times
Download: 0 times
Share this document with a friend
227
First Course in Scientific Computing Table of Contents Open Math1.nb A FIRST COURSE IN SCIENTIFIC COMPUTING Symbolic, Graphical, and Numeric Problem Solving Using Maple, Java, Mathematica, and Fortran Preface Acknowledgements Open Math1.nb C h a p t e r 1: Introduction 1.1 Nature of Scientific Computing 1.2 Instructional Guide 1.3 Excercises to Come Back to Open Math2.nb C h a p t e r 2: Getting Started With M a t h e m a t i c a Landau, First Course in Scientific Computing 1 Copyright 2005: Princeton Univ Press, RH Landau
Transcript
Page 1: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

First Course in Scientific Computing Table of Contents

Open Math1.nb

A FIRST COURSE IN SCIENTIFIC COMPUTING Symbolic, Graphical, and Numeric Problem Solving Using

Maple, Java, Mathematica, and Fortran

Preface

Acknowledgements

Open Math1.nb

Chapter 1: Introduction

1.1 Nature of Scientific Computing1.2 Instructional Guide1.3 Excercises to Come Back to

Open Math2.nb

Chapter 2: Getting Started With Mathematica

Landau, First Course in Scientific Computing 1

Copyright 2005: Princeton Univ Press, RH Landau

Page 2: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

2.1 Setting Up Your Workspace2.2 Mathematica's Problem Solving Environment

2.2.1 Look Around and Smell the Roses2.2.2 Try it, you'll like it!

2.3 Mathematica's Command Structure

2.3.1 Mathematica as a Pocket Calculator2.2.2 Rules of Precedence

2.4 Sums, Strings and Quotes

2.4.1 Strings and Quotes:

2.5 More on Cells2.6 Key Words and Concepts2.7 Supplementary Exercises

Open Math3.nb

Chapter 3: Numbers, Expressions, Functions; Rocket Golf Near Light Speed

3.1 Problem: Viewing Golf from a Rocket3.2 Theory: Einstein's Special Relativity3.3 Math: Integer, Rational, and Irrational Numbers3.4 CS: Floating Point Numbers

3.4.1 Powers of 10

3.5 Complex Numbers3.6 Expressions

3.6.2 Exercise (how expressions are stored)

3.7 Assignment Statements 3.8 Equality3.9 Functions

3.9.1 Built-in Functions

3.10 User-Defined Functions

3.10.1 Special Case: Defining functions with =

2 Landau, First Course in Scientific Computing

©1988-2002 Wolfram Research, Inc. All rights reserved.

Page 3: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

3.11 Reexpressing Answers

3.11.1 Simplifying Examples3.11.2 Expressions Behaving like Functions

3.12 CS: Overflow, Underflow and Round-Off Error3.13 Solution: Viewing Rocket Golf3.14 Tachyons*3.15 Key Words and Concepts3.16 Supplementary Exercises

Open Math4.nb

Chapter 4: Visualization, Abstract Data Types; Electric Fields

4.1 Why Visualization?4.2 Problem: Stable Points in Electric Fields4.3 Theory: Stability Criteria for Potential Energy4.4 Basic 2-D Plots: Plot

4.4.1 Loading Graphics Package4.4.2 Labels and Titles (the plot thickens)

4.5 Compound (Abstract) Data Types, [..] and ..

4.5.1 Several Curves on One Plot4.5.2 Customizing Colors and Line Types4.5.3 Legends4.5.4 Other Options

4.6 3D (Surface) Plots of Analytic Functions

4.6.1 Contours and Equipotential Surfaces

4.7 Solution: Dipole and Quadrupole Fields4.8 Exploration: The Tripole4.9 Extension: Yet More Plot Types

4.9.1 2-D Animations4.9.2 3-D Animation4.9.3 Phase Space (Parametric Plots)4.9.4 Vector Fields: PlotVectorField 4.9.5 Energy Conservation and Implicit Plots4.9.6 Polar Plots4.9.7 Surface Plots of Complex Functions*

Landau, First Course in Scientific Computing 3

Copyright 2005: Princeton Univ Press, RH Landau

Page 4: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

4.9.8 Plotting Lists with ListPlot4.9.9 Creating Simple Figures: Graphics and Show4.9.10 Plotting Vectors: Arrow*

4.10 Visualizing Numerical Data

4.10.1 2-D Plots of Data4.10.2, 3 Numerical Plots: ListPlot (scatterplot)4.10.4 Numerical Plots: Histograms4.10.5 Surface Plots of Data: ListPlot3D4.10.6 ListPlot3D

4.11 Plotting a Matrix: ListPlot3D4.12 Animations of Data*4.13 Key Words and Concepts4.14 Further Exercises

Open Math5.nb

Chapter 5: Solving Equations, Differention; Towers

5.1 Problem: Maximum Height of a Building5.2 Model: Stacking Blocks

5.2.1 Model Problem

5.3 Math: Equations as Challenges5.4 Solution of a Single Equation: Solve

5.4.1 Verify Solution: The / . Replacement Operator5.4.2 Symbolic Solution: Roots5.4.3 Numerical Solution: NSolve and FindRoot

5.5 Solving Simultaneous Equations (Sets)

5.5.1 Algebraic5.5.2 Numeric, Linear5.5.3 Nonlinear Equations

5.6 Solution to Tower Problem5.7 Differentiation: Limit, D, Derivative, Dt

5.7.1 Derivative of Expression: D5.7.2 Second and Partial Derivative: D5.7.3 Derivatives as Functions: Derivative

4 Landau, First Course in Scientific Computing

©1988-2002 Wolfram Research, Inc. All rights reserved.

Page 5: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

5.7.4 Second and Partial Derivative: Derivative5.7.5 Inert Forms: Hold and ReleaseHold

5.8 Numerical Derivatives5.9 Alternate Solution: Maximum Tower Height5.10 Assessment & Exploration5.11 Auxiliary Problem: Nonlinear Oscillations5.12 Key Words and Concepts5.13 Supplementary Exercises

Open Math6.nb

Chapter 6: Integration; Power & Energy Usage (14 too)

6.1 Problem: Power and Energy Usage6.2 Problem: Empirical Model6.3 Theory: Power and Energy Definitions6.4 Mathematica: Tools for Integration

6.4.1 Indefinite Integration6.4.2 Definite Integration6.4.3 Integrals as Functions

6.5 Problem Solution: Energy from Power

6.5.1 Your Solution to Model 2

6.6 Key Words and Concepts6.7 Supplementary Exercises

Open Math7.nb

Chapter 7: Matrices and Vectors; Rotations

7.1 Problem: Rigid-Body Rotations7.2 Math: Vectors and Matrices

7.2.1 Vector Operations and Matrices

7.3 Theory: Angular Momentum Dynamics7.4 Mathematica: Linear Algebra Tools

Landau, First Course in Scientific Computing 5

Copyright 2005: Princeton Univ Press, RH Landau

Page 6: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

7.4.1 Defining Matrices and Vectors7.4.2 Column and Row Vectors7.4.3 Arrays

7.5 Matrix Arithmetic and Operations

7.5.1 Multiplication7.5.2 Other Matrix Operations7.5.3 Vector Operations7.5.5 Vector Calculus*7.5.5 Eigenvalues and Eigenvectors*7.5.7 Solution of Linear Equations*

7.6 Solution: Rotating Rigid Body

7.6.1 Visualization of Vectors with Arrow3D7.6.2 Moment of Inertia for Barbell

7.7 Exploration: Principal Axes of Rotation*7.8 Key Words and Concepts7.9 Supplementary Exercises

Open Math8.nb

Chapter 8: Searching, Programming; Dipsticks

8.4 Mathematica Tools: Programming

8.4.1 Logic8.4.2 Flow Control8.4.3 Looping8.4.3.1 while loop8.4.4 Modules (Methods, Multi-line Functions)8.4.5 Conversion of Modules to Compiled Code

8.5 Solution: Volume from Dipstick Height8.6 Key Words and Concepts8.7 Supplementary Exercises

Open Math15.nb

Chapter 15: Differential Equations with Java & Mathematica

15.6 Mathematica: Differential Equations Tools

6 Landau, First Course in Scientific Computing

©1988-2002 Wolfram Research, Inc. All rights reserved.

Page 7: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

15.6.1,2 Plot Solution: Replacement Rule & Evaluate15.6.3 System of ODE's

15.7 Mathematica Solution: Drag a v15.8 Extractring Operands for Plotting

15.8.1 Solution for R and T

15.9 Drag a v2

15.10 Drag a vI 3ÄÄÄÄ2 M15.12 Key Words15.13 Supplementary Exercises

Open Math16.nb

Chapter 16: Object Oriented Programming; Complex Numbers

16.6 Mathematica Solution: Complex Currents

16.6.1 Mathematica's Surface Plots of Complex Impedance

Open MathB.nb

Appendix B: Mathematica Quick Reference

Basic Operations & Representations Sums, Products, Strings, PrintoutStatements, Expressions & FunctionsSolving EquationsSimultaneous EquationsPlotting Along

Plotting Data (see too Chapter 4)

Calculus

Differentiation IntegrationDifferential Equations

Linear Algebra

Defining Matrices &Vectors

Landau, First Course in Scientific Computing 7

Copyright 2005: Princeton Univ Press, RH Landau

Page 8: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

Matrix Operations Eigenvalues, Eigenvectors, Linear Equations Generating Fortran & C Code Mathematica standard Library Functions Mathematica Packages

8 Landau, First Course in Scientific Computing

©1988-2002 Wolfram Research, Inc. All rights reserved.

Page 9: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

c:1

A FIRST COURSE IN SCIENTIFIC

COMPUTING

Symbolic, Graphical, and Numeric

Problem Solving Using Maple, Java,

Mathematica, and Fortran

RUBIN H LANDAUOregon State University

Coauthors: Robyn Wangberg (Mathematica) Kyle Augustson (Fortran)

Contributors: Manuel J. Paez, Cristian C. Bordeianu,Connelly Barnes, David H. McIntyre

c:2

Preface

This book contains an introduction to scientific computing appropriate for all lower-division college students. Its goal is to make students comfortable using computers to do science, and to provide them with tools and knowledge they can utilize throughout their college careers. Its approach is to introduce the requisite mathematics and computer science in the course of solving realistic problems. On that account care is given to indicate how the each discipline uses its own language to describe the same concept, how their tools are useful to us, and how computations are often concrete examples of abstract ideas.

This is easier said than done.On the one hand, lower-division students are simultaneously learning elementary mathematics and physics, and so this may be the first place they encounter the science and mathematics used in the

Copyright: Princeton Univ Press, RH Landau, 2005

Page 10: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

problems. On the other hand, in order for the tools and techniques to be useful for more than the assigned problem, we give More than an Introduction (an alternate title to this book) to the computational tools. We address the first issue in our teaching by reminding the students that our focus is on having them learn the techniques in the proper context, and that any new science and mathematics they become familiar with will make it easier for them in their other courses. We address the second issue by placing an asterisk * in the title of chapters and sections containing optional materials, and by reminding the students of which sections are most appropriate for the problem at hand.

This book covers the basics of computation, numerical analysis, and programming from a Computational Science point of view. We want the reader to acquire some ideas of what is possible with computers, what type of tools there are for it, and how to go about getting all the pieces to work together. After that, it is easy to use on-line help or the references to get more details. As a result, our presentation is more practical and more focused on mathematics and science than an Introductory Programming or Computer Science text, with minimal discussion of Computer Science theory. The book follows our own personal preference for ``just enough'' computer information in that it avoids going through every option for every command, and instead presents realistic examples.

We follow the dictum that science and engineering students learn computing best while sitting down at a computer in a trial-and-error mode. Hence, we adopt a tutorial approach in which the reader works along with us in solving a problem, learns by doing, and then works on their own version of the problem (there are also additional exercises at the end of each chapter). We use the command-line mode for the compiled languages that makes the tutorial as universal as possible, and, we believe, is better pedagogically. It then follows that this book is closer to a workbook than a reference book. Yet because one always comes back to find worked examples of commands, it should be valuable for reference as well.

A problem solving environment such as Maple or Mathematica is probably the easiest way to start scientific comput­ing, is natural to use with trial and error, and is what we do in Part I. Its graphical interface is friendly, it shows the user a wide spectrum of what can be done with modern computation, such as symbolic manipulations, 2-D, 3-D visualization and linear algebra, and is immediately useful in other courses and for writing technical reports. After the first week with Maple or Mathematica, students with computer fright usually feel better. These environments also demonstrate how computers can give an immediate response in beautiful mathematical notation, or fail at what should be the simplest of tasks.

Part II of the text is on Java (or Fortran). We believe that learning to program in a compiled language teaches more of the basics of computation, gets closer to the actual algorithms used, teaches better the importance of logic, and opens up a broader range of technical opportunities (jobs) for the students than the use of a problem solving environment. In addition, compiled languages also tend to be more powerful and flexible for numerically-intensive tasks, and students naturally move to them for specialized projects. Likewise, after covering Parts I and II of the text it may make sense for a student to use environments like Matlab, which combine elements of both compiled languages and problem solving environments.

Many students may find the logic and precision of language required in programming more challenging than any­thing they have ever faced before. Others find programming satisfying and a natural complement to their study of mathematics and foreign languages. We try to decrease the slope of the learning curve by starting the neophytes with sample programs to run and modify, rather than requiring them to write all their own programs from scratch. This process more exciting, saves a great deal of time otherwise spent in frustrating debugging, and helps students learn by example.

Even though it might not be evident from all the hype about the Java and Web computing, Java is actually a good language for beginning science students. It demands proper syntax, produces useful error messages, is consistent and intelligent in its handling of precision, goes a long way towards being computer-system independent, has free pro­gram development environments available from Sun Microsystems [SunJ], and runs fast enough for nonindustrial purposes (its speed is increasing, as are the number of scientific subroutine libraries being developed in Java).

Part III of the text provides a short LaTeX Survival Guide. A number of colleagues have suggested the need for such materials, and since using LaTeX is quite similar to compiling a code, it does make an a useful extension of the text.

2 Landau, First Course in Scientific Computing

Page 11: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

Even though we do not try to reveal the full power and complexity of LaTeX, we do give enough of its basic elements for the reader to write beautiful-looking scientific documents.

Depending on how many chapters and modules are used, this book contains enough materials for a one or two semes­ter course. Our course has one lecture and two labs every week, with roughly one instructor for every 10 students in lab. Attending lecture and reading the materials before lab are important in acquainting the students with the general concepts behind the exercises and in providing a broad picture of what we are trying to do. The supervised lab is where the real learning occurs.

We believe that a modern student should be acquainted with at least two approaches to scientific computing. Notwith­standing our avowed claim that there are multiple paths leading to good scientific computing, we have had to make some choices as to what to place in the printed version of this book, and what to place on the CD. The basic ideas behind scientific computing may be independent of language, yet the details are not. For all these reasons we have decided to cover Maple, Java, and LaTeX in the printed version of this book, but to place other languages on the CD that comes with the text.

The CD contains Java programs, LaTeX files, data files, and other supplementary materials. As indicated, it also contains Maple worksheets with essentially identical materials as in the Maple section of the text, but in an interac­tive format that we recommend over reading the paper version. Furthermore, the CD contains essentially identical materials to the Maple tutorials as Mathematica notebooks. These can be read with Mathematica or printed out as an alternative version of the text. Likewise, the CD also contains the Java materials of the text converted over to Fortran90, as well as the appropriate Fortran programs. Though we do not recommend trying to learn two languages simultaneously, having alternative versions of the text does present some interesting teaching possibilities. Additions and corrections to the CD are found on our Web pages.

c:3

Acknowledgements

This book was developed on seven year's worth of students in the Introductory Scientific Computing Class at Oregon State University. The course has been taught by Albert Stetz and David McIntyre, in addition to the author, and some of their materials have been incorporated as well. I have also been blessed with some excellent graduate and undergrad­uate student assistants without whose efforts the course could not be taught and the materials developed. These include Matt Des Voigne, Robyn Wangberg (who did the Mathematica conversions), Kyle Augustson (who helped with the code listings and the Fortran90 conversion), Connelly Barnes (who helped with PtPlot, the Advanced Objects chapter, and Fortran90 conversions), and Juan Vanegas. The course was motivated by the pioneering text by Zachary [Zach 96] and the support of UCES [UCES]. Financial support for our project and all these good people came from the National Science Foundation's Course, Curriculum, and Laboratory Improvement (CCLI) Program under the guidance of Duncan McBride, and the National Partnership for Advanced Computational Infrastructure-EOT.

Valuable materials and invaluable friendships have also been contributed by my coauthors on ourComputational Physics text, Manuel Pa?ez and Cristian Bordeianu. They have helped make this book More than the Introduction that it would have been otherwise. I look forward to their continued collaborations. Likewise, I would still remain grateful to my wife Jan for her reliable and loving support and encouragement, even if she had not helped with the proofread­ing this time.

Financial support for developing our degree program in Computational Physics and its curricular materials come from National Science Foundation's Course, Curriculum, and Laboratory Improvement program under Duncan

Landau, First Course in Scientific Computing 3

Copyright: Princeton Univ Press, RH Landau, 2005

Page 12: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

McBride, and the Education, Outreach and Training Thrust area of the National Partnership for Computational Infrastructure. As part of that support, the courses and materials have benefited from formative and summative assessments by Julie Foertsch of the LEAD Center of the University of Wisconsin. This work has also benefits from formative comments by various reviewers and colleagues, in particular Jan Tobochnik and David Cook. Thanks also goes to my editor, Vickie Kearn at Princeton University Press, who has been particularly insightful, encouraging, and courageous in helping me develop this multidisciplinary text, and having it turn out so well.

RHL

c:4

Chapter 1: Introduction

c:5

1.1 Nature of Scientific Computing

Computational scientists solve tomorrow's problems with yesterday's computers; computer scien­tists seem to do it the other way around. [Press 94]

Fig. 1.1 A view of computational science as a multidisciplinary field that combines a science with computer science and mathematics.

The goal of scientific computing is problem solving. The computer is needed for this because real-world problems are often too difficult or complex for analytic or human solution, yet workable with the computer. When done right, the use of a computer does not replace our intellect, but rather leverages it by providing a super-calculating machine or a virtual laboratory so that we can do things that were heretofore impossible.

The mathematical modelling and problem-solving orientation of scientific computing places it in the discipline of Computational Science. In contrast, Computer Science, which studies computers for their own intrinsic interest, provides the underpinning for the development of the hardware and software tools that computational scientists use. As illustrated in Fig. 1.1, Computational Science is a multidisciplinary field that combines a traditional discipline, such as physics or finance, with computer science and mathematics, without ignoring the rigor of each. Books such as this, which employs materials from multiple fields, aim to be the central bridge in Fig. 1.1, connecting and drawing together the three fields.

Studying a multidisciplinary field is challenging. Not only must you learn more than one discipline, you must also work with the separate styles and languages of the different disciplines. To illustrate, a computational scientist may be pleased with a particular solution because it is reliable, self-explanatory, and easy to run on different computers without modification. A computer scientist may view this same solution as lengthy, inelegant, and old-fashioned. Each may be right in the sense that they are making judgement based on the differing values of different disciplines.

4 Landau, First Course in Scientific Computing

Page 13: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

c:6

1.2 Instructional Guide

Landau's Rules of Education: Much of the educational philosophy applied in this book is summarized by these three rules:

1. Most of education is learning what the words mean; the concepts are usually quite simple once you under­stand what you are being told.

2. Confusion is the first step to understanding.

3. Traumatic experiences tend to be the most educational ones.

This book has an attitude and we hope you will develop one too! First of all, we enjoy computing and relish the increased creativity and productivity resulting from powerful computing tools. Secondly, we believe that computing has become so much a part of the fabric of science that an Introductory Scientific Computing course should be part of every lower-division university student's education. Hence we deliberately mix the languages of mathematics, science, and computer science. This mix of languages is how modern scientists think about things, and since ideas must be communicated with these same words and ideas, this is how the book is written. However, we are sensitive to the confusion multiple definitions may reap, and do provide a section at the end of each chapter indicating some key words and concepts, and a glossary at the end of the book defining many technical terms and jargon.

Because we aim to give an introduction to computational science, we cover some basics of numerical analysis, informa­tion about how data are stored, and the concordant limits of computation. However, we present very little discussion of hardware, computer architecture, and operating systems. That is not to say that these are not interesting and important topics, but rather that we want to get the reader busy computing and acquiring familiarity with concrete examples. In our experience, science and engineering students need this practical experience before they can appreci­ate the more abstract principles of Computer Science.

We have aimed our presentation at first and second year college students. We believe that the chapters and sections not marked optional with an asterisk * provides a good introductory course for them. The inclusion of the optional chapters would raise of the level of the presentation and lead to a longer course. To maintain the logical organization of materials, we have intermixed the optional chapters with the others. However, there should be nothing in the optional chapters that is required in order to understand the chapters that follow.

It is hard to keep up with the rapid changes in computer technology and with the knowledge of how to use them. That is not an issue when learning scientific computing because it is the basic principles of mathematics, logic, science and computing that are important, and not the details of hardware and software. Nevertheless, students and faculty often do not enjoy computing because of the frustration and helplessness they feel when computers do not work the way they should. Although we commiserate with those feelings, one of the things we try to teach is that it is not unusual to have new things not work quite right, but that if you relax and follow a trial-and-error approach, then you usually find success working around them.

Be warned, there are some exercises in this book that give the wrong answer, that lead to error messages, or that may ``break'' the program (but not harm the computer). Learning to cope with the limits of computation gets easier and less traumatic after you have done it a few times. We understand, however, that many instructors may not appreciate a

Landau, First Course in Scientific Computing 5

Copyright: Princeton Univ Press, RH Landau, 2005

Page 14: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

computer's failure that they cannot explain, and so we have assembled an Instructor's Survival Guide, available upon request.

It is important that the student become familiar with the material in the text before they come to lab. A lecture helps, but reading and working through the materials is essential. Even though it may not be that hard to work through the problems in lab by having instructors and fellow students prompt you with the appropriate commands to enter, there is little to be gained from that. Our goal to make this introductory experience very much a ``lab'' that develops an attitude of experimentation and discovery, and which nurtures rewarding feelings when a project finally computes correctly.

Many of the Problems we assign require numerical solution and therefore are not covered in elementary texts. These include the behavior of nonlinear oscillators, the motion of projectiles with drag, and the rotation of cubes about an arbitrary axis. Notwithstanding our prediction that other elementary courses and texts will eventually be more multidis­ciplinary, some readers may feel that we are requiring them to understand phenomena at a level higher than in their other courses. Our hope is that the readers will recognize that they are pioneers, will be stimulated by their new-found powers, and will help modernize their other courses.

On the technical side, we have developed the materials with Maple 6--9.5, Mathematica 4.2, and the Java Develop­ment Kit (JDK or Java 2 Standard Edition, J2SE) [SunJ]. Even though studio and workbench environments are available, we prefer the pedagogical value in using a shell to issue separate commands for compilation and execu­tion, and then having to deal with the source and class files directly. In addition, many students are able to load JDK onto their home computers and work there as well.

We have found that WinEdt and TextPad works well to edit and run source code on a Windows platform, and that Xemacs with Java tools is excellent for Unix/Linux machines. In addition, jEdit, the Open Source programmer's editor, is an excellent tool that, because it itself is written in Java, runs on most any platform. Visualization is very important in computational science. It is built into Maple and Mathematica, and is excellent. Part of the power of Java is that it has strong graphical capabilities built right into the language, although calling them is somewhat involved. Consequently, we have adopted the free, open source package PtPlot as our standard approach to plotting with Java. For 3D graphics, a more specialized application, we give instructions on using gnuplot, and refer the interested reader to OpenDx and VisAd. These too are free, powerful, and available for Unix/linux and Windows computers.

c:7

1.3 Exercises to Come Back to

Consider the following list of problems to which a computational approach could be applied. Indicate with an ``M'', ``J'', or ``E'', whether the best approach would be the use of Maple, Java, or Either.

1. calculate the escape velocity from Jupiter

2. write a spreadsheet (accounting) program from scratch

3. solve problems from a calculus textbook

4. prove an algebraic identity

5. determine the time required for a sky diver to reach terminal velocity

6 Landau, First Course in Scientific Computing

Page 15: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

6. write a compiler for a programming language

Landau, First Course in Scientific Computing 7

Copyright: Princeton Univ Press, RH Landau, 2005

Page 16: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

c:1

Chapter 2: Getting Started With Mathematica

c:2

2.1 Setting Up Your Workspace

An important part of scientific computing is being organized. Good organization provides you with more time for the important things like being original and creative in your work, as well as giving you more time to get your work done (or to play). This is particularly true for scientific computing where you may have to deal with many files or many versions of the same file. For students, good organization also keeps you from getting distracted on task.

An important step in organization is knowing where you have stored things (this is probably true for other parts of your life as well). One of the best ways to get organized is to create files in directories and subdirectories (also called folders and subfolders). You need to be able to navigate through your directories, see your files, and tell what's in them by their names. In addition, you need to be able to create, copy, move, and remove files and directories. Finally, you should protect your files from accidental or unintentional intrusions. For whatever operating system you are using, try out and get familiar with the commands to:

- list the names of all files and directories in the present directory

- list the names with details of all files and directories in the directory in which you are working

- display the name of the directory in which you are working

- make (create) a directory named dirname

- copy file1 to file2 and then delete file1

- copy file1 to directory dirname and then delete present file1

- copy file1 to file2 leaving a copy of file1

To get started:

- Create a subdirectory Intro in your home directory

- Create subdirectories Week1, Week2, ... Week10 within directory Intro

- Change to the subdirectory Week1 and use it for this week's work.

Landau, First Course in Scientific Computing 8

Copyright: Princeton Univ Press, RH Landau, 2005

Page 17: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

c:3

2.2 Mathematica's Problem Solving Environment

Mathematica is an example of what a computer scientist would call a Problem Solving Environment. You can view it as a (fairly) complete computer system (a really big program) that does nearly everything you need for mathematical calculations, and does it within an intuitive graphical user interface. Mathematica and its cousin, Maple, extend scientific computations from dealing with numbers to also manipulating algebraic symbols. While problem solving environments can be used for numerical calculations as well, compiled languages are faster and more flexible. (Mat-lab, while also called a problem solving environment by some, is predominantly a friendly interface for doing numeri-cal calculations. It is often used for high-powered design, simulation, and data analysis.)

àc:4

2.2.1 Look Around and Smell the Roses

Ideally, you are reading this document as a Mathematica Notebook (a file with the suffix .nb) within a Mathematica window. If not, we recommend that you do so or at least open up a Mathematica window to experiment with. To do so on a Unix/Linux operating system type mathematica & at a Unix prompt. On Windows go to the Start Menu.

- Look around the window and note how it has drop down menus and buttons that make it look very much like a word processor or text editor with which you may already be familiar. In fact, Mathematica was used to create this notebook.

- Pull down the menus and take note of the types of functions they perform.

- Before you get in too deep, note that the File menu has both Close and Exit as options. Close will terminate the Mathematica window that you are currently working on, while Exit will terminate the entire Mathemat-ica session.

One of the worst experiences of computing is losing a file containing all of your hard work. Note that even though you may have given the file a name, its contents do not get stored permanently unless you issue the Save or Save As command. Although Mathematica will usually ask if you want to save a file before discarding it, it is a good idea for you to explicitly save your file in the desired location before exiting or closing. You save a file with the File=>Save command (the Save command under the File pull-down menu). In fact, it's a good idea to save your file on a regular basis while working on it; then even if Mathematica crashes, you will not lose your work.

The Save As command under the File pull-down menu lets you change the format of the file as well as the loca-tion where it is to be stored. (Make sure you save your files in your personal directory if you ever want to find them again.)

Exercise: Okay, now try doing what you are told!

1. Save this work sheet to your home directory or some other folder.

2. Next, close this window and see what happens.

3. Now, exit Mathematica, start it again, and then return here to continue. Welcome back!!

9 Landau, First Course in Scientific Computing

Page 18: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

4. Open the Format menu and click on the Show Toolbar option if it does not have a check mark by it. The toolbar is handy to have visible while you are working, and helpful for this tutorial.

Observe next that there is an invaluable (well, maybe just valuable) Help menu at the rightmost end of the menu bar. Before you try it out be warned that the Help window may cover up this window. Yet you can get back to this screen by going to the Window pull-down menu, which will show you all the windows that you have open. You can then select this one, to place it on top.

5. Try out the Help facility and notice that there is a Help Browser where you can search for help on almost anything. You can also search within the Master Index, Mathematica Book, and Built-in Functions. On some versions there is also a Tutorial to help you get acquainted with Mathematica.

6. Try selecting (with your mouse) a word in the preceding text such as ``exit''. Then go to the Help menu and choose Find Selected Function. Go ahead and see what it says.

The Help Browser is immense and works like the index into a great book about Mathematica. You should be able to search for and find information on any questions you have with this program! In particular, the Getting Started/Demos option seems to be helpful with walking through some of the basics. Don't let the complexity of the Help Browser scare you, after you use it a couple times you'll be a pro and it may be one of your best resources.

7. Select (highlight) the above paragraph by dragging your mouse over it (holding down the left mouse button). Now try out the buttons that center the selected text, and that right- and left-justify it. Go to the Format pull-down menu and choose Face; you now can make the text bold (Ctrl+b), italic (Ctrl+i), or underlined (Ctrl+u). Likewise you can select text and change the Font, Size, Text Color, and Background Color.

While we are talking about what Mathematica can do with text, and before you start doing math in a notebook, it's a good idea to explain what notebooks are and how you do computations in them. Notebooks are interactive documents organized into a sequence of cells. Each cell may contain material of various types, such as text, graphics, titles, or Mathematica expressions (commands). The cells are indicated by blue brackets on the right side of the screen, and may contain subcells, sub-subcells and so on. Each cell within the notebook is assigned a style which indicates its role within the notebook. The current cell you are reading is in Text style (indicated in the handy toolbar at the top of the notebook) while commands you want Mathematica to execute will be in an Input style cell. The front end (user interface otherwise known as a notebook) of the Mathematica program allows you to modify properties of the cells or materials within the cells.

Groups of cells are used to represent sections, subsections, and execution groups in notebooks. The extent of the group of cells in indicated by a bracket on the far right, so groups of cells are indicated by nested brackets. A group of cells can be either open or closed. When it is open, all the material in the cells is viewable, but when it is closed, only the first cell, or heading cell of the group is visible. Many large notebooks start with a group of closed cells, so that all you see is an outline of the contents (like the rest of the sections below in this notebook). A closed group has a bracket with an arrow at the bottom, and you double click on this bracket to open the group of cells. When you are done reading and want to close the group, you double click on the bracket spanning the group so that only the first cell is visible. The largest bracket (to the far right) encloses all the sections of the chapter. Try double clicking on this now so that you are just left with the Chapter 2 title. To open the chapter, double click on the bracket with the arrow. Now continue through the document, opening and closing groups of cells containing sections and subsections as need be.

àc:5

2.2.2 Try it, you'll like it!

In a well-designed Mathematica notebook, or book for that matter, the section and subsection titles should form an outline of the material covered. This assists the learning process since looking at just the titles of the sections of a document helps map out your journey through the material. Try it with this document:

Try closing and then opening the window within Mathematica in which this text appears (this notebook). With a

Landau, First Course in Scientific Computing 10

Copyright: Princeton Univ Press, RH Landau, 2005

Page 19: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

Windows operating system, a window is closed by depressing the lower-most button on the upper-right side with the x in it. On a Unix/Linux system, a window is closed by pushing the lower-most button on the upper-left side with a - in it, and then selecting the Close option. You will then have to go to the File menu and select Open... , or select the name of this file if Mathematica was nice enough to write its name there.

Try minimizing (iconizing) and then maximizing the window within Mathematica in which this text appears. With a Windows operating system this is done by depressing the lower-most button on the upper-right side with an under-score, _ in it. On a Unix/Linux system this is done by pushing the lower-most button on the upper-right side with a center dot . in it. Then click the icon with the three-dimensional star on it to get the window back.

Finally, find the button that makes the window in which you are reading this text smaller or larger, but does not close or minimize the window. On a Windows machine that button has a single box or multiple overlapping boxes in it; on a Unix machine it is a depressed or raised (shaded) single box.

c:6

2.3 Mathematica's Command Structure

At last we will do some mathematics with Mathematica. First you need to open a new cell beneath this one by either opening the Input pull-down menu and choosing Start New Cell Below, or by moving the mouse downward until the cursor becomes horizontal and clicking the mouse button. A horizontal line will appear across the screen to mark the beginning of a new cell. When using the former method, the new cell will automatically be set to whatever style the current cell is (as seen in the toolbar), but for the latter an Input style cell will always be created. We want an Input style cell to be able to manipulate symbols and expressions. If it is not already an Input cell, highlight the new cell by clicking on the brace on the far right that represents the cell. Then choose Input style in the drop down menu in the tool bar, or go the Format menu, Style submenu, and choose Input. Now, tell Mathematica to add 3 + 82 and hit Shift+Enter or Shift+Return to evaluate the cell, depending on your computer system. Without the Shift you will just get a new line. Note that on systems with a numeric keypad on the far right, the Enter key on that keypad is equivalent to Shift+Enter on the keyboard. Mathematica evaluates your input and reveals the results in an Output cell immediately beneath. Your cursor can be anywhere in the Input cell when you hit Shift+Enter and the In[n]:= and Out[n]= line number labels are added automatically. Execute the following Input cell:

3 + 82

Notice that your command to Mathematica in the Input cell is automatically bold and is in fixed-width font, like a teletype. The teletype font is meant to evoke the aura of the simpler computing days of the past and to indicate that this is your command to the computer.

Notice next that Mathematica speaks back to you in the Output cell with teletype font that is not bold. If an Output cell does not appear, then you either suppressed the output or may have made a mistake and need to go back and edit the input, pressing Shift+Enter to re-evaluate the cell. If you press Enter by itself, you just go to a new line within the cell. Try this in the above Input cell (where you did the sum), as well as another simple sum.

If you make a mistake and enter input that Mathematica does not understand or like, then the program will give you an error message in blue text or sometimes beep at you. You will get a beep whenever you have made a system error and you can find out what it means by going to the Help menu and choosing the Why the Beep? option.

This is a text cell. Try to evaluate it.

11 Landau, First Course in Scientific Computing

Page 20: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In general, when you make a mistake, you can go back to the command you have already entered, correct it, and then hit Shift+Enter any place in the Input cell to execute the command again. The numbers in the In and Out labels will change, but that is okay. This is a lot better than trying to enter the entire command again, especially when the commands get complicated and you are annoyed with the computer and the slow pace of learning. (It is an often-experienced, but not fully-tested fact that computers seem to know when you are annoyed with them, and then really start giving you a hard time).

Note, to get the most out of this tutorial, you should personally key in the Mathematica commands rather than cut and paste them into an Input cell. A good way to enter commands is to go to the File menu and start a New window within Mathematica (you can have several windows open simultaneously).

Now we want to enter a new calculation on your worksheet directly after the Output cell of the previous calculation. Direct your cursor beneath the previous Output cell (containing 85), until it is horizontal and click. A new Input cell is ready to use!

à

c:7

2.3.1 Mathematica as a Pocket Calculator

Mathematica does everything a pocket calculator does, in much the same way, but only more so. It understands the usual arithmetic operators, + and - for addition and subtraction, uses * or a space for multiplication, / for division, and ^ for exponentiation (raising to a power). For example, 3 x 45 - 7^6 would be entered as either of the two statements below, where the first line uses * for multiplication and the second uses a space. Therefore, in Mathematica, spaces do matter. Here, an extra space could mean unwanted multiplication. Execute the following two commands by clicking in either Input cell and pressing Shift+Enter. See if you get -117514 for both commands.

In[1]:= 3∗45 − 7^6H∗ This field is a comment or note. It does not get executed ∗LOut[1]= −117514

[Note: A semicolon is not necessary at the end of an Input command in Mathematica, as it is in Maple. In fact, putting a semicolon at the end of an Input line prevents the output from being displayed.]

Notice how Mathematica produces two Output cells corresponding to the two lines in the Input cell. Try to get just one Output cell. Put a semicolon at the end of the first Input line above and then execute the Input cell. Mathematica should only return one output cell corresponding to the line without the semicolon. Notice how the line numbers of the Input and Output cells have been incremented sequentially. This allows you to keep track of the order in which the commands are evaluated. Just because one expression may appear earlier in your notebook does not mean that it will have been evaluated first. That is true only if it has a lower line number. Likewise, you can go back to an earlier part of your notebook and re-evaluate a previous Input cell.

àc:8

2.3.2 Rules of Precedence

When performing calculations like those above, it is important for Mathematica to know the order in which you want the various operations performed. The order of executions (also followed by most pocket calculators) is

^ then * or / then + or -

Even with this rule, there may be ambiguity. For example, let us say we want to add 4 to 2 and then multiply the sum by 3. Have Mathematica try this by evaluating the (ambiguous) expression 4+2*3:

Landau, First Course in Scientific Computing 12

Copyright: Princeton Univ Press, RH Landau, 2005

Page 21: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[2]:= 4 + 2∗ 3

Out[2]= 10

If you got the answer 10, then you did not do what we wanted! Clearly, this is a calculation where the order of opera-tions matters. Try (4+2) * 3, where the parentheses make our intentions clearer:

In[3]:= H4 + 2L∗3Out[3]= 18

You can always control grouping by explicitly using parentheses, and in Mathematica this is the only use of parenthe-ses. When parentheses are used, multiplication between adjacent groups of parentheses (or a single constant) is implied without a * because a space is automatically entered. Try the following:

In[4]:= H2 + 3L 3H2 + 3L∗3H2 + 3L 3@2 + 3D∗3Out[4]= 15Out[5]= 15Out[6]= 15

Syntax::sntxb : Expression cannot begin with "@2 + 3D∗3".@2 + 3D∗3

The first three expressions all give the same correct answer, while the expression with brackets produces an error. Brackets are used to indicate the arguments to functions or commands, while parentheses used to show groups within expressions. Without the parentheses around (2+3) you will not get 15 due to the rules of precedence. Take out all parentheses and brackets and re-evaluate the cell. What answers do you get now? Is it the same for all of them?

Next try 400/10/2 and explain your result. Since computers tend to do division from left to right (left associative), Mathematica knows what it is doing, but the result may not be obvious to you. See if 400/10/2 is the same as (400/10)/2 or 400/(10/2). Use the Input cell given below to evaluate all three commands at once:

13 Landau, First Course in Scientific Computing

Page 22: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[7]:= 400ê10ê2H400ê10Lê2400êH10ê2L

Out[7]= 20Out[8]= 20Out[9]= 80

Remember: if there is a chance that the results maybe ambiguous or unclear, use parentheses to force the operations you want and to ensure clarity.

c:9

2.4 Sums, Strings and Quotes

Many problems in science and mathematics require you to evaluate sums. Sometimes the sums are over a finite number of terms, and at other times the number of terms is infinite. With a little cleverness you can write a sum as a single expression. For example, here is an infinite sum, ‚

i=0

∞ H−1Li x2 iH2 iL!

The variable i is called the summation index and starts from 0 and runs all the way to infinity. Entering sums into Mathematica is done using the Sum command:

In[10]:= Sum@HH−1L^i ∗ x^H2∗iLLêH2∗iL!, 8i, 0, Infinity< DOut[10]= CosAè!!!!!!x2 E

Couldn't this be simplified more? It seems like a stupid answer that only a computer could think of. Let us see what Mathematica does with the Simplify and FullSimplify commands. They should take into account that cos(x) = cos(-x). Try entering these two commands on the last result generated in the Input cell below.

Landau, First Course in Scientific Computing 14

Copyright: Princeton Univ Press, RH Landau, 2005

Page 23: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[11]:= FullSimplify@%D H* Use % to retrieve the last result *LOut[11]= Cos@xD

If life is fair, you should have obtained Cos[x] as the value of the simplified sum. This means that Mathematica has recognized this infinite sum as the power-series expansion for cos(x). You can also use the palette of math symbols to create the sum in the Input cell and evaluate it to get the same answer. Pallets are opened from the menu under File. Try this below. It may take some time to figure out how to make it exactly like the expression above, but it's a great experience!

Take a close look at the Sum command we have used here. Like all Mathematica commands, it has a format that should be followed precisely. To begin with, note that the square brackets contains the arguments of the command. In this case there are two arguments separated by a comma. The first argument contains the expression to be summed, while the second field contains a list of three items describing the range of values covered by the summation index. The description of the range is in the form

i, imin, imax

where i is the summation index and imin and imax are the lower and upper limits of the range (in this case, imax = Infinity). Notice how in Mathematica the keyword for ¶ is Infinity, with an capital I (the language is case sensi-tive), and how the range is enclosed in curly braces. This is how Mathematica does lists, which we will define more precisely later. If you deviate from this format, Mathematica may tell you that you did something wrong with a blue error statement or an audible beep. It may also assume that you know what you are doing (Mathematica is good at doing math but not judging character), and make a reasonable attempt to follow your command. For example, try these:

In[21]:= Sum@H−1L^i ∗ x^H2∗iLêH2∗iL!, 8i, 0, infty< DIn[22]:= Sum@H−1L^i ∗ x^H2∗iLêH2∗iL!, 8i, 0, Infinity DIn[22]:= Sum@H−1L^i ∗ x^H2∗iLêH2∗iL!, 8i, Infinity <D

In the first case we had the wrong key word for ¶ and Mathematica evaluated the sum treating infty as if it were an algebraic symbol. In the second case, the closing curly brace for the range field was missing, and this led to the beep and blue error message. Observe how the command was reprinted in blue and underlined in red so that you know just what is not correct (somewhat like puppy training). In the third case, the minimum range limit was left off, and so Mathematica assumed the range started at 1, hence the result changed accordingly.

àc:10

2.4.1 Strings and Quotes:

A string is an ordered collection of characters that is treated as a literal sequence of characters with no inherent meaning or value. Simple strings are formed in Mathematica by placing characters within quotation marks, for example, "this is now a string". Variables can be assigned to strings and thus manipulated with Mathematica commands. For example:

In[12]:= strng = "George"H∗ Assign variable strng to "George" ∗LOut[12]= George

In[13]:= StringLength @strngDH∗ Returns number of characters ∗LOut[13]= 6

15 Landau, First Course in Scientific Computing

Page 24: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[15]:= StringReverse@strngDH∗ Reverses the characters ∗LOut[15]= egroeG

Here we used the name strng instead of string to avoid conflict with the Mathematica's reserved word String. There are many other neat commands in Mathematica to use with strings that you can find via the Help menu.

At times you may want Mathematica to produce output that has the expression to evaluate and the output of the expression on the same line. You do this with the Print command and the use of strings:

In[16]:= Print@"cosHPiL = ", Cos@PiDDH∗ Not obvious, but nice output ∗LcosHPiL = −1

The arguments of the Print command are expressions separated by commas. Print concatenates the output from each expression together ending with a line feed. The first expression in our case is a string, and so the characters are the output, whereas the second expression is a command, and the output is the evaluation of the command. We will occasion-ally use this Print command in the text to obtain nicely formatted output. Its downside is that you cannot use the % after a Print command to retrieve the previous output. You will notice that when the Print command is used, an Output cell is produced, but it does not have the signature Out[#] = at the left with the corresponding execution number.

c:11

2.5 More on Cells

In this tutorial we usually want you to observe the effect of each Mathematica command, or each group of commands, one at a time. Mathematica helps us with this because the kernel (the actual computer code behind Mathematica that does the calculations) evaluates a notebook on a cell-by-cell basis. For this reason many commands have their own Input cells and corresponding Output cells. For example, execute the following with the Shift+Enter keys:

In[17]:= [email protected][17]= 0.14112

Landau, First Course in Scientific Computing 16

Copyright: Princeton Univ Press, RH Landau, 2005

Page 25: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[18]:= Print@"sqrtH10.L = ", [email protected] = 3.16228

Notice an output cell (additional blue bracket on the right) has been produced, as well as a horizontal line beneath the Output cell.

Try entering text immediately after an Output cell. You should notice that an additional Input cell is created to contain your text. If you continue working like this, you will end up with multiple input and output cells, with Mathemat-ica executing one cell and then stopping at the next. While this is fine for studying the effect of individual commands, it is easier to get your work done if a bunch of commands are placed in a single Input cell to form an execution group. In order to place multiple commands in a single cell, enter Enter (or Return) after an input line to start another line in the cell, without the Shift. To execute the entire cell in one fell swoop, enter Shift+Enter.

If you would like the output to be suppressed from a line, place a semicolon ; at the end of the line. For example, as indicated by the blue lines on the right, the following Input cell contains two commands and results in two Output cells (also observe the little triangle used for input cells):

In[19]:= [email protected][19]= 0.14112

17 Landau, First Course in Scientific Computing

Page 26: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[20]:= [email protected][20]= 3.16228

Now, put a semicolon after the Sin command line, re-execute the cell, and observe that the output is suppressed.

Each Input cell, or execution group, may contain plots, spreadsheets, textual materials, or any combination of the lot. Only Input cells are evaluated by the kernel. Text cells (like this one with two lines at the top) are for descriptions. There are also cells for tiles, subtiles, pictures, and so forth. In this book we will try to keep our execution groups small in order to encourage you to study the consequence of each command. However, you can execute the entire notebook from top to bottom by going to Kernel=>Evaluation=>Evaluate Notebook. However, we suggest that you work through the chapters like tutorials, evaluating each group of commands as you read.

Sometimes you end up with a bunch of cells that would be better off joined together. For example, the preceding sentence up until the sentence ending with W should really be in one input cell. Combine or merge these cells by selecting the cell brackets (control +click) and click on

Cell=>Merge Cells. This will make the cells the same type. In general, you should only combine cells of the same type to maintain their functionality. Now that you have combined these three cells, split it up into two by going

to Cell=>Divide Cell. This divides the cell into two cells of the same type, the break being where the cursor is positioned. W

If this is the kind of thing you find interesting, you can find an entire submenu of Cell Grouping commands on the Cell menu. For example, you may keep your notebook neat by choosing to have the cells automatically grouped as you create them. However, if you decide later that you would like to connect cells to form an execution group, you will need to select Manual Grouping and then go about selecting the cells you wish to group or ungroup and choosing Cell Grouping=>Group Cells, or Ungroup Cells. You may also have noticed the Cell Properties submenu under the Cell menu. Explore these options. By default, all cells are Open and Editable.

c:12

2.6 Key Words and Concepts

sums arithmetic expression command strings cell closed cell on-line help precedence rules

1. Explain the meaning of these keywords.

2. Mathematics is often called the universal language of science. Evaluate this remark in the context of what Mathematica does.

3. What is the difference between a Mathematica Input cell and a Mathematica Output cell?

4. How does Mathematica differ from a pocket calculator?

5. How does the computer know the difference between a string and the name of a variable?

6. If computers at their heart understood only numbers, how can Mathematica understand algebraic symbols?

Landau, First Course in Scientific Computing 18

Copyright: Princeton Univ Press, RH Landau, 2005

Page 27: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

c:13

2.7 Supplementary Exercises

1. Use a Text style cell in Mathematica to write a notebook containing:

a. Your name

b. Your educational level

c. Your computer experience

d. What you would like to get out of this course (or book)

Convert your name into a bold font, your educational background into italics, and underline your experience. Note, it is a good habit to save your notebook often as you are working on it, and especially before trying to print it out. Sooner or later Mathematica will freeze up or quit on you, and lose track of the active notebook. That being the case, you will only have to make up the work since your last save.

2. Save your notebook as a file in the directory Intro and the subdirectory Week1. Do not close the notebook yet.

3. Print out this first notebook and hand it in. To do that, you may have to look at the page that comes up when you issue the print command, and pick the printer to which you want the output sent.

4. Use the Sum command to find a simple expression for the sum of the first n integers, 1 + 2 + ... n. You might want to experiment with the commands Simplify[%], FullSimplify[%], and Factor[%] to get a compact expression.

5. What is the ratio of (n+1)! to n!? How about (n+50)! to n!? What happens when you try to calculate the ratio of (n+m)! to n!? Use Simplify[%] and FullSimplify[%] to get a better idea of the result. Do you obtain what you expect to? Explain.

6. a) Make three different Input style cells, each having four lines. Have each line raise 2 to a power equal to the sum of the line number plus cell number.

b) Now enlarge each cell so that they contain an additional line for input.

c) Add comments of your choice to one of the execution groups.

7. Evaluate

a) Sin[Pi], Sin[pi], and Sin[PI], and explain

b) the natural logarithm of e, the base for natural logarithms

c) the natural logarithm of 10

d) the logarithm to the base 10 of 10

8. Explore two ways of accessing Mathematica's online help.

a) Use Mathematica to select the word help from the above line and then go to the Help menu on the Mathematica toolbar (in the upper right) and get help on help.

19 Landau, First Course in Scientific Computing

Page 28: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

b) Simply go to the Help menu and choose Help Browser.

9. Verify that the following infinite series equals pÅÅÅÅ4 .

1 −13 +

15 −

17 + − ...

10. Sum the following infinite series:

sin HxL +sin H3 xL

3 +sin H5 xL

5 + ...

Although you may not believe that Mathematica can do it, try evaluating the sum for arbitrary values of x. You should always get +/- π

4 .

11. Use the precedence and arithmetic rules of Mathematica predict the values of each of the following expressions

a) 2*3 + 4/2

b) 5 - 6 + 7^2

c) 1 - 2 ^ (3/4)

d) 8 / 4 / 2

12. Use the precedence and arithmetic rules of Mathematica to predict the values of each of the following expressions:

a) (4/2)*3 - 7^8 + 7^8 b) 10/14 c) 10./14

d) 8 / (4/2) e) 8 / 4 / 2 f) 6^1 g) 8 + 2 ^ 4 / 2

13. For the following inputs, what would Mathematica produce as output:

a) Sum[(-1)^i / (2*i)!, i, 1, 2]

b) Sum[(x)^i / (2*i)!, i, 1, 2]

Landau, First Course in Scientific Computing 20

Copyright: Princeton Univ Press, RH Landau, 2005

Page 29: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

c:1

Chapter 3: Numbers, Expressions, Functions; Rocket Golf

Near Light Speed

Note to Instructor: This problem, as stated, requires the same level of relativity as covered in elementary Physics texts, and is thus appropriate for first- or second-year college students. Even if the students do not understand the full implications of the equations we use, it is their application that is the point of this chapter. However, it is conceptually challenging to go further and ask about the golf ball's trajectory as viewed in different frames, as this involves the questions of simultaneity and acceleration in relativity.

c:2

3.1 Problem: Viewing Golf from a Rocket

Michele, a golf fanatic, would like to break the world's record for the fastest golf ball hit. Money being no object, she rents a rocket and hits her golf balls from the moving rocket. The rocket is fast, with a speed of c/2, where c is the speed of light (299 792 458 m/s). (This speed is really is fast considering that no object with mass can attain a velocity of c.) As indi-cated in Fig. 3.1, Michele hits her drive with a speed of U ' = c ëè!!!3 , at an angle q = 30 degrees, as she measures with respect to the moving rocket. She observes her drive to remain in the air for a hang time T' = 2.6 x 107 seconds (which is almost a year!). Ben, an observer on the earth, sees her rocket moving to the right with a velocity v = c/2, and this velocity somehow gets added to that of Michele's golf ball.

Problem: Inasmuch as some readers may not be familiar with special relativity, we do not expect you to solve this problem on your own, or even to understand all the equations. The theory of special relativity does have it subtleties and fine points, but it is accessible to beginning students and we will use only a few simple results. We will lead you through the solution for two cases, and then ask you to follow our steps for a third case. This leadership should give you a good working knowledge of some tools (the main focus of this chapter). The third case you work out is the interesting one in that round-off error arising from the use of floating-point numbers becomes evident. Usually it takes many computational steps before you see the effect of round-off error, but it this problem it arises fairly simply. Your explicit problem is:

1. How would Ben, watching Michele's drive from the earth, describe the golf ball in terms of its speed, angle f, and hang time T?

2. How would the answer to 1. change if Michele hit her ball to the left with the same inclination q, i.e, in a direc-tion opposite to the rocket's velocity?

3. How would the answer to 1. change if Michele hit her ball to the left at an angle 60o degrees below the horizon, that is, with q = 240o ?

4. If Michele hit the ball with a speed U = c, how would the answers change?

Landau, First Course in Scientific Computing 21

Copyright: Princeton Univ Press, RH Landau, 2005

Page 30: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

0.2 0.4 0.6 0.8 1x

-1

-0.5

0.5

1y Earth Frame O

0.2 0.4 0.6 0.8 1x'

0.5

1

1.5

2y'O' with velocity v, seei

Fig.2 Top: FrameO in which Ben is at rest.Right: FrameO' moving to the right with velocity v(horizontal arrow). The heavy arrow represents the ball velocityU' as seen by Michelle inO'.

22 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 31: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

c:3

3.2 Theory: Einstein's Special Relativity

Being told that an object is travelling with a velocity near that of the speed of light is a hint that the problem is not a simple mechanics one. Indeed, this means that we need to apply Einstein's special theory of relativity [Smith 65, Ser00] to it. As indicated in Fig. 3.1, we start by considering Ben in a reference frame O with axes (x,y) attached to the earth, and Michele in frame O' with axes (x',y') attached to the moving rocket. Relative to Ben, frame O' (the rocket) is moving along the positive x axis with uniform velocity v. Likewise, Michele feels herself at rest in the rocket, and sees Ben moving to the left with velocity -v. Both are equally correct and agree on their relative velocity; indeed, this is reason it is called the theory of relativity.

Ben and Michele may agree on their relative velocities, but they do not agree on measurements of times and distances. As an example, if Michele says that her golf ball was in the air for a period of time T', then Ben will say that the ball was in the air for a longer time

DT = g T' (time dilation),

where g is a function of relative velocity v that is always greater than 1:

g = 1ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅè!!!!!!!!!!!!!!!!!!1-v2êc2 > 1

In view of the fact that the speed of light c is so much larger than any velocities we normally encounter, g is usually very close to 1, and only gets large for exceedingly high velocities (normally restricted to elementary particles). The fact that Ben would measure a longer hang time than Michele is called time dilation, and is often described with the phrase ``moving clocks run slow''.

The additional result we need from special relativity relates the velocities seen by Michele and Ben. If Michele in the moving rocket O' sees her golf ball having velocity components U' = (Ux ' , Uy '), then Ben on earth O, will see her golf ball move with velocity components

Ux =Ux ' + v

1 + vUx'êc2 Uy =Uy '

γH1 + vUx'êc2Lwhere g is the same function as above. If you study the Ux equation, you will notice that the numerator describes the usual addition of relative velocities, while the denominator is the relativistic correction. In turn, the relativistic effects in Uy are in the numerator.

Landau, First Course in Scientific Computing 23

Copyright: Princeton Univ Press, RH Landau, 2005

Page 32: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

c:4

3.3 Math: Integer, Rational, and Irrational Numbers

There are different types of numbers that are used in mathematics and in computation. For example, there is a count-able infinity of positive integers 0, 1, 2, 3, ..., and nearly twice that many if we include the negative integers too. Mathematica stores these integers exactly and tries to retain infinite precision for its pure mathematical operations with them. Yet while a computer program may be smart, the computer is finite and sooner or later it will run out of room if we try to compute with very large numbers that are stored exactly. Accordingly, computers often store very large (and very small) number approximately using a floating-point representation. We shall discuss that soon.

Even though the number of integers is infinite, there is a yet larger infinity of rational numbers, that is, of numbers formed by the ratio of two integers, N/D. Mathematica stores these rational numbers exactly by storing the numerators and denominators as integers and then displaying a fraction rather than a bunch of digits. In the execution block below enter the operations

1/3, 4/2, 2485/3479, 3(1/3), 3[1/3].

and interpret Mathematica's response.

In[4]:= 1ê33@1ê3D

Out[4]=13

Out[5]= 3A 13E

What does the result of the last expression mean? (Hint: what are brackets [..] used for in Mathematica?)

There are also numbers in our world that cannot be expressed as the ratio of integers, and so would require an infinite number of digits to store. These are called irrational numbers and include numbers like p or ‰, the base of the natural logarithms. When Mathematica encounters irrational numbers, it usually uses the familiar symbol for them rather than approximating them by a fraction or a decimal. For example, see what happens when you ask Mathematica to use some of its built-in functions to determine the angle whose cosine is -1, or raise ‰ to the first power:

Note: Mathematica's built-in function names start with capital letters and square brackets are used for the arguments of functions. For example, cos-1H-1L :

In[6]:= ArcCos@−1DOut[6]= π

24 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 33: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[7]:= ^1

Out[7]=

These results are more than just pretty symbols. Mathematica knows symbols. There may well be a palette of common mathematical symbols on the right side of the screen when you first open the Mathematica program, called the Basic­Input palette. If you don't see the palette on your screen, open the Palettes menu under the File menu and choose BasicInput. You can also access other specialized palettes by using the Palettes menu. To insert a symbol into your command, you simply click on the desired symbol in the palette.

A useful symbol that does not appear in this palette is the percent sign %. Mathematica uses % to represents the result of the last calculation you did, whether it be in this notebook or another one you have open concurrently. Likewise, %% represents the next-to-last result. To try this out, go back to the previous two commands and add Input cells beneath the two Output cells containing Cos[%] and Log[%], and then start from the evaluation again starting at ArcCos[-1].

Mathematica actually knows a lot about a large number of functions. Some common ones are Log[x], Exp[x], Abs[x], Cos[x], Sin[x], Sqrt[x], ArcSin[x], and Cosh[x]. Other ones can be found via the Help menu and the Built-in Functions option, and are also given in an appendix.

Sometimes you may need to include p or ‰, or some other irrational, into one of your commands. The easiest thing to do is use the palette of symbols mentioned above. However, Mathematica also accepts expressions like Pi, PI, pi, e, or E as algebraic symbols. You can always define these symbols to be what you want (with techniques we'll get to shortly), but Mathematica has predefined many such symbols for general use. Here, we prompt you to experiment and deduce what Maple thinks of each using Cos[x] and Log[x]:

Landau, First Course in Scientific Computing 25

Copyright: Princeton Univ Press, RH Landau, 2005

Page 34: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[8]:= Cos@PiDCos@PIDCos@piDLog@eDLog@ED

Out[8]= −1

Out[9]= Cos@PIDOut[10]= Cos@piDOut[11]= Log@eDOut[12]= 1

You should have found that Cos[Pi] produces the expected answer since Mathematica recognizes Pi as the ratio of the circumference to the diameter of a circle. However, Cos[PI] and Cos[pi] are just echoed back because Mathematica doesn't know what values are associated with the algebraic symbols PI and pi. Similarly, Log[E] produces the expected output because Mathematica recognizes E as the base to the natural logarithms, it just interprets e as an algebraic symbol without a value. Notice how the symbol Mathematica uses for the base of the natural logarithms is a script ‰, (or E), and not just e. You can also obtain the ‰ symbol by pressing ``Esc ee Esc''. That is, escape followed by e and e, followed by escape.

c:5

3.4 CS: Floating Point Numbers

In spite of integers are neat to work with, there are limits to the kind of calculations possible with them. Occasionally you might want to see what the numerical value of an irrational number like p or Sin[1] really is, or a very large number (like the size of the universe), or you may need to know how much steel to buy in order to make a steel circle of circumference 2p. Numbers with decimal points are stored on the computer in a format known as floating point notation. This is similar to scientific or engineering notation of the form

mantissa x 2exponent

with the mantissa and exponent stored as separate words, and the 10 understood. The term "floating-point" denotes the idea that the decimal point moves around or "floats" during calculations in order to keep the number of digits in the mantissa constant.

One easy way to tell Mathematica that you want to do some work using floating point numbers ("floats") is to place a decimal point in one of the number of your calculation. If one of your numbers is a float, Mathematica will assume that you want the final answer to be a float as well. Mathematica assumes your input number is only accurate to a fixed number of decimal places and produces an approximate numerical result. To experience this in action, enter and observe Mathematica's response to each of the following:

26 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 35: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[13]:= 1ê31ê3.1.ê31.ê3.2 + 1.ê3.

Out[13]=13

Out[14]= 0.333333

Out[15]= 0.333333

Out[16]= 0.333333

Out[17]= 2.33333

The other way to get Mathematica to do a calculation using floats, or give an approximate numerical result, is to explicitly tell it to evaluate the expression numerically. This is done using the N[expr]command (the N means "numerical"), or entering expr//N (putting //f at the end of any expression means that f is applied to the expression):

In[18]:= N@1ê3D1ê3 êê N

Out[18]= 0.333333

Out[19]= 0.333333

If you count the number of 3's you will see that Mathematica has stored 6 decimal places. This is the default value, but you can also tell Mathematica exactly how many significant figures to keep in the calculation by using N[expr,precision]. Now evaluate 1/3 again setting the number of decimal places to 20 in the Input cell below. Also try to set the number of decimal places to 4. Does it work?

In[20]:= N@1ê3, 20D H∗ Evaluate as a float with 20 digits ∗LOut[20]= 0.33333333333333333333

Actually, has an internal variable named Precision that controls the number of digits that get stored. We can check what it is, and then change it:

Landau, First Course in Scientific Computing 27

Copyright: Princeton Univ Press, RH Landau, 2005

Page 36: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[21]:= N@1ê3DPrecision H%LSetPrecision@1ê3, 4D

Out[21]= 0.333333

Out[22]= 0.333333 Precision

Out[23]= 0.3333

àc:6

3.4.1 Powers of 10

We have just seen how Mathematica can store numbers in floating-point or scientific notation. Note, that unless you are dealing with an exact power of 10, like 10,000, the floating point representation of a number is always approximate since only a finite number of digits is used to store the mantissa. While we are discussing exponents and exponentials (which are related, but different), it is useful to see how Mathematica gives you the ability to enter a number as a power of ten by using *^ and its exponent.

Enter each of the following (with spacing exactly as given) one at a time, and explain Mathematica's response to each:

3.1*^6, 3.1 *^6, 3.1*10^6, 3.1 10^6, 3.1E6, 3.1e6, 3.1 E^6, Log[E^1], Ln[E], Log[1 e^1], Log[Exp[1]], Exp[1.], Log[Exp[1.]]

In[24]:=

We deduce from these results that:

Mathematica recognized 3.1*^6 as the floating point number 3.1x106 , with mantissa 3.1 and exponent 6. However, it threw a syntax error for the second case, 3.1 *^6. This is due to the space in between the number and the *, and is not recognized as scientific notation. The third and fourth examples only differ in the multiplication being represented by a * or a space, and Mathematica evaluates them as the correct floating point number.

In contrast, the expressions 3.1E6 and 3.1e6 are accepted by Mathematica, but it assumes you want to multiply 3.1 by E6 and e6 respectively, and believes that E6 and e6 are algebraic symbols. This is not scientific notation even though it may look like what your calculator gives you. However, 3.1E^6 evaluates ‰ 6 and multiplies it by 3.1 so a floating point number is calculated. Remember that Mathematica uses E for a representation of the irrational base of the natural logarithms.

The next case is as expected because Log and E are inverse functions in Mathematica. That is, Log[x] represents the natural logarithm. Therefore, Ln[E] has no result in Mathematica because Ln is not a built-in Mathematica function. Log[e] also has no result in Mathematica because it treats e as an algebraic symbol. The last cases use the built-in function Exp[1], instead of E or ‰, for the base of the natural logarithms. Accordingly, Log[Exp[1]] = 1 exactly. Exp[1.] reveals a truncated value of ‰, but Log[Exp[1.]] = 1.0!! Mathematica does contain the logarithm of other bases besides ‰. For base, b, other than ‰, use the Log[b,x].

28 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 37: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

c:7

3.5 Complex Numbers

A complex number is the sum of a real number and an imaginary number. An imaginary number is è!!!!!!!-1 times a real

number (if you need some review of complex numbers, you may want to read the introductory material in Chap. 16 in the Java part of this book). Usually mathematicians and physicists use the symbol i to represent è!!!!!!!

-1 , while engineers often use the symbol j; regardless of its name, it is the same number, and it does not really exist in our world. Mathemat-ica, in turn, marches to its own drummer and uses I to represent è!!!!!!!

-1 . To see how this works (we will encounter complex numbers in a number of places again), we give you some examples:

In[25]:= Sqrt@−1D H∗ See what Mathematica returns ∗LOut[25]=

In[26]:= 1 + H2 + 2∗ILêH2 − 2∗ILH∗ Algebraic calc with complex numbers ∗LOut[26]= 1 +

To convert this result to polar notation (r, q), we need to find each component separately:

In[27]:= Abs@%D H∗ Modulus r ∗LOut[27]=

è!!!2In[28]:= Arg@%%D H∗ Phase θ *L

Out[28]=π4

In[29]:= Sqrt@ D H∗ Square root of Hnot obviousL ∗LOut[29]= H−1L1ê4In[30]:= Expand@%D H∗ Try to get in complex form ∗L

Out[30]= H−1L1ê4In[31]:= ComplexExpand@%%D H∗ This should do it *L

Out[31]=1 +è!!!2

Landau, First Course in Scientific Computing 29

Copyright: Princeton Univ Press, RH Landau, 2005

Page 38: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[32]:= %∗% H∗ Verify result by squaring ∗LOut[32]=

Both of the above answers are correct, and one would think that the Expand function would give us the complex answer we are looking for, but ComplexExpand is the function to use. This is a handy function that assumes all the variables in the expression are real. If the expression has complex variables, you need to list them as an argument of the function (i.e., ComplexExpand[expr, x1, x2, ...xn]).

c:8

3.6 Expressions

We started our work with Mathematica by using it as a sophisticated pocket calculator. You keyed in commands one at a time, and Mathematica evaluated them one at a time. Mathematica can do much more. One of the truly modern things it can do is mathematics, including calculus, with algebraic symbols. Many of the commands in Mathematica work with either numbers or symbols. We shall see some examples of that.

In a semantic sense, most of the commands that we have been feeding to Mathematica up until now are expressions and statements. While you may know what these terms mean in common English, they have rather specific meanings in both computer science and mathematics. (This is an example of Landau's First Rule of Education.) Expressions are objects that have numerical values (or would have values if the variables containing the expressions had values). Commands like 1+4 and Sin[Pi/2]are expressions with values, 5 and 1 respectively. On the other hand, ‰x- 1 is also an expression, but it has a numerical value only if x has previously been assigned a value. Try it:

In[33]:= Exp@xD − 1 H∗ Evaluate Exp@xD − 1 ∗LOut[33]= −1 + x

In[34]:= x = H∗ Assign a value to x, , e.g. x = 2 ∗LSyntax::tsntxi : "x =" is incomplete; more input is needed.

x =

30 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 39: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[34]:= Exp@xD − 1 H∗ Evaluate Exp@xD −1 again ∗LOut[34]= −1 + x

Note that when Mathematica just echoes what you have entered, it is being diplomatic and telling you that it has heard what you have said, but that it cannot do anything more at this point. (For example, Mathematica just repeated your first command using ‰ instead of Exp.) If this is not what you want, then you better do something so Mathematica can get what it needs to act! As far as leaving a mark on history or setting up values to be used again in later computations, expressions don't do much. After Mathematica evaluates an expression and returns its value, it's done with it.

3.6.1 Clear and ClearAll

When we refer to a constant we mean an object whose value does not change. As an instance, Pi = p is such a constant. When we refer to a variable we mean an object whose value may change. For example, the circumference C = 2p r will have different values depending on the radius r of the circle. When we refer to a symbol, such as x, we view it as one would in algebra, that is, as an abstract object representing something more concrete. Sometimes x may have a numerical value, and sometimes it may not. In any case, we manipulate it using the rules of algebra and calculus.

When a symbol has been assigned within a Mathematica notebook, it normally stays assigned until you give Mathematica a command to change it, or until you close that particular notebook. (It's often useful to have several notebooks open at one time, possibly even different versions of the same notebook). Sometimes you may be happily working away or editing deep within a notebook that was just working fine for you, and for some reason your statements no longer appear to be working correctly. The problem may be that you have forgotten that some variable has been assigned previously, and you are using it as if it hadn't. That being the case, you need to unassign, or Clear, the variables. Forgetting to clear the variables is the cause of many problems in Mathematica and in general you should remove the assigned values from variables as soon as you are finished using them. Also, if you just jump into the middle of a notebook, you do not know which variables have been assigned, or which packages have been called, and it would be safest to "start with a clean slate".

To start again with unassigned values for x and y, as if it were a whole new session, use the Clear[x, y] command, with the variables that need clearing as arguments.

In[35]:= Clear@x, yD H∗ Unassign x and y variables ∗L[There is no way we know of to clear all assigned variables at once like Maple's restart command.]

To unassign a single-variable, use Clear[x] with the variable as an argument, or assign the variable to the period symbol . which nullifies the variable and returns it to a symbol:

In[36]:= x = 10 H∗ The immediate assignment statement ∗LOut[36]= 10

Landau, First Course in Scientific Computing 31

Copyright: Princeton Univ Press, RH Landau, 2005

Page 40: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[37]:= x = . H∗ Remove any value assigned to x ∗Lx H∗ Show the present value of x ∗LSyntax::sntxf : "x =" cannot be followed by ".x".

x = .x

A more powerful command is the ClearAll. It clears the values as well as the attributes, messages and defaults associ-ated with variables. Clear will unassign the value of the variable, whereas ClearAll will remove all information about that variable as well. Unless you have reason not to, it's a good idea to issue the Clear or ClearAll command with all variables you have used previously at the beginning of a new group of operations. In particular, if Mathematica appears not to be computing some statements correctly when it did ``just a while ago'', it may be that you have inherited some garbage from previous work, and it's always a good idea to take out the garbage. If Mathematica really seems to be working improperly, you should save your files (maybe to new versions), exit Mathematica, and then start it again (we all do better after a little vacation).

c:9

3.6.2 Exercise (how expressions are stored)

The factorial expression n! = n(n-1)(n-2)...(2)1 occurs frequently in mathematics. If n is an integer, then Mathematica evaluates n! just as you would expect. What is the ratio of (1001)! to 1000!?

In[37]:= H1001L!ê1000!

Out[37]= 1001

However, when n is a symbolic variable with no value assigned to it, Mathematica prefers to store it as n! rather than as the product of many terms. This makes sense both because it saves memory (computers are finite), and because it makes further manipulations easier. Try it:

In[38]:= Hn + 1L!ên! H∗ What is the ratio of Hn+1L! to n! ? ∗LOut[38]=

H1 + nL!n!

In[39]:= Hn + 50L!ên! H∗ What is the ratio of Hn+50L! to n! ? ∗LOut[39]=

H50 + nL!n!

While it may appear that Mathematica is arrogantly repeating to you the command that you have just barked at it, a more understanding view is that Mathematica does not think like a real person, and so has to be told more explicitly just what you have in mind. In this case, Mathematica has worked out an answer which apparently looks fine to it, while we might prefer something simpler. We tell Mathematica to simplify an answer with the FullSimplify[%] command:

In[40]:= Hn + 50L!ên!H∗ Calculate ratio of Hn+50L! to n! remembering to simplify ∗LOut[40]=

H50 + nL!n!

32 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 41: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[41]:= FullSimplify@%D100!ê50!

FullSimplify@ Hn + 50L!ên!, Assumptions → n ú Integers DOut[41]=

Gamma@51 + nDn!

Out[42]= 3068518756254966037202730459529469739228459721684688959447786986982158958772355072000000000000

FullSimplify::optx : Unknown option Assumptions

in FullSimplifyA H50 + nL!n!

, Assumptions → n ú IntegersE.Out[43]= FullSimplifyA H50 + nL!

n!, Assumptions → n ú IntegersE

In[44]:= FullSimplifyA H50 + nL!

n!, Assumptions → n ú IntegersE

FullSimplify::optx : Unknown option Assumptions

in FullSimplifyA H50 + nL!n!

, Assumptions → n ú IntegersE.Out[44]= FullSimplifyA H50 + nL!

n!, Assumptions → n ú IntegersE

Calculate now the ratio of (n+m)! to n!, where neither n nor m have been assigned values.

In[45]:= H∗ Calculate the ratio of Hn+mL! to n! ∗LYou should note that Mathematica has output the G symbol. This denotes some highfalutin mathematical function called the Gamma function (of course). This is actually the correct for noninteger values of n and m, and reduces to the usual factorials for integer n and m. We told you that Mathematica really does know a lot of math!

c:10

3.7 Assignment Statements

Whereas expressions have values, statements cause things to happen. In other words, statements have side effects such as assigning values to variables or plotting up graphs. The most common type of statement is the assignment statement setting one object equal to another:

In[46]:= x = 1.ê3 H∗ Sets x = result of computation ∗La = b H∗ Sets a equal to a symbol ∗L

Out[46]= 0.333333

Out[47]= b

Landau, First Course in Scientific Computing 33

Copyright: Princeton Univ Press, RH Landau, 2005

Page 42: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[48]:= xa

Out[48]= 0.333333

Out[49]= b

We see that the side effects of these statements is that x will have the value .333333, and a the value b. This is just what Mathematica tells you in its responses.

3.8 Equality

Because assignment statements set things equal to each other, they must contain an equal sign. Mathematica has two types assignment operators, and hence two types of assignment:

lhs = rhs, immediate assignment with rhs evaluated

lhs := rhs, delayed assignment with rhs evaluated each time lhs is invoked

It is easy to be confused about which assignment operator to use in a given situation. Think of it this way: if you consider the assignment as giving the final value of an expression, then use the = operator; if you consider the assignment as being a command to find the value of the lhs using the current and changing value of rhs, then use the := operator. In general use := if you aren't sure, but beware that value will change accordingly. [This may all seem strange to you if you are used to Maple or other computer programming languages that use := as their only assignment operator, with = used for logical statements. In Mathematica both = and := are used for assignment.]

These equal signs are assignment operators that may be thought of as saying ``set the variable on my left equal to the value on my right''. To a computer this means ``go to the location in memory where the value of the variable on my left is stored, and place the value on my right into that memory location''. In contrast to conventional programming languages, like C or Java, Mathematica permits the value on the RHS to be purely symbolic.

In spite of the assignment statements above looking like equations, they do not express the same type of equality as do algebraic equations. To illustrate, when we say x = y in algebra, we mean that the objects on both sides of the equal sign are the same. Thus it follows that y = x is also true. Yet if we issue the Mathematica statement x = 4, we are issuing a command to replace whatever was stored in memory as the value of x with the new value 4. What we most certainly do not want, is 4 = x, that is, to have all values of 4 replaced by the present value of x, which may well be 10.

34 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 43: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

c:11

3.9 Functions

Mathematicians and scientists make life easier by employing things called functions in their work. Computer scientists do much the same thing with what they also call methods and subroutines. So while we will use the word ``function'' in Mathematica and mathematics, when we get on to programming, we will speak of ``methods'' which are also functions.

-2 02x

-2 0 2y

0

5

10

15

-2 02x

-2 0 2y

Figure 3.2: Function as meat grinder, arguments x, y, .. go in, f(x,y,...) comes out.

As visualized in Fig. 3.2, a function f(x) can be thought of as a mathematical meat grinder in which you feed it some variables as input, it processes the input variables, and then it returns the value of the function as output. As a case in point, f HxL = 10 x4 sin H3 xL is such a function. You feed it the variable x, it multiplies x by 3, evaluates the sine of 3x, multiplies that by 10 x4 , and then returns the result. In other words, x is the independent variable that we can choose, and y = f(x) is the dependent variable.

While this should sound familiar to you, it is worth mentioning that the number 3 and 10 occur in our function not as variables, but rather as parameters that are not expected to be changing much. So if we replace the numerical parameters with algebraic symbols, f HxL = A x4 sin Hk xLthen x is still the independent variable, and A and k are now the parameters. Clearly then, whether a symbol is a variable or a parameter is determined by its use, which we usually can figure out from the context. Accordingly, we also could write our function as a function of two variables, f Hx, kL = A x4 sin Hk xLor as a function of three variables, f Hx, k, AL = A x4 sin Hk xL. In a sense then,the form chosen is just a matter of convenience. Functions of more than one variable are called multivariate functions, and are very much like our meat grinder analogy in Figure 1, except that we now have a number of ingredients (variables).

When we instruct a computer program such as Mathematica to create a function for us, we have to tell it which symbols are variables and which are parameters. As a rule of thumb, it is probably best to make your decision as to what are variables and what are parameters based on convenience: if it is unlikely that the values for the parameters will change, then it is simpler and clearer to build them into the function as, say, 3 and 10 (without declaring them as variables that can be changed by mistake); if it is likely that you will want to change the parameters, for example to make a number of plots, then it is best to treat them as variables.

Landau, First Course in Scientific Computing 35

Copyright: Princeton Univ Press, RH Landau, 2005

Page 44: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

àc:12

3.9.1 Built-in Functions

Even though mathematical functions occur in descriptions of our world, computers do not inherently know about them. However, there are often collections of programs called ``libraries'' that supplement computer languages and that contain many functions and methods. Maple has an extensive library of such functions, and we give a complete list in Appendix B (which you can also get via Help[Mathematical Functions]). Some functions that you may find most useful are:

Exp@xD, Log@xD, Abs@xD, Sin@xD, Cos@xD, Sqrt@xD,ArcCos@xD, Cosh@xD, LegendreP@n, xD, BesselJ@n, zD, ...

Note again that Mathematica requires square brackets [ ] for function arguments, with parentheses ( ) used just for group-ing. Most conventional computer languages handle these common functions, as would your calculator: you key in a number, you get back a number. In contrast, symbolic languages like Mathematica not only can give you numerical values for the functions, but also know much about the mathematical properties of these functions and can help you manipulate them.

In its usual insightful manner, if you give Mathematica a floating-point numbers as input, it will evaluate the function numerically. If an argument is symbolic, then Mathematica will return a symbolic answer.Try it:

In[50]:= H∗ Enter y = 10 x4 Sin@3 xD ∗LH∗ Enter x = 10 ∗LIn[51]:= H∗ Enter y = 10 x4 Sin@3 xD ∗L

We see that Mathematica has remembered the value of x from one line to the next (it actually will remember the value of x until we do something to reassign it or until we Clear it. Regardless of the fact that we entered purely numerical values for the argument of the sine function, Mathematica has still not given us the answer you would get from a calculator! Do not get annoyed. The answer y = 100000 sin(30) is an exact mathematical expression with no approximations made, and so Mathematica keeps it that way. If we want a floating-point or decimal number as an answer, then you must force Mathemat-ica to make the approximation by having it evaluate the answer as a floating-point number:

In[52]:= N@%D H∗ You could use %êêN ∗LOr you could have done this in one step,

In[53]:= y = N@10∗x^4∗Sin@3∗xDDOut[53]= 0.103885

Note again how Mathematica has remembered that we have previously assigned x=10. Alternatively, you could have used a floating-point number in the argument of the function, in which case Mathematica would have automatically converted to floats:

36 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 45: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[54]:= y = 10∗x^4∗Sin@3.∗xDOut[54]= 0.103885

In the Input cell below, try some variations on the preceding commands in which either x is a float or the factor in front of the sine function is a float:H∗ Try your variations here ∗LAs we have said before, by default (i.e. unless you instruct otherwise) Mathematica performs all floating point calculations with a precision of six significant digits.

c:13

3.10 User-Defined Functions

In addition to Mathematica's built-in functions, you can define your own functions and call them anything you want (for the most part). For example, let us say we want to define the function, g(x) = 10 x4 sin(3 x):

In[55]:= Clear@x, yD H∗ Clear out old assignments ∗Lg@x_D := 10∗x^4∗Sin@3∗xD H∗ Define function g. Note the _ ∗L?g H∗ Shows the context & definition of g ∗L

Info3307794721-2877600

Global`g

Info3307794721-2877600

g@x_D := 10 x4 Sin@3 xDSurvey a few things here:

- The := operator is used to define those functions that you plan on to use often, that are piecewise, or recursive. (We give an example below in which = must be used.

- The right hand side of the definition tells Mathematica how to compute the value of g for any given value of x. You may use any valid Mathematica operations or functions on the RHS.

- The underscore _ on x_ on the LHS of the definition is essential. It tells Mathematica that x is a dummy variable to be replaced by something else. Your function will not work correctly without the underscore.

- Finally, you need the ?g line after the function to provide you with information about your function, such as its type and definition.

If you do all of this right, your function will work just like a built-in one. Evaluate g[10] and see if you get the same answer as we did above:

In[58]:= g@10D H∗ Enter g@10D or y=g@10D ∗LOut[58]= 100000 Sin@30D

Landau, First Course in Scientific Computing 37

Copyright: Princeton Univ Press, RH Landau, 2005

Page 46: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[59]:= [email protected] H∗ Now try float as argument for g ∗LOut[59]= 62747.8

Defining multivariate functions just requires you to add some more variables to the argument list. This is often a useful way to feed a single-variable function the parameter values that it may need. For example, to create our old friend y(x)= A x4 sin(3 x) as a function, we replace [x] with [A_, b_, x_]:

In[60]:= Clear@x, yD H∗ Define 3−variable function ∗Ly@x_, A_, b_D := A ∗ x^4 ∗ Sin@b∗xD?y

Info3307794726-2006151

Global`y

Info3307794726-2006151

y@x_, A_, b_D := A x4 Sin@b xDUse y[x_, A_, b_] to evaluate 10 x4 (i.e. the output should be 10 x4 ):

In[63]:= H∗ Hint: you need Sin@b xD= 1 ∗Lc:14

3.10.1 Special Case: Defining functions with =

Sometimes the function you define is some function of an expression involving yet another function, for example, y(x) =Log[Sin[x]^2] . In cases such as these, you need to use the = equal sign, but still the x_:

In[64]:= Log@Sin@xD^2D H∗ An expression involving x ∗LOut[64]= Log@Sin@xD2DIn[65]:= LogSinFunc@x_D = Log@Sin@xD^2DH∗ Define function with arg = x ∗L

Out[65]= Log@Sin@xD2DIn[66]:= LogSinFunc@1 + bD H∗ Result of function when x = 1 + b ∗L

Out[66]= Log@Sin@1 + bD2DIn[67]:= LogSinFunc@3D H∗ Result of function when x = 3 ∗L

Out[67]= 2 Log@Sin@3DDIn[68]:= LogSinFunc@3D êê N H∗ Evaluate result numerically ∗L

Out[68]= −3.91629

Let's try a similar function but use := to define the function and see what happens:

In[69]:= Log@Cos@yDD H∗ An expression involving y ∗LOut[69]= Log@Cos@yDD

38 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 47: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[70]:= LogCosFunc@y_D := Log@Cos@yDD H∗ Define function wêarg y ∗L?LogCosFunc H∗ Display the function definition ∗L

Info3307794737-2964655

Global`LogCosFunc

Info3307794737-2964655

LogCosFunc@y_D := Log@Cos@yDDIn[72]:= LogCosFunc@bD H∗ Result of function when y=b ∗L

Out[72]= Log@Cos@bDDIn[73]:= LogCosFunc@3D H∗ Result of function when y=3 ∗L

Out[73]= π + Log@−Cos@3DDUsing =: didn't go too well here. However, in most often you will use := to define functions, except for these special cases.

c:15

3.11 Reexpressing Answers

Mathematica knows that è!!!!!!16 is 4 and will evaluate it with no further ado (usually). However, if there is not an exact root to some number, then Mathematica will reduce the number down as far as it can, but may leave some part of the number in root form. Numbers with explicit roots included are called algebraic numbers. For example, ask Mathematica to evaluateI1 + è!!!2 M2 :

In[74]:= H1 + Sqrt@2DL^2 H∗ Mathematica command for I1 + è!!!2 M2 ∗LOut[74]= I1 + è!!!2 M2

Maybe Mathematica is trying to be difficult here, or maybe it really thinks that you want to keep the answer in this com-pact form. Well, whatever, we will tell Mathematica that we would like the expanded form of the previous expressions:

In[75]:= Expand@%D H∗ Ah, that is better. ∗LOut[75]= 3 + 2 è!!!2

There are a bunch of Mathematica commands, such as

Simplify, FullSimplify, Factor, Collect, Expand, ComplexExpand, Evaluate, Normal

that are useful in getting Mathematica to change the form of its answers to something you might like better. For example, how about some cute cube roots:

In[76]:= H−8L^H1ê3LOut[76]= 2 H−1L1ê3

Landau, First Course in Scientific Computing 39

Copyright: Princeton Univ Press, RH Landau, 2005

Page 48: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[77]:= Simplify@%D H∗ Not revealing ∗LOut[77]= 2 H−1L1ê3In[78]:= ComplexExpand@%D H∗ Ah, that' s better ∗L

Out[78]= 1 + è!!!3As we get into more complicated calculations, we shall see that there is little question that Mathematica can do algebra quickly. However, the results it gives may not always be in the form that humans find revealing. Indeed, learning how to use Mathematica is more than just learning the names and grammar of a whole bunch of commands, it is also acquiring a state of mind in which you naturally try to manipulate Mathematica's output until it produces the most mathematically revealing form for you! In this section we look at some manipulations and ``tricks''.

Mathematica is real good at summing finite and infinite series:

In[79]:= Sum@i, 8i, 0, n<D H∗ Sum the integers from 1 to n ∗LOut[79]=

12n H1 + nL

This is the result that we learned in our algebra class, so we lucked out. Sometimes to get more illuminating forms of output we need to issue one or more of the following commands:

Expand[%], Factor[%], Simplify[%], FullSimplify[%], Cancel[%]

where % is the result of the previous calculation. Now use Mathematica to produce some complicated expressions, and then try to simplify them:

In[80]:= Product@HHx^2 + 3∗i − 1LêHi + 3LL, 8i, 0, 10<DOut[80]=

13113510400

HH−1 + x2L H2 + x2L H5 + x2L H8 + x2LH11 + x2L H14 + x2L H17 + x2L H20 + x2L H23 + x2L H26 + x2L H29 + x2LLIn[81]:= Expand@%D H∗ Expand the polynomial ∗L

Out[81]= −11339486

−19303181 x2

3891888+75727019 x4

5054400+235273943 x6

23587200+293387 x8

103680+8594731 x10

18869760+

308441 x12

6739200+280831 x14

94348800+

13 x16

103680+

187 x18

56609280+

x20

20217600+

x22

3113510400

In[82]:= Factor@%D H∗ Factor the polynomial ∗LOut[82]=

13113510400

HH−1 + xL H1 + xL H2 + x2L H5 + x2L H8 + x2LH11 + x2L H14 + x2L H17 + x2L H20 + x2L H23 + x2L H26 + x2L H29 + x2LLSo you see that Expand and Factor mean the same things as they do in algebra. However, you probably have not found much use for Simplify, FullSimplify, and Normal yet . To find basic information about any Mathematica command, type a question mark, ? in front of the command name (with no arguments) in an Input cell and execute the cell. A link to the help pages will be included with the basic information. For example,

40 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 49: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[83]:= ?Simplify

Info3307794748-1458228

Simplify@exprD performs a sequence of algebraic transformationson expr, and returns the simplest form it finds. Simplify@expr, assumD does simplification using assumptions. More…

Now you try it with Normal:

In[84]:= H∗ Obtain basic info on normal ∗LIn[85]:= Simplify@Cos@xD^2 + Sin@xD^2DH∗ Simplify using identities ∗L

Out[85]= 1

In[86]:= Normal@Product@HHx^2 + 3∗i − 1LêHi + 3LL,8i, 0, 10<DDOut[86]=

13113510400

HH−1 + x2L H2 + x2L H5 + x2L H8 + x2LH11 + x2L H14 + x2L H17 + x2L H20 + x2L H23 + x2L H26 + x2L H29 + x2LL3.11.1 Simplifying Examples

In[87]:= Clear@x, y, g, a, bDExpand@Tan@a + bDD H∗ Fails ∗L

Out[88]= Tan@a + bDIn[89]:= TrigExpand@Tan@a + bDD H∗ Succeeds ∗L

Out[89]=Cos@bD Sin@aD

Cos@aD Cos@bD − Sin@aD Sin@bD +Cos@aD Sin@bD

Cos@aD Cos@bD − Sin@aD Sin@bDIn[90]:= Factor@%D

Out[90]=Cos@bD Sin@aD + Cos@aD Sin@bDCos@aD Cos@bD − Sin@aD Sin@bD

In[91]:= Expand@H1 − xL^2∗Hx + 2LDOut[91]= 2 − 3 x + x3

In[92]:= Simplify@%D H∗ Fails ∗LOut[92]= 2 − 3 x + x3

In[93]:= Factor@%D H∗ Succeeds ∗LOut[93]= H−1 + xL2 H2 + xLIn[94]:= Simplify@Cos@xD^2 − Sin@xD^2D

Out[94]= Cos@2 xD

Landau, First Course in Scientific Computing 41

Copyright: Princeton Univ Press, RH Landau, 2005

Page 50: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[95]:= Factor@x^4 − x^2DOut[95]= H−1 + xL x2 H1 + xLIn[96]:= 1êHx + 1L + 1êHx − 1L

Out[96]=1

−1 + x+

11 + x

In[97]:= Normal@%D H∗ Fails ∗LOut[97]=

1−1 + x

+1

1 + x

In[98]:= Simplify@%D H∗ Succeeds ∗LOut[98]=

2 x−1 + x2

àc:16

3.11.2 Expressions Behaving like Functions

It seems perfectly reasonable to think of a variable like x or y as a symbol that does not have function-like properties. However, Mathematica is so smart and has such a good memory that if you set a variable equal to a complicated expres-sion, like a polynomial or some combination of functions, Mathematica will treat that variable much as it does the explicit expression and substitute in values for the other variables. The manipulations we did in the section on functions can also be done on variables representing expressions:

In[99]:= z = Hx + 2L^15 H∗ variable z now can be used instead of the expression ∗LOut[99]= H2 + xL15In[100]:= Expand@zD

Out[100]= 32768 + 245760 x + 860160 x2 + 1863680 x3 +

2795520 x4 + 3075072 x5 + 2562560 x6 + 1647360 x7 + 823680 x8 +

320320 x9 + 96096 x10 + 21840 x11 + 3640 x12 + 420 x13 + 30 x14 + x15

In[101]:= Factor@zDOut[101]= H2 + xL15

Even though we are manipulating z as if it were a function, it is not a true function and does get evaluated differently. To cite an instance, if we enter z(3) as if the expression were a function, we get something interesting but not 515 :

In[102]:= Print@"z@x=3D = ", z@3DDz@x=3D = H2 + xL15@3D

To evaluate z for x = 3, where x has a definite value (numeric or symbolic), you need to create a transformation rule or mapping and then apply it to the expression z. The transformation rule to replace x with the value 3 is x->3. To apply a transformation rule to an expression, you type expression /. rule . The replacement operator /. is also typed as a pair of characters with no space between them:

42 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 51: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[103]:= z ê. x → 3

Out[103]= 30517578125

We now obtain the expected answer, 5 to the 15th power. Since we have done this replacement with one variable, it may be useful to mention that it can also be done with several variables. In order to do this, you place the transformation rules in a list:

In[104]:= z = Hx + yL Hx − yLOut[104]= Hx − yL Hx + yLIn[105]:= z ê. 8x → 3, y → 2<

Out[105]= 5

c:17

3.12 CS: Overflow, Underflow and Round-Off Error

All computers are finite and, alas, Mathematica is too. This means that if you keep making numbers bigger and bigger, at some point the computer cannot handle them and an overflow occurs. Likewise, if you keep making numbers smaller and smaller, at some point an underflow occurs. In addition, since floating-point numbers are stored with a finite number of significant figures, the digit beyond the last one is truncated, and the last digit is rounded off. Similarly, if the truncated digit is greater than 5, then the last stored digit is rounded up, and this leads to round-off errors. (For convenience, both truncation and round-off errors are usually called ``round-off error''.) In principle, the algorithms used by Mathematica for calculations have no limit to their precision and should be exact if no floating-point numbers are called. Serious problems result if you write a program and underflow or overflows occur within it, or if there is a great deal of round-off error.

Enough talk, let us have some fun and see if we are able to break Mathematica using the factorial, n! and powers of 10. Do not worry, you will do no permanent harm and no one will yell at you if you break Mathematica, although you may lose active notebooks. In general, you get no warning that Mathematica is about to break, so drive defensively and Save Often! If your command is not responding for a considerable amount of time, it may be working, or it may be misfunction-ing. Before you quit or kill Mathematica, go to the Kernel menu and choose Abort Evaluation, or alternatively press Alt +

Seeing that the limits of implementation depend greatly on the computer platform, version of Mathematica, and other local details, so you may not get the same results we have. Here we challenge Maple and show how it admits failure:

In[106]:= 2^32^3^4000 H∗ Take powers till overflows ∗L

Out[106]= 8

General::ovfl : Overflow occurred in computation.

Out[107]= Overflow@D

Landau, First Course in Scientific Computing 43

Copyright: Princeton Univ Press, RH Landau, 2005

Page 52: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[108]:= 5!

10! H∗ Calc factorials till overflows ∗LOut[108]= 120

Out[109]= 3628800

In[110]:= 10.^10000010.^100000000 H∗ Increase exponent till overflows ∗L

Out[110]= 1.0000000000×10100000

Out[111]= 1.0000000×10100000000

In[112]:= 10.^H−10000L10.^H−1000000L H∗ Decrease exponent till underflows ∗L

Out[112]= 1.00000000000×10−10000

Out[113]= 1.000000000×10−1000000

Because calculations that employ floating-point numbers are often truncating or rounding off the last digit in the mantissa, and because these errors tend to accumulate in time, their final results may be less precise than the numbers you input. This is called truncation and round-off error. We use the term ``error'' here in much the same way as one does when speaking about the experimental ``error'' in a physics laboratory. It is not an error in the sense that you read the meter wrong or had your finger caught in the caliper, but is really an uncertainty arising from the finite number of digits used to represent numbers.

To see a living example of truncation error, work through the following commands:

In[114]:= x = N@Pi, 20D H∗ Set x to store Pi to 20 digits ∗LOut[114]= 3.1415926535897932385

In[115]:= N@x, 40D H∗ Value of x to 40 digits ∗LOut[115]= 3.1415926535897932385

In[116]:= N@Pi, 40D H∗ Pi to 40 digits ∗LOut[116]= 3.141592653589793238462643383279502884197

This example of truncation error shows that the digits of the variable x not being displayed are not really there. If some calculations we were performing relied on these digits being there to get the right answer, then we would get the wrong answer.

Round-off error is related to truncation error and occurs in every calculation when the computer knows that it is about to truncate a digit greater than 5, and so rounds up the previous digit by one unit. For example, if 3 digits are kept, 0.2468 gets rounded off to 0.247, which is better than 0.246, but still has loss of precision. To see Mathematica do this, evaluate 2./3:

44 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 53: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[117]:= 2.ê3 H∗ Enter 2.ê3 into this cell ∗LOut[117]= 0.666667

c:18

3.13 Solution: Viewing Rocket Golf

We will now apply our Mathematica tools to the relativistic golf ball problem. Michelle on the moving rocket, sees her golf ball travel with velocity U' at an angle q, with a hang time T':

U ' =c

ÅÅÅÅÅÅÅÅÅÅÅÅÅè!!!3 , q = 30o, T ' = 2.6 x 107 seconds

Ux ' =c Cos@qDÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅè!!!3 , Uy ' =

c Sin@qDÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅè!!!3

Ben on the earth observes the rocket moving with a speed v= c/2. He sees the golf ball with velocity components Ux and Uy and a hang time of T. The equations of special relativity (that we have not derived, and that we do not expect you to fully understand) relate Michele's and Ben's observations

T = gT', g =1

ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ"################1 - v2ÅÅÅÅÅÅc2

, Ux =Ux ' + v

ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ1 + v Ux 'ÅÅÅÅÅÅÅÅÅÅÅÅc2

, Uy =Uy '

ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅgH1 + v Ux 'ÅÅÅÅÅÅÅÅÅÅÅÅc2 L

Because the time dilation function g is rather complicated and is used in several places, we start our solution by defining a function for it:

In[118]:= Clear@v, θ, γDIn[119]:= Gamma@v_D := 1êSqrt@1 − v^2êc^2D;

?Gamma

SetDelayed::write : Tag Gamma in Gamma@v_D is Protected.

Info3307794769-9237686

Gamma@zD is the Euler gamma function. Gamma@a, zD is theincomplete gamma function. Gamma@a, z0, z1D is the generalizedincomplete gamma function Gamma@a, z0D − Gamma@a, z1D. More…

Whoops! Although this was the obvious thing to do, it does not work because Mathematica apparently has its own Gamma function and does not want us to steal its name. On account of this we try defining our function using a lowercase g:

Landau, First Course in Scientific Computing 45

Copyright: Princeton Univ Press, RH Landau, 2005

Page 54: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[121]:= gamma@v_D := 1êSqrt@1 − v^2êc^2D;?gamma

General::spell1 : Possible spelling error: newsymbol name "gamma" is similar to existing symbol "Gamma".

Info3307794774-4742798

Global`gamma

Info3307794774-4742798

gamma@v_D := 1"#############1− v2c2

Ah, that's better, (we shall ignore the warning about the spelling error). We see that gamma is defined globally. To make life simple for us beginners, let us adopt the convention that we measure all velocities as a fraction of the speed of light c. For example, rather than say v = c/2, we would just say v = 1/2. This will make the equations look simpler, and save us some time. So we just redefine gamma to be:

In[123]:= gamma@v_D := 1êSqrt@1 − v^2D;?gamma

Info3307794774-1793082

Global`gamma

Info3307794774-1793082

gamma@v_D := 1è!!!!!!!!!!!1−v2

This function is apparently acceptable to Mathematica, but we need to test it before we believe it is right. We know that for v = 0, g should equal 1, and that is should be progressively larger as v approaches the speed of light c. So let us see:

In[125]:= gamma@0Dgamma@1ê2Dgamma@1êSqrt@3DDgamma@99ê100D

Out[125]= 1

Out[126]=2è!!!3

Out[127]= $%%%%%%32

Out[128]=100è!!!!!!!!!199

These appear to be getting larger, but to be sure let us repeat the calculation using floating-point numbers. We can do that by acting on the function with the //N command, or by just placing some decimal point in the arguments. We'll be lazy:

46 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 55: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[129]:= gamma@0Dgamma@1ê2.Dgamma@1ê[email protected]@99ê100.D

Out[129]= 1

Out[130]= 1.1547

Out[131]= 1.22474

Out[132]= 7.08881

Yes, gamma does grow rapidly as v approaches the speed of light. But what happens if the relative velocity equals the speed of light? Let us try v = c:

In[133]:= gamma@1DPower::infy : Infinite expression 1

0encountered.

Out[133]= ComplexInfinity

Well this does not tell us much. That's because division by zero is not defined. However, in a mathematical sense, what we really want is the limit as v approaches c. So let us try something a bit more mathematical. One of the topics covered in calculus classes is the limiting process in which a variable is made to approach some value in infinitesimal steps. Mathemat-ica has the Limit command to do that, and it usually works quite well:

In[134]:= g = Limit@gamma@vD, v → 1DOut[134]= − ∞

The answer doesn't make sense because Mathematica is not giving us a physical answer. This is a case where the precision of language common in mathematics is called for. The cause of the problem is that there is an infinity at v = 1 (a division by 0) and the limit depends on just how we approach that infinity. After using the Help Browser for Limit, we discov-ered that there are some subtleties involved with the limiting process near a singular point (where the function goes to infinity). For the present case, we use an option of the Limit command to tell Mathematica we approaching the singular-ity from smaller values of x, or from the left, that is from v < c:

In[135]:= g = Limit@gamma@vD, v → 1, Direction → 1DOut[135]= ∞

This is better. We see that the time dilation factor g approaches infinity as the rocket speed approaches the speed of light.

We will discuss plotting in more detail in Chap. 4. Nevertheless, we make here a simple plot of g(v) using the Plot command. Because we have set c=1 there are no variables with symbolic values in g[v], and so Mathematica evaluates it as a number and plots it

Landau, First Course in Scientific Computing 47

Copyright: Princeton Univ Press, RH Landau, 2005

Page 56: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[136]:= Plot@gamma@vD, 8v, 0, 1<, PlotLabel −> "Gamma@vD vs vêc"D;

0.2 0.4 0.6 0.8 1

2

4

6

8

10

12

14Gamma@vD vs vêc

We see that g[v] is essentially 1 until the velocity gets close to the speed of light. Indeed, this is why we do not usually experience relativistic effects in our everyday lives. For the problem at hand, the exact and floating-point values of g[v] that we will use are:

In[137]:= Clear@gamma, v, cDIn[138]:= gamma@v_D := 1êSqrt@1 − v^2D;In[139]:= PrintA"gamma@ 1è!!!!

3D = ", gamma@1êSqrt@3DDE

gamma@ 1è!!!3 D = $%%%%%%32

In[140]:= PrintA"gamma@ 1è!!!!!!3.

D = ", gamma@1ê[email protected]@ 1è!!!!!!3.

D = 1.22474

The difference in value from 1 indicates that there is a significant relativistic effect for our problem. Specifically, Ben says that the golf ball stayed in air 22% longer than Michele thought it did:

In[141]:= T = gamma@1ê[email protected]∗2.6 E7;Print@"TBen = ", TDTBen = 3.18434 E7

Next we calculate the speed U at which Ben sees the golf ball hit, knowing that Michelle, moving with a relative velocity v = cÅÅÅÅÅÅÅÅÅÅè!!!!3

, saw it hit with velocity U'. So we need to calculate

Ux =Ux ' + v

ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ1 + v Ux '

, Uy =Uy '

ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅgH1 + vUx 'L

where we have assumed all velocities will be entered as a fraction of c. To be flexible, we create functions to calculate these velocity transformations, in one case using the previously-defined gamma function.

48 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 57: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[143]:= Ux@Up_, v_D := HUp ∗ Cos@θD + vLêH1 + v∗Up∗Cos@θDL;?Ux

Info3307794794-4764733

Global`Ux

Info3307794794-4764733

Ux@Up_, v_D := Up Cos@θD+v1+v Up Cos@θD

In[145]:= Uy@Up_, v_D := HUp ∗ Sin@θDLêHgamma@vD∗H1 + v∗Up∗Cos@θDLL;?Uy

Info3307794796-7086700

Global`Uy

Info3307794796-7086700

Uy@Up_, v_D := Up Sin@θDgamma@vD H1+v Up Cos@θDL

Ben knows Michele's value for q, and, after converting it to radians, uses it as input:

In[147]:= θ = 30∗Piê180 ; H∗ Convert 30 degrees to radians ∗LPrint@"θ = ", θDθ =

π6

In[148]:= N@θD H∗ Decimal value ∗LOut[148]= 0.523599

In[149]:= 30 Degree êê N H∗ Check conversion vs Mathematica' s ∗LOut[149]= 0.523599

In[150]:= UxBen = Ux@1êSqrt@3D, 1ê2D ; H∗ Ux in O frame ∗LPrint@"UxBen = ", UxBenDUxBen =

45

In[152]:= N@UxBenD H∗ Convert to decimal value ∗LOut[152]= 0.8

In[153]:= UyBen = Uy@1êSqrt@3D, 1ê2D; H∗ Uy in O frame ∗LPrint@"UyBen = ", UyBenDGeneral::spell1 : Possible spelling error: new

symbol name "UyBen" is similar to existing symbol "UxBen".

UyBen =15

Landau, First Course in Scientific Computing 49

Copyright: Princeton Univ Press, RH Landau, 2005

Page 58: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[154]:= N@UyBenD H∗ Convert to decimal value ∗LOut[154]= 0.2

If nonrelativistic kinematics are applied to this problem, we would see Michelle's golf ball moving at the combined speeds of the rocket plus its speed relative to the rocket:

UnonRel = v + Ux =cÅÅÅÅÅ2

+c Cos@30 °DÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅè!!!3 = c

Yet relativity teaches us that this is not possible for anything but light. If we look at the answer we just calculated, we see that the velocity seen by Ben is less than c (1 in our units):

In[155]:= UBen = Sqrt@UxBen^2 + UyBen^2D;Print@"UBen = ", UBenDGeneral::spell : Possible spelling error: new symbol

name "UBen" is similar to existing symbols 8UxBen, UyBen<.UBen =

è!!!!!!175

In[157]:= N@UBenDOut[157]= 0.824621

Now that we have calculated the components Ux and Uy of the velocity in Ben's frame, we can calculate the angle f at which Ben see the golf ball fly off by using the fact that,

tan Hφ L =UyUx

, or φ = tan−1 J UyUx

NInasmuch as the argument to the arctangent function would be infinite if Ux = 0, Mathematica's ArcTan function takes Uy and Ux as separate arguments:

In[158]:= φ = ArcTan@UxBen, UyBenD;Print@"φ = ", φDφ = ArcTanA 1

4E

In[160]:= N@φDOut[160]= 0.244979

In[161]:= % ∗ H180êPiL H∗ Convert to radians ∗LOut[161]= 14.0362

Thus we see that while Michelle saw her ball fly up at 30 degrees, Ben sees it ``pushed forward'' to about 15 degrees.

Problem b) In this version of the problem we have Michele hitting her golf ball backwards, that is, in a direction opposite to the direction of the rocket's flight. If the ball follows the same trajectory as in Problem a, only now in the negative x' direction. This is equivalent to replacing q by p-q in the preceding analysis:

50 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 59: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[162]:= θ = H180 − 30L∗Piê180; H∗ Convert degrees to radians ∗LPrint@"θ = ", θDθ =

5 π6

In[163]:= N@θD H∗ Decimal value ∗LOut[163]= 2.61799

In[164]:= 150 Degree êê N H∗ Check our conversion against Mathematica' s ∗LOut[164]= 2.61799

In[165]:= UxBen = Ux@1êSqrt@3D, 1ê2D;Print@"UxBen = ", UxBenDUxBen = 0

In[167]:= N@UxBenDOut[167]= 0.

In[168]:= UyBen = Uy@1êSqrt@3D, 1ê2D;Print@"UyBen = ", UyBenDUyBen =

13

In[170]:= N@UyBenDOut[170]= 0.333333

Assessment: These are interesting results! As expected, if Michelle hits her ball in the opposite direction to the rocket's path, the rocket's forward speed cancels out the ball's backward speed, and in this case Ben sees the ball hit straight up into the air!

This is also an interesting result from the computational point of view because we got exactly zero as an answer even though there were a number of steps involved. This is a consequence of us not entering floating-point numbers anywhere in the problem and of Mathematica being able to do exact arithmetic. However, we could have placed some decimal points in some of the quantities and then ended up with a floating-point computation. Let us see what the results would have been if we did the calculation in floating-point with 6 places of precision.

In[171]:= θ = N@H180 − 30.L∗Piê180.D H∗ Convert degrees to radians ∗LOut[171]= 2.61799

In[172]:= UxBen = Ux@1.ê[email protected], 1.ê2.DOut[172]= −1.4803×10−16

Landau, First Course in Scientific Computing 51

Copyright: Princeton Univ Press, RH Landau, 2005

Page 60: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[173]:= UyBen = Uy@1.ê[email protected], 1.ê2.DOut[173]= 0.333333

We see now that with limited precision, the velocity is no longer exactly zero (although it is zero within our level of precision). If we ask ``what is the relative error in the x-component of velocity?'', the answer would have to be infinite, since the exact answer is zero, and division by zero gives infinity. However, we should recognize that the answer UxBen = -1.4803 x 10-16 is consistent with 0, given the number of decimal places of precision that we have. Since it is very hard for floating-point calculations to calculate 0 with high precision, all that we can say is that the answer is small and possibly 0. Some further analysis would be needed to see if 0 is really the correct answer.

Problem c) Now repeat this exercise for a golf ball hit at 60o down and backwards, that is, at q = 240o . As a conse-quence of velocities perpendicular to motion not being reversed by a Lorentz transformation, there is no way that this ball will be seen as hit above the horizontal. However, it is possible for the horizontal component of velocity to be reversed by viewing the golf ball in different reference frames, and so it is possible for Ben and Michele to disagree on that.

c:19

3.14 Tachyons*

One of the principles of relativity is that no particle can be made to go faster than the speed of light. A particle of light, the photon, does travel at the speed of light, yet it has zero mass. To accelerate a particle with mass to v=c, would require an infinite amount of energy since the energy of the particle

E =moÅÅÅÅÅÅÅÅÅÅc2

è!!!!!!!!!!!!!!!!!!!!!!1 - v2 ê c2

is seen to approach infinity as v Ø c.

The thought has consequently arisen [Fein 76] that if a particle somehow started off its life with v>c, then its energy would be finite, albeit imaginary! Such particles are called tachyons from the Greek tachus meaning speedy. These would be very strange particles. If you increased their velocities, their energy would decrease, while if you decreased their velocity, their energy would increase, with infinite energy required to slow them down to c.

Repeat these exercises assuming that Michele's golf ball was a tachyon.

52 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 61: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

3.15 Key Words and Concepts

arguments assignment complex equality exponent expression floating-point number function imaginary integer irrational number mantissa overflow

rational number real round-off error side effects statement truncation error underflow

1. Explain the meaning of these keywords.

2. Are irrational numbers irrational only in the decimal system?

3. Do irrational numbers occur in nature?

4. Do floating-point numbers occur in nature?

5. Do floating-point numbers occur in mathematics?

6. What price is paid for Mathematica's use of infinite precision?

7. Might we be able to eliminate round-off and truncation error if we were more careful in our calculations?

8. What is the difference between a statement of equality and an assignment statement?

9. Explain why it makes sense to think of functions as mappings?

10. Are integers purer numbers than irrational numbers?

11. Are integers purer numbers than floats?

12. Does the form of a mathematical expression change its meaning?

13. How do you know when to tell Mathematica to simplify an expression?

14. What is the difference between an expression and a function in Mathematica?

Landau, First Course in Scientific Computing 53

Copyright: Princeton Univ Press, RH Landau, 2005

Page 62: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

c:21

3.16 Supplementary Exercises

1. Make a new worksheet that includes examples of overflow, underflow, and roundoff. Save it. Hint: 10^(-100) raises 10 to a negative power 10H-100L .2. Do you expect the following to give the same results?

1/3 + 1/3 + 1/3 and

1./3. + 1./3. + 1./3.

If not, why not? Do you get the same result in Maple?

3. Use Mathematica to do these complex multiplication and division:

a) (10 + 99Â)(10 - 99Â)

b) (10 + 99Â)/ (10 - 99Â)

4. Determine a numerical (floating-point) value for:

a) ln(11)

b) sin( pÅÅÅÅ8 )

5. Mathematica has a bunch of commands that test the properties and types of expressions. These commands end with the letter ``Q'' because they are ``asking a question'', and return either True or False. Several are: MatrixQ, VectorQ, EvenQ, OddQ, IntegerQ, PrimeQ, PolynomialQ, and NumberQ. There are more like these that can be found in the Help menu.

a) Enter the Mathematica statement x:= y = 3 in an Input cell.

b) Test if x is an integer, even, odd, prime, or number.

c) Test for the type(s) of data that y is.

d) Explain your results.

6. Recall some of theMathematica commands we introduced that are used to simplify algebraic expressions. Use whatever commands you need to place

aa + b −

aa − b +

1a

into a simpler form. Add comments to your Input cells explaining what you are doing.

7. Determine the resistance of three resistors in parallel. Circuit theory tells us that the equivalent resistance is1R =

1R1

+1R2

+1R3

54 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 63: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

Determine the simplest form for R.

8. Write the following numbers in scientific notation so that they reflect the given number of significant digits:

a) 25.3 to four significant figures

b) 0.00005 to two significant figures

c) 1.351 to two significant figures

d) 84000 to three significant figures

9. Suppose that the floating-point number system on your computer has two-digit mantissas and exponents ranging from -2 to 1. Indicate whether the following expressions each would result in Overflow, Underflow, Round-off error, or an Exact answer.

a) 20. + 20. b) 50. * 50. c) 20. + 0.01

d) 20. * 0.01 e) 0.01 + 0.01 f) 0.01 * 0.01

10. (Adopted from [Zach 96]) Indicate with an ``R'' or ``F'' which of the following values should be represented with rational numbers and which with floating point numbers?

a) the speed of light

b) the number of protons in an atom

c) the distance from the earth to the moon

d) the acceleration due to gravity on the planet Jupiter

e) the number of megabytes of memory in a computer

11. You are given the expression 10 x4 sin(k x) to use in Mathematica.

a) How would you enter this as a function of the variable x?

b) How would you enter this as a function of the variables x and k?

c) How would you enter this as an expression (an object that takes no explicit arguments)?

d) How would you evaluate the expression for x = 3?

e) How would you evaluate the expression for x = è!!!!y ?

f) How would you evaluate the function for x = 3?

g) How would you evaluate the function for x = è!!!!y ?

12. What is the effect of the following Mathematica Input cells:

a) Print["x/y = ", z/r]

b) D[x^3, x]

c) x = 3

x = .

x

d) N[1/3]

Landau, First Course in Scientific Computing 55

Copyright: Princeton Univ Press, RH Landau, 2005

Page 64: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

e) x^3 /. x->1/3

f) x[z_] := x^5-(1/3)*Cos[z];

?x

13. Explain in just a few words what is meant by:

a) an integer

b) an irrational number

c) a floating-point number

d) truncation error

e) a statement being different from expression

f) x = y not being the same as x := y.

g) a complex number

h) a string

14. Use Mathematica to simplify (to a form that looks simple to you)

a) x + 2ÅÅÅÅÅÅÅÅÅÅÅÅx

b) Hx2 + 1L è!!!xÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅx

15. Consider a tachyon with mo c2 = 1. Determine its energy for vÅÅÅÅc = 3, 2, 1.

16. Assign the variable y to the expression pÅÅÅÅ6 , and then evaluate y3 , y81ê3< , and Tan[y] both exactly and numerically.

17. Express y8 - 2y4 + 1 as the product of factors.

18. For a = 9.2, b = 1.5, and c = 100, evaluate "################2 a - 3 b2ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅc3- 20 .

56 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 65: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

Chapter 4: Visualization, Abstract Data Types; Electric Fields

4.1 Why Visualization?

One of the most rewarding uses of computers is visualizing the results of calculations. This is done with 2-D and 3-D plots (especially with colored surfaces), with contour maps, and with animations. These types of visualization can be breathtak-ingly beautiful and often provide deep insight into a problem by letting you see and ``handle'' the functions with which you are working. Visualization also assists the program debugging process, the development of physical and mathematical intuition, and the all-around enjoyment of your work. Some of the reasons for this may arise from the fact that some large fraction (~50%) of our brain gets involved in visual processing, and if you can use this extra brain power in your scientific work, then you have extended what was otherwise possible with solely logical abilities.

Traditionally, visualization of a scientific problem was the last step in problem solving. After studying table of numbers for hours and gaining confidence that they are right, a scientist might then go to the trouble of making a bunch of 2-D plots to examine various aspects of data. Well, in present times computational scientists have demonstrated how much there is to be gained by going beyond 2-D plots. Now it is regular practice to use surface plots, volume rendering (dicing and slicing), and animations (movies). In this chapter, we use some of these techniques within the context of visualizing the electric potential around charges.

4.2 Problem: Stable Points in Electric Fields

Figure 4.1 Static configuration for two, three, and four charges (the charges are at the corners).

You are given some simple configurations of two, three, and four charge systems, as shown in the Fig. 4.1. The two charges are fixed on a line at coordinates (1,0), (-1,0); the three charges are fixed to the corners of an equilateral triangle at coordinates (0,1), (è!!!3 /2, -1/2), (-è!!!3 /2, -1/2); and the four charges are fixed to the corners of a square at coordinates (1,1), (1,-1), (-1,-1), (-1,1). The origin is at the center of each geometric figure. Your problem is to determine the electri-cal potential at the arbitrary point (x,y) and see if there might be some points in space at which we can place a charge that is free to move and have it remain there even if perturbed. (For the equivalent gravitational problem these stable points are known as Lagrange points and are the location of asteroids for the earth-sun system.)

Landau, First Course in Scientific Computing 57

Copyright: Princeton Univ Press, RH Landau, 2005

Page 66: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

4.3 Theory: Stability Criteria for Potential Energy

Coulomb's law tells us that if we have a charge q at the origin, then the electric field E (the force per unit charge) at a distance r from that charge is

EHrL =ke qÅÅÅÅÅÅÅÅÅÅÅÅÅr2 r

where r is a unit vector in the radial (r) direction. Here ke = 8.9875 109 N m2 /C2 is Coulomb's constant in SI units, and the electric force E is directed radially away from the charge. Because E is a vector, the electric force field about a charge is a vector field with both magnitude and direction at each point. However, no information is lost, and it's much simpler, if, instead of the electric field E, we consider the electric potential field

V HrL =ke qÅÅÅÅÅÅÅÅÅÅÅÅÅ

r=

qÅÅÅÅÅr

In the second form of this equation we have left off the electric constant ke for simplicity; since this affects just the magnitudes of the graphs and not their shapes, it will not change the conclusions we draw. We see that V(r) falls off less rapidly than E(r) and is a scalar, that is, has no direction associated with it.

Our problem requires us to determine the potentials for two- and three-charge systems, and then to look for stable points in these potentials. To determine the potential for two charges, we use Pythagorean's theorem to determine the distance to the charges,

r1 = "###########################Hx - aL2 + y2 , r2 = "###########################Hx + aL2 + y2

and then just add up the potentials from the individual charges:

V2Hx, yL =q1

ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ"#########################Hx - aL2 + y2+

q2ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ"#########################Hx + aL2 + y2

For three charges at the corners of the equilateral triangle, we know the coordinates are (0,a), (a cos q, -a sin q), (-a cos q, -a sin q), where q = 30 degrees. Again we use Pythagorean's theorem and add the potentials from the individual charges to obtain

V3Hx, yL =q1ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ"##########################x2 + Hy - aL2

+q2ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ"##########################################################Hx - a cos qL2 + Hy + a sin qL2

+q3ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ"##########################################################Hx + a cos qL2 + Hy + a sin qL2

These equations for the electric potentials are what we wish to visualize. To make them simpler to visualize, we set a = 1 and substitute for q:

V1Hx, yL =q1ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅè!!!!!!!!!!!!!!!x2 + y2

, V2Hx, yL =q1ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ"#########################Hx - 1L2 + y2

+q2ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ"#########################Hx + 1L2 + y2

V3Hx, yL =q1ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ"#########################x2 + Hy - 1L2

+q2ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Ix -

è!!!!3ÅÅÅÅÅÅÅÅÅÅ2 M2+ Hy + 1ÅÅÅÅ2 L2

+q3ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ$%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%Ix +

è!!!!3ÅÅÅÅÅÅÅÅÅÅ2 M2+ Hy + 1ÅÅÅÅ2 L2

Owing to its two dimensional nature, a purely mathematical solution for the equilibrium points in these potential gets complicated. Instead, we will solve it graphically and rely on our intuitive understanding of how balls roll under the action

58 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 67: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

of gravity. Specifically, we know that a ball released on a surface rolls downhill, and that if the ball is placed in a concave depression, it will remain there. Because the gravitational potential near the Earth's surface is proportional to height, our description of the ball on a surface is equivalent to a description of how a particle behaves in a potential energy field. It therefore follows that charges will ``roll down'' the electric potential surface, and will find a stable position at the con-cave minimum of the potential. So our problem translates into drawing pictures of the electric potential surfaces and looking for minima at the bottom of hills.

4.4 Basic 2-D Plots: Plot

Before we get to Maple's plotting commands, let us examine some general principles. First, keep in mind that the point of visualization is to make the science clearer and to better communicate your work to others. So it follows that when you produce a figure you should look at it and think if there are some better choices of units, ranges of axes colors, style, et cetera that might get the message across better and provide better insight. Taking into account that we are dealing with the complexity of human perception and cognition, there may not be one definite way to do things, and some trial and error is necessary to see what looks best.

Our general recommendation for visualization is to make each figure as clear, informative and self-explanatory as possible. This means labels for various curves and data points, a title, and labels on the axes. We know, you are thinking that this is really a lot of work for a lousy assignment or report, and that you do not need all those time-consuming extras to compre-hend what is going on. Yet the more often you do it, the quicker and better you get at it, and the more useful will your work be to others (and yourself in the future).

The convention when plotting is to have the independent variable, say x, along the abscissa (horizontal axis), and the dependent variable, say y=f(x), along the ordinate. (Remember that your mouth spreads horizontally across when you say ``abscissa'', and that it puckers vertically up when you say ``ordinate''.) If you have trouble deciding which variable is independent, think of an experiment in which you measure the position or velocity of a ball as a function of time. Because you are free to pick the times at which you make the measurement, time is an independent variable. However, once you have chosen the time, nature picks what the position of the ball is at that particular time, so position and velocity are dependent variables.

Mathematica excels at easily producing graphs of all sorts, and indeed, visualization is one of the most valuable aspects of Mathematica. While we will discuss and give examples of a number of possible plots, Mathematica offers you more options than we discuss, and we recommend you browse the Help pages to create just the graph you want. Unlike Maple, where you need to load the graphics tools before you use them, the basic graphics tools in Mathematica are contained in the standard package and can be used without loading. However, we will need to load specific packages later as we go beyond the basics. We will first make a simple plot and then embellish it with things like labels and colors. Let us start by looking at the electric potential for a single charge (using our natural units) at the origin as defined by a function V(r).

In[1]:= V@r_D := 1êrH∗ Remember underscore needed to define function, not when used ∗L? VNull

Global`V

V@r_D := 1r

Landau, First Course in Scientific Computing 59

Copyright: Princeton Univ Press, RH Landau, 2005

Page 68: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[4]:= Plot@V@rD, 8r, 0, 1<D H∗ Plot previously defined function ∗L

0.2 0.4 0.6 0.8 1

50100150200

Out[4]= Graphics

You will observe from the figure that the second argument to the Plot command is a list that gives the range of values for the abscissa (r in this case). Our interest is really for r between 0 and infinity, but this does not produce such a useful result since we mainly see the repulsive peak at the origin. So we can get a more revealing plot by not letting r get quite so close to the origin:

In[5]:= Plot@V@rD, 8r, 1ê50, 1<D

0.2 0.4 0.6 0.8 1

1020304050

Out[5]= Graphics

However, the plot has left out the r=0 part of the graph, and so does not fully convey the image that the potential is infinite there. We can tailor our plot more to our liking by giving some limits to the ordinate (also works if called generic y):

In[6]:= Plot@V@rD, 8r, 0, 1<, PlotRange → 880, 1<, 80, 10<<DH∗ Limit y range Hcute,huh!L ∗L

0.2 0.4 0.6 0.8 1

246810

Out[6]= Graphics

In[7]:= Plot@Min@V@rD, 10D, 8r, 0, 1<DH∗ Keep ordinate <10 another way ∗L

0.2 0.4 0.6 0.8 1

2

4

6

8

10

Out[7]= Graphics

As an alternative, you can tell Mathematica that you want to see the full dependence of the potential from r=0 to ¶, although you may lose some details:

60 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 69: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[8]:= Plot@V@rD, 8r, 0, Infinity<DPlot::plln :

Limiting value ∞ in 8r, 0, ∞< is not a machine−size real number.

Out[8]= Plot@V@rD, 8r, 0, ∞<D

Well, it didn't like that. You can try leaving off the range for the abscissa as well, to see how smart Mathematica really is:

In[9]:= Plot@V@rDDPlot::argmu : Plot called with 1 argument; 2 or more arguments are expected.

Out[9]= Plot@V@rDD

You see that because Mathematica was not given a range of r values to plot, it throws an error since it expects two or more arguments. Pretty smart!

The plot above shows the basic physics. If we view V(r) as an equivalent gravitational potential, a small positive charge (mass) placed near the fixed positive charge will be repelled (roll downhill) out to infinity. There are not any locations where a charge remains at rest in equilibrium. If we had fixed a negative charge at the origin, the potential would have the opposite sign:

In[10]:= Plot@−V@rD, 8r, 0, 1<, PlotRange −> 880, 1<, 80, −10<<D0.20.40.60.8 1

-10

-8

-6

-4

-2

Out[10]= Graphics

This shows that, regardless of where we place it, our positive test charge will fall into the hole at the origin. As we have just seen by placing a minus sign in front of the first argument to the command, it is allowable to have the argument be an expression and not just a function:

Landau, First Course in Scientific Computing 61

Copyright: Princeton Univ Press, RH Landau, 2005

Page 70: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[11]:= Plot@−5êr, 8r, 0, 5<, PlotRange → 880, 5<, 80, −20<<DH∗ Plot explicit expression ∗L

1 2 3 4 5

-20-17.5

-15-12.5

-10-7.5-5

-2.5

Out[11]= Graphics

In summary, the first argument to the Plot command is the name of the function or expression to be plotted along the ordinate, that is, the dependent variable. The second argument is the range of values for abscissa, that is, the independent variable. The range is specified in a list containing the name of the independent variable, the minimum value, and the maximum value, e.g., x, -10, 10. In order to place a range on the ordinate, the PlotRange option must be used. Options are rules indicated by an arrow ->, with the arguments enclosed in curly braces.

After evaluating the command you may notice the -Graphics- description following the produced graph. This indicates that the plot is a ``graphics'' object, which can be manipulated. The description may be suppressed by placing a semicolon ; to the right of the Plot command. Try putting a semicolon after the last Plot command and re-evaluate the cell. We will do this for the rest of our examples.

Before we get on to embellishing the Plot command, let us have some fun with the pretty graph you just produced:

- Click on the graph to select it.

- Note how a box is formed around the selected graph and that there are dark little nodes at the corners and in the middle of the sides.

- Use your mouse to resize the graph by grabbing one of the nodes, and then dragging it with the mouse button still depressed. Notice that when a node is selected, a little two-sided arrow appears to show you the direction in which the frame can be resized. The resizing can be done diagonally along the corners or horizontally and vertically along the edges. [If you find that you can only resize diagonally, with both sides having the same ratio, then the AspectRatioFixed option under Graphics Options needs to be changed to False. To do this, make sure your graph is selected, then open the Format menu and choose Option Inspector.... A separate window

will appear where you can click on the arrow next to Graphics Options, then Image Bounding Box. You will then see the property that needs to be changed in order to resize your graph any way you wish.]

- Select the graph, copy it (it's placed on the ``clipboard''), and then paste it back to the notebook so that now you have two graphs.

- Make one of your graphs into a long, narrow one, and the other into a high, tall one. Notice how the tall one emphasizes the variation in the magnitude of V(r), while the long one emphasizes the range of r values to which V(r) extends. Both are perfectly legitimate ways to view a function. One emphasizes the singular nature near the origin, the other the long range of the potential.

- Another way to view a function, especially one that has orders of magnitude variation in value, is with a semilog plot or a log-log plot. (Note, however, that you cannot take the log of 0). In the Input cell below, use the Log[10, z] function to see how a semilog plot changes the appearance of the same f(x) we have been viewing. Follow the instructions in the comment fields below:

In[12]:= H∗ Repeat plot with Log@10,V HrLD ∗L

Next try the explicit semilog plot function, LogPlot.

62 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 71: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

à 4.4.1 Loading Graphics Package

Before attempting to use that function, we need to load the Graphics package, which contains it. For many calculations the standard Mathematica package is sufficient, but often you may need more specialized functions and procedures that are not loaded with Mathematica, but are found in various Mathematica packages. They are loaded with the << command:

In[1]:= << Graphics`Graphics`

where Graphics is the name of the package (folder) in Mathematica's StandardPackages, and Graphics.m is the name of the file being loaded. You may also load this file from a specific location (if you know the absolute path of the package), using the Get command:

In[2]:= H∗ Get@"Graphics.m",Path→8"êusrêlocalêmathematicaêAddOnsêStandardPackagesêGraphicsê" <D ∗L

Notice how both arguments are enclosed in quotes, and the Path option in curly braces.

Once a package is loaded you can get a list of the functions it contains by using the Names command:

In[2]:= Names@"Graphics`Graphics`∗"DOut[2]= 8BarChart, BarEdges, BarEdgeStyle, BarGroupSpacing, BarLabels, BarOrientation,

BarSpacing, BarStyle, BarValues, DisplayTogether, DisplayTogetherArray,ErrorListPlot, GeneralizedBarChart, Histogram, LabeledListPlot,LinearLogListPlot, LinearLogPlot, LinearScale, ListAndCurvePlot,LogGridMajor, LogGridMinor, LogLinearListPlot, LogLinearPlot, LogListPlot,LogLogListPlot, LogLogPlot, LogPlot, LogScale, PercentileBarChart,PieChart, PieExploded, PieLabels, PieLineStyle, PieStyle, PiScale,PolarListPlot, PolarPlot, ScaledListPlot, ScaledPlot, SkewGraphics,StackedBarChart, TextListPlot, TransformGraphics, UnitScale<

An easy mistake is trying to use a command before its package has been loaded, then loading the package, and then trying to use the command again. This leads to an error message due to the way the command was initially entered into the symbol table. You need issue the Remove[command name]command before loading the package. For example, enter:

In[3]:= Show@Graphics3D@[email protected], 0.5DDD;Graphics3D::gprim : [email protected], 0.5D was encountered

where a Graphics3D primitive or directive was expected.

The blue error message is a reminder that Shapes package containing the Cylinder graphics primitive was not loaded, so we do it now:

In[4]:= << Graphics`Shapes`Show@Graphics3D@[email protected], 0.5DDDGraphics3D::gprim : [email protected], 0.5D was encountered

where a Graphics3D primitive or directive was expected.

Out[5]= Graphics3D

Typing the command again does not give us the expected graph because we now have two symbols Cylinder, and the one introduced before the loading of the package takes precedence. Now the Remove command is handy:

In[6]:= Remove@CylinderD

Landau, First Course in Scientific Computing 63

Copyright: Princeton Univ Press, RH Landau, 2005

Page 72: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[7]:= << Graphics`Shapes`Show@Graphics3D@[email protected], 0.5DDD; H∗ That' s better! ∗L

While speaking of packages, you can easily check which packages you have loaded:

In[9]:= $Packages H∗ Check whick packages are loaded ∗LOut[9]= 8Graphics`Shapes`, Geometry`Rotations`, Utilities`FilterOptions`,

Graphics`Common`GraphicsCommon`, Graphics`Graphics`, Global`, System`<

Now that the Graphics package is loaded, we can try out the LogPlot command:

In[10]:= LogPlot@x^2, 8x, 0, 10<D;

0 2 4 6 8 101.×10−8

1.×10−6

0.0001

0.01

1

100

In[11]:= H∗ Try log−log plot here using LogLogPlot command ∗LLogLogPlot@x^2, 8x, 0, 10<D;

0.20.5 1 2 5 10

0.1

1

10

100

à 4.4.2 Labels and Titles (the plot thickens)

Any plot worth looking at is worth explaining. This is done by placing labels along the axes and by placing a title above the curves. Here, try this:

64 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 73: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[12]:= Plot@1êr, 8r, 1ê10, 5<, AxesLabel → 8"radius r", "VHrL"<,PlotLabel → " Potential for point charge"D;

1 2 3 4 5radius r

246810VHrL Potential for point charge

Take stock of how we just add a comma after the range list (in braces) and then added the label and title options (with arrows), separated by commas. Look carefully at the syntax for each option, and notice how they are really rules with the arrow Ø pointing towards a list. Since there are two axes, the AxesLabel option contains a list of entries, one for the x axis, and one for the y axis. The PlotLabel option requires only one string, hence no curly braces needed. Notice next that the labels and title are enclosed in double quotes. When you input a string of text to Mathematica you must always enclose it in double quotes. The only type of quotes allowed are the double quotes.

The quotes in Mathematica are used to define an alphanumeric string. A string is just a literal recording of whatever characters are within the quotes; the computer does not try to interpret a string as either variables or numbers. You can put anything you want within the string and it will get pasted into your plot. Modify the previous command so that the words ``abscissa'' and ``ordinate'' appear in the appropriate places and so that the actual expression being plotted appears in the title:

In[13]:= H∗ Plot with your modified labels and title ∗L

In a later section we will discuss how to place a legend on your graphs to identify an individual curve on a multicurve graph. You may have already noticed that we have placed r along the "x'' axis and V(r) along the "y'' axis. Since this is a free world, we may also call y the independent variable at times. So you see already why the words ordinate and abscissa were invented (to avoid confusion).

4.5 Compound (Abstract) Data Types, [..] and ..

As we proceed with our exercises in visualization, you will see how to enter arguments to the Plot commands using different types of parentheses. We recognize that some users may prefer just following the rules without questioning them. Nevertheless, the commands will make more sense, and will be easier to generalize, if you have some understanding of the method behind the madness. And so we now take a little excursion in which we define some terms that are frequently used in mathematics and computer science and employed by Mathematica commands.

We have already seen a number of ways in which Mathematica displays data. Sometimes there's just a single symbol, sometime's there's a bunch of symbols separated by commas, sometimes there's a bunch of things in curly braces, and sometimes not. For example, in Chap. 5 you will see that when the Solve command produces several solutions, Mathemat-ica separates them with commas and lists them in curly braces:

Landau, First Course in Scientific Computing 65

Copyright: Princeton Univ Press, RH Landau, 2005

Page 74: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[14]:= Solve@x^4 − 1 0, xDOut[14]= 88x → −1<, 8x → − <, 8x → <, 8x → 1<<

Take note of two types of parentheses here.

Abstract or Compound Data Types: An object in Computer Science denotes a data type with multiple parts. It may also be called an abstract data type, or a compound data type. Here the word ``abstract'' means that there is more to something than meets the eye, that is, the data type may contain multiple parts. Many of the individual symbols or variables used in Mathematica can be replaced by objects. We will discuss objects in more depth when we study Java, which is known as an object oriented language.

Sequence: A collection of objects separated by commas is called a sequence in mathematics. Note that the arguments given to this Solve command, and indeed to most Mathematica commands, are variables or rules separated by commas, and accordingly form sequences. The square brackets indicate an argument to the function (as discussed in Chapter 2), so in these cases the function argument is a sequence.

List: In Mathematica the way to make collections of objects is with a list. Lists are important and general structures (objects themselves) that contain comma-separated objects within curly braces .... Sometimes the order of objects within a list matters, and sometimes it doesn't. An example of when the order matters can be found in the Plot command:

In[15]:= Plot@x^3, 8x, 1, 5<D;

2 3 4 5

20406080100120

Within the second argument list it is clear that order matters because the maximum and minimum are different. However, order does not matter within the list of solutions that the Solve command produces. All of the solutions are equally valid. Therefore, it is the purpose of the list which determines whether the order of objects matters or not.

Arrays: Another data type related to vectors and matrices are arrays. We discuss them in Chapter 7.

à 4.5.1 Several Curves on One Plot

We have seen that the first argument to the Plot command is the function to be plotted; e.g:8xHtL, vHtL, aHtL<For our electric potential problem, we may want to compare the r dependence of the potential and the magnitude of the electric field due to a positive charge to those due to a negative charge. We know that the potential falls off as 1/r and the force as 1/r2 . In cases such as this, where there are several functions and all are functions of the same independent vari-able (radius r here), it may be illuminating to plot all functions on the same graph. Since Mathematica treats the argument as an object, it can be an abstract data type, and we can substitute the list81 ê r, -1 ê r, 1 ê r2, -1 ê r2<as the first argument to the Plot command. The fact that we used a list as the object to plot makes sense if you recall that any time a collection of expressions is needed, lists are used in Mathematica. In this case the order of the list does not matter, because the order of plotting does not matter. (Also note that for the sake of clarity to you, we try to include spaces after commas. Mathematica doesn't care one way or the other.)

Experiment now with the Plot command for a list of functions:

66 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 75: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[16]:= H∗ List as first argument ∗LPlot@81êr, −1êr, 1êr^2, −1êr^2<,8r, 1ê10, 5<, PlotRange → 881ê10, 5<, 8−20, 20<<,PlotStyle → [email protected]<, [email protected]<, [email protected]<, [email protected]<<,AxesLabel → 8"r", "V, E"<D;

2 3 4 5r

-20-15-10-5

5101520V, E

Notice that for small r the force diverges more rapidly than the potential, while for large r the force dies off more rapidly. Finally, note how each function has a different color. This is due to the PlotStyle option within the Plot command. Mathematica does not automatically color the graphs, but rather the user must specify the colors; we will talk about this more later.

à 4.5.2 Customizing Colors and Line Types

It is important to distinguish the various curves on a plot since Mathematica will draw them all with the same size line in the color black unless you specify otherwise. Keep in mind that you want colors and lines that look great on the screen as well as on printouts or projections (green and yellow are often barely visible). Graphics options (uses Ø) are used to specify how the graphical elements should be drawn. The option PlotStyle is used to specify the style of a graph:

PlotStyle → style H∗ If only one style option is used ∗LPlotStyle → 8style1, style2, ...< H∗ If several style options are needed,ie more than one curve is on the graph ∗L

Some of the most common styles include those functions which allow graphs to be drawn in color, or grayscale:

è GrayLevel[x] with 0 § x § 1, allows for lightening of the image. Values of x closer to 1 will make the image appear lighter.

è Hue[h] is color specification. As h is varied from 0 to 1, the color runs from red, yellow, green, cyan, blue, magenta, and back to red.

è Hue[h, saturation, brightness] specifies colors in terms of their hue, saturation, and brightness. Each has values between 0 and 1.

è RGBColor[red, green, blue] specifies a color with certain mixture of red, green, and blue components, each between 0 and 1. For example, RGBColor[0,1,0] produces pure green. An easy way to compute an RGB formula is to go to Input menu and choose ColorSelector to click on the color of your choice. The RGB formula for that color will be placed into your Mathematica notebook at the cursor position.

è CMYKColor[cyan, magenta, yellow, black] specifies a color with certain mixture of cyan, magenta, yellow, and black, each between 0 and 1. This is used for printing colored graphics on paper.

Landau, First Course in Scientific Computing 67

Copyright: Princeton Univ Press, RH Landau, 2005

Page 76: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[17]:= Plot@81êr, 1êr^2, r<, 8r, 0, 1.5<,PlotRange → 880, 1.5<, 80, 10<<, PlotStyle → 8RGBColor@1, 0, 0D,RGBColor@0, 0, 1D, [email protected], 0.172549, 0.258824D<D;

0.2 0.4 0.6 0.8 1 1.2 1.4

2

4

6

8

10

In the previous plot the first two curves are colored red and blue respectively, while the ColorSelector was used to pick a maroon color for the third. The PlotStyle option is also used to specify the style of line used for various curves. We can add a list of styles containing the type of lines for each graph. An especially effective way to distinguish different curves on the same plot without the use of color, is to draw them with different thickness, which you can try below:

è Dashing[r1, r2, ...] shows the lines as a sequence of dashed segments and spaces of lengths, r1, r2, ... repeated cyclically. Each r value is given as a fraction of the total width of the graph. If you wish to distinguish curves with dashing, they each need their own Dashing function.

è AbsoluteDashing[a1, a2, ...] similar to Dashing but uses absolute units to measure dashed segments. The absolute lengths are measured using printer's measure, approximately 1/72 of an inch.

è Thickness[r] gives the lines a thickness r as a fraction of the width of the graph. The default value for 2-D graphs is 0.004.

è AbsoluteThickness[r] gives the lines a thickness r measured in absolute units, defined the same as above.

68 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 77: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[18]:= Plot@81êr, 1êr^2, r<, 8r, 0, 1.5<, PlotRange → 880, 1.5<, 80, 10<<,PlotStyle → [email protected]<D, [email protected]<D, [email protected]<D;

0.2 0.4 0.6 0.8 1 1.2 1.4

246810

à 4.5.3 Legends

Legends explain to the reader just what is being plotted with each curve. They are invaluable and do wonders for your presentation. When presenting several curves in one graph, it is important that the viewer not only be able to tell them apart by the different color or line style used for each, but also be given information as to what the different curves represent. It is good practice to explain in the caption below a graph what each curve means, as well as in the text (or in your talk) when the graph gets referenced. However, it is also good practice to have a legend in the plot itself explaining what each curve means. Captions and text may get removed, but it is a lot harder to remove a good legend.

The legend option for the Plot command is PlotLegend[text1, text2, ...] which attaches strings text1, text2, ... to each description in PlotStyle, in the order of the curves. If there are more PlotStyle descriptions than text descriptions, the text will be repeated cyclically. PlotLegend is contained within the Graphics`-Legend` package and must be loaded before use:

In[19]:= << Graphics`Legend`

Landau, First Course in Scientific Computing 69

Copyright: Princeton Univ Press, RH Landau, 2005

Page 78: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[20]:= Plot@81êr, 1êr^2, r<, 8r, 1ê50, 1.5<, PlotRange → 881ê50, 1.5<, 80, 25<<,PlotStyle → [email protected]<D, [email protected]<D, [email protected], .08<D<,PlotLegend → 81êr, 1êr2, r<, LegendPosition → 8.5, .2<D;

0.2 0.4 0.6 0.8 1.2 1.4

5

10

15

20

25

r

1r2

1r

The LegendPosition option is used with the legend to place it conveniently. The default position for the legend is in the lower left corner of the graph and will most likely cover important portions of the plots. Hence, you will want to tweak the position coordinates in the command to place the legend where you wish. Other display options for the legend can be found in the Graphics`Legend` package.

à 4.5.4 Other Options

There are many ways to customize your graph, and the Help browser is a good place to find out about them. Here we look at a few. When Mathematica plots, it tries to scale the x and y axes to show only the most interesting features of the plot. Therefore, if your function gets too large, or has singularities, those parts may be cut off. This is the different from Maple, which automatically adjusts the ordinate's range to accommodate large variations. The PlotRange option can be used to specify exact ranges of x and y for your plot. For example, Tan[x] would normally overshadow Sin[x, but Mathemat-ica automatically limits the y range so that all functions are shown:

In[21]:= Plot@8Sin@xD, Tan@xD, x<, 8x, −Pi, Pi<,PlotStyle → 8RGBColor@1, 0, 0D, RGBColor@0, 0, 1D, RGBColor@0, 1, 0D<D;H∗ Vertical limits automatic ∗L

-3 -2 -1 1 2 3

-10-5

51015

In[22]:= Plot@8Sin@xD, Tan@xD, x<, 8x, −Pi, Pi<, PlotStyle →8RGBColor@1, 0, 0D, RGBColor@0, 0, 1D, RGBColor@0, 1, 0D<, PlotRange → AllD;H∗ PlotRange set to s how all points. Tan@xD overshadows Sin@xD and x ∗L

-3 -2 -1 1 2 3

-800-600-400-200

200

70 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 79: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[23]:= Plot@8Sin@xD, Min@10, Tan@xDD, x<, 8x, −Pi, Pi<,PlotStyle → 8RGBColor@1, 0, 0D, RGBColor@0, 0, 1D, RGBColor@0, 1, 0D<D;H∗ Another way to force limiting the vertical, if need be ∗L

-3 -2 -1 1 2 3

-10-5

510

Sometimes a function falls off slowly, and so you might want to see its behavior for values of its argument from negative to positive infinity. While Maple allows plots like this, Mathematica appears to be too picky:

In[24]:= Plot@Exp@−x^2D, 8x, −∞, ∞<, PlotLabel −> "Gaussian"D;Plot::plln :

Limiting value −∞ in 8x, −∞, ∞< is not a machine−size real number.

In[25]:= H∗ Try to find a good x range and use

PlotRange to get an interesting graph of −x2 ∗L

Another Plot option to explore is PlotPoints. Mathematica always tries to plot functions as smoothly as possible, and so Mathematica will use more points in the region where your function is highly oscillatory, rather the default of 25 points:

Landau, First Course in Scientific Computing 71

Copyright: Princeton Univ Press, RH Landau, 2005

Page 80: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[26]:= Plot@Sin@1êxD, 8x, −1, 1<D;-1 -0.5 0.5 1

-1

-0.5

0.5

1

Use PlotPoints to sample the above function with more points. Is it better or worse? Remember that the larger the value of PlotPoints, the longer it will take Mathematica to plot the function, but it can be most helpful at times.

4.6 3D (Surface) Plots of Analytic Functions

We have examined the potential field V(r) = 1/r surrounding a single charge as a function of r. A 2-D plot is fine for this since there is only one independent variable r. However, when the same potential is expresses as a function of the Carte-sian coordinate x and y,

V Hx, yL =1

ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅè!!!!!!!!!!!!!!!!x2 + y2,

we have two independent variables, x and y, and so need a 3-D visualization. We get that by creating a world in which the z dimension (mountain height) is the value of the potential, and x and y lie on a flat plane below the mountain. Because the surface we are creating is a 3-D object it is not possible to draw it on a flat screen, and so different techniques are used to give the impression of three dimensions to our brains. We do that by rotating the object, shading it, employing parallax, and so forth.

-4 -2 0 2 4x -4

-20

24

y00.51

1.522.5

VHx,yL-4 -2 0 2 4

x

The command to make a 3-D plot is Plot3D, and in many ways is like our old friend Plot:

In[27]:= Clear@x, y, VDV@x_, y_D := 1êSqrt@x^2 + y^2D;H∗ Define function of two variables ∗L? V

Global`V

V@x_, y_D := 1è!!!!!!!!!!!!!!x2+y2

72 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 81: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[30]:= Plot3D@V@x, yD, 8x, −4, 4<, 8y, −4, 4<D; H∗ Basic form of Plot3D ∗L

-4 -2 0 2 4 -4-2

02

40.20.40.60.8

-4 -2 0 2 4

This is a pretty interesting plot showing (what should be) the singular nature of the potential near the origin, but it is rough looking. The option PlotPoints specifies the number of points to be used to produce the graph in each direction. The default value for a 3-D plot is 15, but as you can see, this leads to ragged surfaces on many graphs. Let us try the same plot, but with more point:

In[31]:= Plot3D@V@x, yD, 8x, −4, 4<, 8y, −4, 4<, PlotPoints → 40D;-4

-2 02

4 -4-2

02

40.20.40.60.8

-4-2 0

24

We get more information yet if we extend the z-axis range higher. We do that with the PlotRange option for the z range (and also add some labels):

In[32]:= Plot3D@V@x, yD, 8x, −4, 4<, 8y, −4, 4<, PlotPoints → 40,PlotRange → 80, 2.5<, AxesLabel → 8"x", "y", "VHx,yL"<D;

-4-2

02

4x -4

-20

24

y00.51

1.522.5

VHx,yL

-4-2

02

4x

à 4.6.1 Contours and Equipotential Surfaces

To make your mind understand that different colors mean different potential values, we now use the ContourPlot command to produce contour lines showing the different levels of the potential:

In[33]:= Clear@x, y, VDV@x_, y_D := 1êSqrt@x^2 + y^2D; H∗ Define a function of two variables ∗L? V

Global`V

V@x_, y_D := 1è!!!!!!!!!!!!!!x2+y2

Landau, First Course in Scientific Computing 73

Copyright: Princeton Univ Press, RH Landau, 2005

Page 82: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[35]:= ContourPlot@V@x, yD, 8x, −4, 4<, 8y, −4, 4< D;

-4 -2 0 2 4-4

-2

0

2

4

In analogy to gravity, the contour lines can be thought of as lines of equal elevation. If you walked along a contour line, your elevation would not change. Imagine the plot above in three dimensions: it would look like a mountain with rings around it. Therefore a trip around one of the rings would be at constant elevation. (For a visual cue look at the correspond-ing Chapter 4.5.1 section in the text book). For our electrical potential problem, the contours correspond to the locust of points in space with the same potential, and are called equipotential surfaces (even if they are just lines). Likewise, no work is done if a charge is moved along an equipotential surface (there may be a force on the charge, but it is perpendicu-lar to the surface). We see the circles that are expected for the symmetric case of a single charge, but they are rather grainy. That' s a clue that Mathematica's algorithm for contours is probably not evaluating the function with enough points, so we increase the number:

74 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 83: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[36]:= ContourPlot@V@x, yD, 8x, −4, 4<, 8y, −4, 4<, PlotPoints → 30D;

-4 -2 0 2 4-4

-2

0

2

4

That looks better! However, we prefer the Maple 3-D contour surface in which the contours are on the surface. [Mathemat-ica does have a ContourPlot3D command under the Graphics package. It plots the surface implicitly defined by fun[x, y, z] == 0, and only contour surfaces for specified values. This does not work with our function.]

4.7 Solution: Dipole and Quadrupole Fields

We have used a number of visualization tools to examine the potential field surrounding a single positive and single negative charge. The tools only showed us what we probably knew already, namely that the potential field does not have concave areas in which a charge may remain stably at rest. This was as intended; it is a good idea to learn about new tools on problems for which you know the right answer. We are now in the position to finally investigate the electric potential due to a dipole and tripole. Let us start with the dipole configuration, as shown in Figure 4.2. We know that the potential is

V2Hx, yL =q1ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ"#########################Hx - 1L2 + y2

+q2ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ"#########################Hx + 1L2 + y2

We start by defining a Mathematica function

In[37]:= Clear@V, x, yDv2@x_, y_, q1_, q2_D := q1êSqrt@Hx − 1L^2 + y^2D + q2êSqrt@Hx + 1L^2 + y^2D;?v2

Global`v2

v2@x_, y_, q1_, q2_D := q1è!!!!!!!!!!!!!!!!!!!!!!!!Hx−1L2+y2+ q2è!!!!!!!!!!!!!!!!!!!!!!!!Hx+1L2+y2

Now we visualize it with the 3-D plots and contours. First we try a classic dipole with one positive and one negative charge:

In[40]:= q1 = 1;q2 = −1;Print@"q1 = ", q1DPrint@"q2 = ", q2Dq1 = 1

q2 = −1

Landau, First Course in Scientific Computing 75

Copyright: Princeton Univ Press, RH Landau, 2005

Page 84: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[44]:= Plot3D@v2@x, y, q1, q2D, 8x, −3.5, 3.5<, 8y, −3.5, 3.5<,AxesLabel → 8"x", "y", "v2@x,yD"<, PlotPoints → 50D;

-20

2x-2

0

2

y

-0.50

0.5v2@x,yD

-20

2x

If you change the viewpoints and replot, you will see that wherever you place a charge it will either roll downhill away from the positive charge, or fall into the hole of the negative charge. This means that there is no stable point. So let us look at two charges of the like sign:

In[45]:= q1 = 1;q2 = 1;Plot3D@v2@x, y, q1, q2D, 8x, −3.5, 3.5<, 8y, −3.5, 3.5<,

AxesLabel → 8"x", "y", "v2@x,yD"<, PlotPoints → 40D;H∗ Enter command to make 3−D plot for two positive charges ∗L

-20

2x-2

0

2

y0.51

1.52

v2@x,yD

-20

2x

In[48]:= H∗ Enter command to make 3−D plot for two negative charges ∗L

Interestingly enough, the figure (which looks like a saddle) has a region between the two peaks where it appears that a charge can remain at rest. In addition, if the charge is displaced along the positive or negative x axis, it will roll back towards the midpoint. This means that the midpoint position is stable for disturbances in the x direction. However, if the test charge has a component of displacement in the y direction, then it will roll away to infinity, clearly not a stable thing to do. This type of shape is known as a saddle point. It occurs for two positive or two negative charges. If the charges have unequal values, then the shape gets distorted, but still has the same property. As a check on our analysis, let us look at the contours for this surface:

In[49]:= H∗ Make a contour 3−D here− still not sure how to do this!!! ∗L

We see the saddlepoint structure as a single point where two equipotential surfaces cross.

Let us now look at the quadrupole potential (we leave the tripole for you). Our intuition tells us that the high degree of symmetry here must lead to a stable position at the center. We define the potential and then we plot it as a 3-D surface and as 3-D contours:

76 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 85: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[50]:= v4@x_, y_D := 1êSqrt@Hx − 1L^2 + Hy − 1L^2D + 1êSqrt@Hx − 1L^2 + Hy + 1L^2D +

1êSqrt@Hx + 1L^2 + Hy − 1L^2D + 1êSqrt@Hx + 1L^2 + Hy + 1L^2D;?v4

Global`v4

v4@x_, y_D := 1è!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Hx−1L2+Hy−1L2 + 1è!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Hx−1L2+Hy+1L2 + 1è!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Hx+1L2+Hy−1L2 + 1è!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Hx+1L2+Hy+1L2

In[52]:= Plot3D@v4@x, yD, 8x, −3.5, 3.5<, 8y, −3.5, 3.5<,AxesLabel → 8"x", "y", "v4@x,yD"<, PlotPoints → 40D;

-20

2x-2

0

2

y024v4@x,yD

-20

2x

Yes, we do indeed see a large, central flat region surrounded by a lip to hold the charge in. We can check this out further by looking at some slices through the central region:

In[53]:= Plot@v4@x, 0D, 8x, −3, 3<, PlotLabel −> "v4@x, y=0D vs x"D;

-3 -2 -1 1 2 32.65

2.752.82.852.9

v4@x, y=0D vs x

Landau, First Course in Scientific Computing 77

Copyright: Princeton Univ Press, RH Landau, 2005

Page 86: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[54]:= Plot@Min@4, v4@x, xDD, 8x, −3, 3<, PlotLabel −> "v4@x=yD vs x"D;H∗ Use min to cut off hilltops and see details ∗L

-3 -2 -1 1 2 3

1.52

2.53

3.54

v4@x=yD vs x

So we see that the central portion of this potential is indeed a flat region with a ``lip'' all around it. So a charge placed there will have no force on it (the flatness) and will be stable (the lip).

4.8 Exploration: The Tripole

Repeat the analysis carried out for the dipole and quadrupole now for the tripole. Be sure to make a 3-D plot with labels and title, as well as to include contours. You will also need to slice your plot through its center to verify that you have found a stable point.

4.9 Extension: Yet More Plot Types

à 4.9.1 2-D Animations

We have just seen that surface-rendering techniques permit us to create images from mathematical functions that give the impression of viewing a true three-dimensional object. This literally gives a new dimension to our visualizations. In addition, if we have plots that show behavior of some quantity as a function of space. If this behavior changes gradually with time, then the observation of a sequence of plots of the spatial dependences, each one for a slightly different time, gives the impression of a continuous evolution of the spatial function in time. The function appears to be alive and, indeed, for this reason, creating a series of snapshots in time is known as animation.

To produce animations we take our familiar 2-D plots and add the dimension of time to them. For example, let us say we wanted to show the changing temperature distributions along a metal bar as the bar cooled with increasing time. We could say that we want to show T1[x], T2[x],...TN[x], where the number after T is the time. However, it is more elegant and more concise to say that there is only one temperature distribution, and that it is a function of both space and time,

T = T@x, tDIf the bar was initially hot in the center, and was then cooled over time, the temperature distribution could be approximated by [Krey]

78 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 87: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

T = THx, tL = sinHxL ‰-t -1ÅÅÅÅÅ9

sinH3 xL ‰-9 t

Here is a 3-D surface plot to show the variation of T with both space and time:

0123 x

05101520t

00.10.20.30.4

T@x,tD

0123 x

05101520t

In many ways an animation is more natural in displaying the time dependence. In any case, an animation provides another way to visualize a function of two variables, and it is worth looking at to see if it is illuminating.

Make a 3-D surface plot of this temperature distribution from time 0 to 20, and for position 0 to p. Make sure to label the axes so that you know which variable is which. Your result should look like the plot above. Try grabbing this plot and enlarging it, and then rotating it to look like the plot above by using the 3D ViewPoint Selector and changing the plot command:

In[55]:= Plot3D@Sin@xD∗Exp@−0.3∗tD − HSin@3 xD∗Exp@−9∗0.3 tDLê9, 8x, 0, π<,8t, 0, 20<, BoxRatios → 81, 1, 1<, AxesLabel → 8"x", "t", "T@x,tD"<D;

01

23x

05

10 15 20t

00.10.20.30.4

T@x,tD

01

23x

05

10 15 20t

After we load up the needed package, we will animate this same function by using the Animate command:

Landau, First Course in Scientific Computing 79

Copyright: Princeton Univ Press, RH Landau, 2005

Page 88: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[56]:= << Graphics`Animation` H∗ Load the needed package ∗LNames@"Graphics`Animation`∗"D

Out[57]= 8Animate, Animation, AnimationFunction, Frames,MovieContourPlot, MovieDensityPlot, MovieParametricPlot, MoviePlot,MoviePlot3D, RasterFunction, RotateLights, ShowAnimation,SpinDistance, SpinOrigin, SpinRange, SpinShow, SpinTilt<

In[58]:= Clear@x, tDIn[59]:= Animate@ Plot@Sin@xD∗Exp@−0.3∗tD − HSin@3 xD∗Exp@−9∗0.3 tDLê9, 8x, 0, π<,

PlotRange → 80, π<, AxesLabel → 8"x", "t"<, Ticks → FalseD, 8t, 0, 20< DNote that at first the result of the command does not look like anything beyond a bunch of static 2-D plots. The first step in animation is the construction of a sequence of images, each slightly different from the other. Next, use your mouse to select the image cell brackets (you must select the bracket containing all of the image cells). Then go to the Cell menu and choose Animate Selected Graphics. Mathematica lets you control the direction and speed of the animation with the controls like those on a VCR found in the lower left-hand corner of the screen. Notice the buttons for forward, reverse, stop/start, and continuous loop. We recommend the continuous animation. You can change the speed of the animation with the buttons with up and down arrows. The animation will stop if you click your mouse anywhere else in the notebook.

An animation works by displaying (flipping through) a sequence of slightly modified images. In movie parlance, these images are called frames. The more images you have and the less difference between them, the smoother your ``movie'' will look. You can include a command option in Animate to change the number of frames. The default is 24 frames. A larger number of frames will lead to both a smoother and slower animation.

In[60]:= H∗ Include a Frames→100 option in the Animate command from above ∗L

You can also use the MoviePlot command to animate functions, and sometimes it is less clumsy than the Animate command. A similar series of plots will be created, and you animate them the same way as you did before, by choosing Animate Selected Graphics. The MoviePlot has the same options as Plot, but does not contain the handy Frames option found in Animate:

In[61]:= MoviePlot@Sin@xD∗Exp@−0.3∗tD − HSin@3 xD∗Exp@−9∗0.3 tDLê9,8x, 0, π<, 8t, 0, 20<, PlotRange → 80, π<Dà 4.9.2 3-D Animation

Well, if you have been reading and executing up to this point, it is pretty clear what 3-D animations are about. If you have a function of two space coordinates that also varies in time, then you can make a 3-D surface plot to visualize the space dependence at any one time, or an animation to visualize the time dependence. For example, assume the temperature distribution is now the two (space)-dimensional function ikjjjSin@xD ‰H-.3 tL -

Sin@3 xD ‰H-9.9 tLÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ

9yzzzikjjjSin@yD ‰H-.3 tL -

Sin@3 yD ‰H-9.9 tLÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ

9yzzz

This is complicated enough that we will define a Mathematica function rather than try to squeeze the long expression into the MoviePlot3D command. Other than using the name MoviePlot3D, the format of the command is the same as MoviePlot. We start with the function T(x,y,t), then give the ranges for each variable, the plot range, and then the labels:

In[62]:= << Graphics`Animation` H∗ Load the needed package ∗L

80 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 89: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[63]:= T@x_, y_, t_D := HSin@xD∗Exp@−0.3∗tD − Sin@3 xD∗Exp@−9.9∗tDê9L∗HSin@yD∗Exp@−0.3∗tD − Sin@3 yD∗Exp@−9.9∗tDê9L;?T

Global`T

T@x_, y_, t_D :=

HSin@xD −0.3 t − 19 Sin@3 xD −9.9 tL HSin@yD −0.3 t − 1

9 Sin@3 yD −9.9 tL

In[65]:= MoviePlot3D@T@x, y, tD, 8x, 0, π<, 8y, 0, π<, 8t, 0, 20<,PlotRange → 80, 1<, AxesLabel → 8"x", "y", "T@x,yD"<D

01

23

x0

1

2

3

y0

0.250.5

0.751

T@x,yD

01

23

x

à 4.9.3 Phase Space (Parametric Plots)

In science we often encounter several physical quantities that are simultaneous functions of the same variable. For exam-ple, the position x[t], velocity v[t], and acceleration a[t] of a mass undergoing simple harmonic motion are all trigonomet-ric functions of time:

xHtL = sinHw tLvHtL = -w cosHw tLaHtL = -w2 sinHw tL

We can easily plot the position and velocity on the same graph:

In[66]:= << Graphics`Legend`

In[67]:= Plot@8Sin@ωtD, −2∗Cos@ωtD<, 8ωt, 0, 8∗ π<,PlotStyle → 88RGBColor@1, 0, 0D<, 8RGBColor@0, 1, 0D<<,PlotLegend → 8"x@ωtD", "v@ωtD"<D;

The graph shows that position and velocity are out of phase, but with the same period. A more direct way to observe the relation of two dependent variables (x and t in our example) as a function of the same independent variable is known as a phase-space or parametric plot. These types of plots have now proven themselves to be highly illuminating and valuable.

Phase space is an extension of the usual space of position and also includes velocity as if it were a new dimension, along with position. Explicitly, we plot x(t) along the abscissa as if it were the independent variable and y(t) along the ordinate. In a sense then, a phase-space plot is a plot of the velocity v(t) as a function of position x(t), that is, a plot of v(x). In general, there might be some complicated mathematics needed to analytically eliminate the time dependences of these two func-tions so that they can be expressed in terms of each other. However, it is pretty easy to do this graphically (numerically), and that is what Mathematica does. Explicitly, Mathematica just breaks up the total time interval T into a number of steps, and then records the pair of values (x,v) for each time step. These values then get plotted as v(t) versus x(t) with the phase-space plot ParametricPlot:

Landau, First Course in Scientific Computing 81

Copyright: Princeton Univ Press, RH Landau, 2005

Page 90: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[68]:= ParametricPlot@8Sin@ωtD, −2∗Cos@ωtD<,8ωt, 0, 8∗ π<, AxesLabel → 8"Position", "Velocity"<D;

-1 -0.5 0.5 1Position

-2

-1

1

2Velocity

Note that the syntax of the command is very similar to that of our old friend Plot. A list of two functions is used as the function argument, and the range of time values is listed separately. The general syntax for a 2-D parametric plot is

ParametricPlot@8x@tD, y@tD<, 8t, a, b<, optionsD

where t is known as the parametric variable, or simply parameter, and x[t] and y[t] denote the horizontal and vertical functions, respectively.

As far as the output goes, this phase-space plot looks like an ellipse. Yet note that it has properties that agree with the observations we have made before: when the mass is at its maximum positions, at the extreme right and left edges of the ellipse, the velocity is zero. When the mass has it maximum speed, at the top and bottom of the ellipse, it has zero position, that is, it is passing through its equilibrium position. So while a harmonic oscillator can be described via a complicated set of position, velocity, and acceleration functions, in phase space its motion is an elliptical orbit on which the mass passes over and over. This geometric approach has proven to be a simpler way to understand oscillatory motion. Indeed, the general value of phase-space plots is that they convert dynamical relations into geometric ones that are easier to visualize (the point of this chapter after all). For our simple oscillator, a sine relation along one axis and a cosine relation along the other converts into a simple ellipse.

You may be wondering in looking at this graph, just how we hit upon the exact range of wt values for which the graph exactly closes on itself. Well, we really did not. In fact, our plot covers two full cycles and plots them on top of each other (which you cannot see). If, on the other hand, your phase-space plot did not form a closed figure, then you would need to run for more values of the time. Try out smaller and smaller ranges for the phase wt in the plot command until you can generate 1, 1/2, and 1/4 of an ellipse:

In[69]:= ParametricPlot@8Sin@ωtD, −2∗Cos@ωtD<,8ωt, 0, .5∗ π<, AxesLabel → 8"Position", "Velocity"<D;0.2 0.4 0.6 0.8 1

Position

-2

-1.5

-1

-0.5

Velocity

As you can see from looking at the monitor in front of you, visual displays tend to be broader than they are high. Accord-ingly, graphs tend to get stretched horizontally (``scaled'') in order to fill the screen. While this is not normally a concern if the graph looks good, it is if you are trying to determine the actual shape of a geometrical figure. Mathematica has a AspectRatio option designed to determine the height-to-width ratio of a graph. The default value is set to 1/GoldenRa-tio, where GoldenRatio is (1 + è!!!5 )/2. This is known to be an eye-pleasing ratio. However, it can be changed to scale both axes identically by setting AspectRatio-> Automatic, or any ratio of vertical to horizontal axis length with AspectRatio->ratio. Use the execution group below to try several ratio values and reshape this ellipse back into a circle:

82 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 91: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[70]:= ParametricPlot@8Sin@ωtD, −2∗Cos@ωtD<, 8ωt, 0, 8∗ π<,AxesLabel → 8"Position", "Velocity"<, AspectRatio → .75D;

H∗ Play with the AspectRatio option ∗L

-1 -0.5 0.5 1Position

-2-1

12

Velocity

à 4.9.4 Vector Fields: PlotVectorField

Consider again the electric dipole shown in Figure 4.1. The problem we examined dealt with the electric potential for this type of system. While potentials are easier to compute and visualize than fields, it is usually fields that are related to forces and thus measured in experiments. As an extension of our previous work, we now visualize the electric field E(x,y) for the dipole. Mathematically, we can determine the electric field as the derivative of the potential using the techniques of vector calculus. This is complicated because the electric field is a vector field with components in the x, y, and z directions. While we can visualize each component of a vector field individually, generally it is more illuminating to examine magnitude and direction of the field. Let us see how Mathematica does that.

For the dipole in Figure 4.1, the electric potential has the vector form

E =q1Hr - r1LÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅH » r - r1 »L2 +

q2Hr - r2LÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅH » r - r2 »L2

where the E and r's in this equation are all vector quantities. For unit charges located a distance 1 and -1 along the x axis, the x and y components of E are:

In[71]:= Ex@x_, y_D := Hx + 1LêHHx + 1L^2 + y^2L − Hx − 1LêHHx − 1L^2 + y^2L;?Ex

Global`Ex

Ex@x_, y_D := x+1Hx+1L2+y2

− x−1Hx−1L2+y2

In[73]:= Ey@x_, y_D := yêHHx + 1L^2 + y^2L − yêHHx − 1L^2 + y^2L;?Ey

Global`Ey

Ey@x_, y_D := yHx+1L2+y2

− yHx−1L2+y2

We can visualize these individual components in two surface plots:

Landau, First Course in Scientific Computing 83

Copyright: Princeton Univ Press, RH Landau, 2005

Page 92: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[75]:= Plot3D@Ex@x, yD, 8x, −3.5, 3.5<,8y, −3.5, 3.5<, AxesLabel → 8"x", "y", "ExHx,yL"<D;

-20

2x-2

0

2

y

-0.50

0.5ExHx,yL

-20

2x

While this does show the force components at each point in space, it is rather hard to get a good feel for the magnitude and direction of the force acting on a test charge at each point in space. This is obtained with the PlotVectorField com-mand, and hence we need to load the PlotField.m package:

In[76]:= << Graphics`PlotField`

In[77]:= PlotVectorField@8Ex@x, yD, Ey@x, yD<, 8x, −3.5, 3.5<, 8y, −3.5, 3.5<D;

We see here the direction of the field given by the direction of the arrows, and the magnitude given by the length.

Although not often seen in elementary classes, the real world is actually three dimensional. Accordingly, the electric field actually has three components:

In[78]:= Clear@Ex, EyDEx@x_, y_, z_D :=Hx + 1LêHHx + 1L^2 + y^2 + z^2L − Hx − 1LêHHx − 1L^2 + y^2 + z^2L;?Ex

Global`Ex

Ex@x_, y_, z_D := x+1Hx+1L2+y2+z2

− x−1Hx−1L2+y2+z2

In[81]:= Ey@x_, y_, z_D := yêHHx + 1L^2 + y^2 + z^2L − yêHHx − 1L^2 + y^2 + z^2L;?Ey

Global`Ey

Ey@x_, y_, z_D := yHx+1L2+y2+z2

− yHx−1L2+y2+z2

84 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 93: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[83]:= Ez@x_, y_, z_D := zêHHx + 1L^2 + y^2 + z^2L − zêHHx − 1L^2 + y^2 + z^2L;?Ez

Global`Ez

Ez@x_, y_, z_D := zHx+1L2+y2+z2

− zHx−1L2+y2+z2

We visualize a 3-D vector field with the PlotVectorField3D command found in the PlotField3D.m package:

In[85]:= << Graphics`PlotField3D`

In[86]:= PlotVectorField3D@8Ex@x, y, zD, Ey@x, y, zD, Ez@x, y, zD<,8x, −3.5, 3.5<, 8y, −3.5, 3.5<, 8z, −3.5, 3.5<D;

Note that the output from the PlotVectorField3D command is a 3-D plot that can be rotated using the 3D View Point Selector under the Input menu, having the usual options.

à 4.9.5 Energy Conservation and Implicit Plots

In a preceding section we looked at the position x[t] and velocity v[t] of an oscillator, each as a function of time, and showed how a parametric plot can be made from them. Mathematica solves numerically for the function x[v] or v[x]. There may also be cases where you know some functional relation between two variables, say x and v, and wish to make a plot of x versus v. For example, let us say that we have a spring with a nonlinear force law so that the potential energy stored in it is

V HxL = k x6

The kinetic energy of a mass attached to this spring is, as always,

K =m v2

ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ2

Since we know that the sum of kinetic plus potential energy is conserved, this means we have an implicit relation between position and velocity, namely,

E = V + K

E = k x6 +m v2

ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ2

This last equation permits us to use Mathematica's ImplicitPlot command to plot x versus v if we have explicit values for the constants:

In[87]:= << Graphics`ImplicitPlot` H∗ Load the needed package ∗L

Landau, First Course in Scientific Computing 85

Copyright: Princeton Univ Press, RH Landau, 2005

Page 94: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[88]:= ImplicitPlot@5∗x^6 + H13ê2L∗v^2 1, 8x, −1, 1<, 8v, −1, 1<D;H∗ Create an implicit plot of x versus v ∗L

-1 -0.5 0 0.5 1-1

-0.5

0

0.5

1

In[89]:= H∗ See how this phase space diagram changesif the potential energy varies as the 5 th power of x ∗L

In analogy to the 2-D implicit plots we just made for a nonlinear oscillator, the function ContourPlot3D plots the 3-D surface defined by some implicit relation between x, y, and z:

In[90]:= Clear@x, y, vD H∗ Clear existing variables and load package ∗L<< Graphics`ContourPlot3D`

In[92]:= ContourPlot3D@x^2 + y^2 + z^2ê3 − 1,8x, −1, 1<, 8y, −1, 1<, 8z, −2, 2<, Boxed → FalseD;

86 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 95: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[93]:= ContourPlot3D@Exp@z^2D − Sqrt@x^2 + y^2D,8x, −3, 3<, 8y, −3, 3<, 8z, −1, 1<, Boxed → FalseD;

à 4.9.6 Polar Plots

A polar plot is the representation r(q) of a function that is created by placing a point a distance r(q) from the origin for different values of q. If r were independent of q, then the polar plot would be a circle. Other dependencies are less obvious until you see them. Polar plots can be highly illuminating since the angle on the plot corresponds to the actual angle of the function's argument, and so the shape of the plot lets you visualize the variation of the function in actual space.

Making polar plots is done using the PolarPlot command, where q is the independent variable and r = f[q] as q varies from qmin to qmax:

PolarPlot@f@θD, 8θ, θmin, θmax<D

To get a feel for how this works, let us make a polar plot of a function that is independent of q, and then one of the familiar Sin[q]. The PolarPlot command is found in the Graphics.m package, so we will load it again to make sure we have it:

In[94]:= << Graphics`Graphics`

In[95]:= r = 1;PolarPlot@r, 8θ, 0, 2 π<D;

-1 -0.5 0.5 1

-1

-0.5

0.5

1

Landau, First Course in Scientific Computing 87

Copyright: Princeton Univ Press, RH Landau, 2005

Page 96: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[97]:= PolarPlot@Sin@θD, 8θ, 0, 2∗ π<D;

-0.4 -0.2 0.2 0.4

0.2

0.4

0.6

0.8

1

In[98]:= PolarPlot@8Cos@tD, Sin@tD<, 8t, 0, 4 π<D;H∗ Several polar graphs on one set of axes ∗L

-0.4 -0.2 0.2 0.4 0.6 0.8 1

-0.4-0.2

0.20.40.60.81

As a more realistic example, consider the expression for the intensity of low-energy X-rays scattered off a reflecting sphere as a function of the scattering angle, or radiation pattern around antenna:

s@qD = 3 + 2 Cos@qD4 + 2 Cos@qDVisualize this function with a 2-D plot of s[q] versus scattering angle. You should get a plot like the one below:

In[99]:= H∗ Use [email protected] here ∗L

1 2 3 4 5 6theta

34567

It may not be obvious that this graph means that there is a strong peak in the forward direction along the beam at q = 0, and that there is a weaker amount of scattering back into the beam at q = p . However, if we plot this function in a polar plot these features become evident:

88 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 97: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[100]:= PolarPlot@3 + 2 Cos@θD^4 + 2 Cos@θD, 8θ, 0, 2 π<D;-2 2 4 6

-3

-2

-1

1

2

3

Notice how you can intuitively feel where the scattering is large and where it is small. Notice too, that the form of the PolarPlot command is very similar to that of the Plot command.

à 4.9.7 Surface Plots of Complex Functions*

At present we have not found a ComplexPlot command or similar 3-D version of complex plotting in version 4.100 of Mathematica. However, the corresponding Maple section on this topic is useful.

à 4.9.8 Plotting Lists with ListPlot

Say we want to plot a set of data points of the form x1 , y1 , x2 , y2 , x3 , y3 , ... xN , yN . To do that we generate a list of numbers with the Table command:

In[101]:= mylist = Table@i^2, 8i, 10<DOut[101]= 81, 4, 9, 16, 25, 36, 49, 64, 81, 100<

The order is preserved since this is a list. To make the plot we use the ListPlot command. This command creates two-dimensional plots of points from either a list of y values or a list of ordered pairs of points, x,y. We have the first case, and the x values are taken to be 1, 2, ..., whereas in the second case, you can specify the x values. The option Plot-Joined -> True connects the points by line segments, and this should yield a single-valued function if the points are sequentially ordered. Let us try both below PlotJoined options below:

In[102]:= ListPlot@mylistD;

4 6 8 10

20

40

60

80

100

Landau, First Course in Scientific Computing 89

Copyright: Princeton Univ Press, RH Landau, 2005

Page 98: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[103]:= ListPlot@mylist, PlotJoined → TrueD;

4 6 8 10

20406080100

à 4.9.9 Creating Simple Figures: Graphics and Show

Here we give some examples of the use of the Graphics command using graphics primitives Point and Line along with the Show command to create simple figures of a barbell (we use the figure in Chapter 7). There are three steps involved. First we create the shapes with the lines using the Line graphics primitive, and then create the data points at the corners using the Point graphics primitive. Finally we use Mathematica's Graphics and Show commands to display the lines and points on the same graph. We do this first for a 2-D plot with Graphics, and then for a 3-D plot with Graphics3D. The 3-D plot is particularly useful as it permits the viewer to rotate the figure to gain different perspectives.

In 2-D we give each of the points as a list of doublets x, y:

In[104]:= p1 = Point@8−0.7, 0.7<Dp2 = [email protected], −0.7<D

Out[104]= Point@8−0.7, 0.7<DOut[105]= [email protected], −0.7<D

The Line command is a graphics primitive that represents a line joining a sequence of points. Here we would like a line to join our points and need to enter in their coordinates as a nested list:

In[106]:= ln1 = Line@88−0.7, 0.7<, 80.7, −0.7<<DOut[106]= Line@88−0.7, 0.7<, 80.7, −0.7<<D

Since both Point and Line are graphics primitives, we use the Graphics command to represent the graphical image of each, and then use the Show command to display the graphical images.

Graphics@primitives, optionsD

The shape, size, and color, of the primitives are contained in a list for the first argument to the Graphics command, while the options are the second argument. For example, the axes and plot information are set by the options. However, if you are displaying more than one graphic on the same graph with Show, the axes information should be specified in the first graphic, and the graphics are separated by commas:

In[107]:= Show@Graphics@8RGBColor@1, 0, 0D, [email protected], 8p1, p2<<,Axes → True, AxesLabel → 8"x", "y"<D, Graphics@ln1DD;

-0.6 -0.4 -0.2 0.2 0.4 0.6x

-0.6-0.4-0.20.20.40.6

y

In 3-D we give the points as a list of triplets x, y, z, and the line will now connect those points:

90 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 99: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[108]:= p1 = Point@8−0.7, 0, 0.7<Dp2 = [email protected], 0, −0.7<Dln1 = Line@88−0.7, 0, 0.7<, 80.7, 0, −0.7<<D

Out[108]= Point@8−0.7, 0, 0.7<DOut[109]= [email protected], 0, −0.7<DOut[110]= Line@88−0.7, 0, 0.7<, 80.7, 0, −0.7<<D

Now we will use the Graphics3D command for the graphics objects. The same Show command can be used to display 2-D and 3-D graphics:

In[111]:= Show@Graphics3D@8RGBColor@1, 0, 0D, [email protected], 8p1, p2<<,Axes → True, AxesLabel → 8"x", "y", "z"<D, Graphics3D@ln1DD;

-0.5 0 0.5x

-1-0.5

0 0.5 1y

-0.50

0.5z

-0.5 0 0.5x

-1-0.5

0 0.5 1y

à 4.9.10 Plotting Vectors: Arrow*

Mathematica's ability to do linear algebra is discussed in Chapter 7. We can define vectors, matrices, and arrays of arbi-trary sizes and dimensions. Mathematica provides some easy-to-use tools for visualizing vectors and matrices, in particu-lar Arrow, Arrow3D, and ListPlot.

In[112]:=

00.250.50.751x 1

1.52

y

1

1.5

2

z

00.250.50.751x

Visualization of Vectors with Arrow3D

The Arrow command creates a 2-D graphics primitive from points specifying the base and tip of the vector. Likewise, Arrow3D creates a 3-D graphics primitive from two points in 3-D. [You may have to copy Arrow3D.m into the Graph-ics folder under your installation of Mathematica's StandardPackages.] The Show command lets you place several Graphics or Graphics3D arrows together.

3-D Arrows

In[112]:= << Graphics`Arrow3D` H∗ Load Arrow3D package ∗L

In[113]:= Omega = 81, −3, 6<; H∗ Define vector Omega ∗LPrint@"Omega = ", OmegaDOmega = 81, −3, 6<

Landau, First Course in Scientific Computing 91

Copyright: Princeton Univ Press, RH Landau, 2005

Page 100: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[114]:= L = 86, 0, 6<; H∗ Define vector L ∗LPrint@"L = ", LDL = 86, 0, 6<

In[115]:= w = Arrow3D@80, 0, 0<, OmegaD; H∗ Assign object w to arrow of Omega ∗L

In[116]:= Show@Graphics3D@wDD;

Go up to the Input -> 3D ViewPoint Selector and change the Graphics3D command above to rotate the omega arrow.

In[117]:= l = Arrow3D@80, 0, 0<, LD; H∗ Assign object l to arrow of L ∗L

In[118]:= Show@Graphics3D@lDD; H∗ Rotate this arrow as well ∗L

We now have visualizations of both L and W that we can rotate. Note that we defined the arrows to start at the origin and end at the defining vector location. We place them on the same graph by placing both of the Graphics3D commands separated by commas in Show:

92 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 101: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[119]:= Show@Graphics3D@w, Axes → True, AxesLabel → 8"x", "y", "z"<,PlotLabel −> "Omega and L Vectors"D, Graphics3D@lDD;Omega and L Vectors

02

46

x-3-2-10y

3456

z

02

46

x

Since the Arrow3D is a fairly crude primitive, changing the color of the arrows is not an option (believe me, I have tried). Also, both of the arrows are defined to start at the origin, however the tails do not appear to meet at the origin as expected.

2-D Arrows

In[120]:= << Graphics`Arrow` H∗ Load Arrow package ∗L

In[121]:= Clear@Omega, w, L, lDOmega = 81, −3<;L = 86, 0<;Print@"L = ", LDPrint@"Omega =", OmegaDL = 86, 0<Omega =81, −3<

In[126]:= w = Arrow@80, 0<, OmegaD; H∗ Assign object w to arrow of Omega ∗L

In[127]:= l = Arrow@80, 0<, LD; H∗ Assign object l to arrow of L ∗L

Landau, First Course in Scientific Computing 93

Copyright: Princeton Univ Press, RH Landau, 2005

Page 102: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[128]:= Show@Graphics@w, Axes → True, AxesLabel → 8"x", "y"<,PlotLabel → "Omega and L Vectors"D, Graphics@8l, RGBColor@1, 0, 0D<DD;

H∗ Display Omega and L arrows on one graph ∗L

1 2 3 4 5 6x

-3-2.5-2

-1.5-1

-0.5

yOmega and L Vectors

Notice that when we create the graphics objects for the arrows, we tried to give an option to change the color of the arrow, but we are unable to. There are limited options for the Arrow and Arrow3D graphics primitive. However, we are still able to give the usual options for the plots within the Graphics and Graphics3D commands. So it is by the use of the Graphics command that we are able to place labels and titles, as well as control the scaling to make the vertical and horizontal sizes true. It is by the Show command that we are able to place more than one graphics object on a single graph and display it.

4.10 Visualizing Numerical Data

à 4.10.1 2-D Plots of Data

Most realistic computations in science produce numerical output, not analytic functions. While there is more work involved in plotting numerical data than there is for an analytic function, Mathematica is up to the task and actually has a number of ways to make 2-D plots of numerical data. Here we demonstrate the use of ListPlot from the standard Graphics package and Histogram from the DescriptiveStatistics package.

à 4.10.2, 3 Numerical Plots: ListPlot (scatterplot)

The ListPlot command creates a 2-dimensional plot from a list of numerical data values, as we have already seen. If only the y values of the data are given, say as the four-element list

Ydata = 81, 8, 27, 100<,

then ListPlot will assign x values as 1, 2, 3, 4, that is, the data points areH1, 1L, H2, 8L, H3, 27L, H4, 100L

94 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 103: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[129]:= ListPlot@81, 8, 27, 100<, PlotJoined → TrueD;H∗ Plot these y values with x as order number and connect points ∗L

1.5 2 2.5 3 3.5 4

20

40

60

80

100

In[130]:= Ydata = 81, 8, 27, 100< H∗ Enter y data into list Ydata ∗LOut[130]= 81, 8, 27, 100<

In[131]:= ListPlot@Ydata, PlotJoined → TrueD;H∗ Plot data object Ydata with x as order number ∗L

1.5 2 2.5 3 3.5 4

20

40

60

80

100

The default value of the PlotJoined option is False, so in order to connect the points in the order in which they are plotted, you need to set this option to True. If you want to give explicit x values to your data, then you can place each (xi , yi ) coordinate value in its own 2-element list, and make a big list of these small lists:

88x1, y1<, 8x2, y2<, 8x3, y3<, 8x4, y4<<

In[132]:= ListPlot@880, 1<, 8Sqrt@3Dê2, 1ê2<, 8−Sqrt@3Dê2, 1ê2<<,PlotJoined → TrueD;H∗ Plot Hxi, yiL values in a list and connect points ∗L-0.75 -0.5 -0.25 0.25 0.5 0.75

0.5

0.6

0.7

0.8

0.9

Landau, First Course in Scientific Computing 95

Copyright: Princeton Univ Press, RH Landau, 2005

Page 104: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[133]:= ListPlot@880, 1<, 8Sqrt@3Dê2, 1ê2<, 8−Sqrt@3Dê2, 1ê2<, 80, 1<<,PlotJoined → TrueD; H∗ Repeat first point to make a figure ∗L-0.75 -0.5 -0.25 0.25 0.5 0.75

0.50.60.70.80.9

In[134]:= XYdata = 880, 1<, 8Sqrt@3Dê2, 1ê2<, 8−Sqrt@3Dê2, 1ê2<, 80, 1<<H∗ Enter Hx,yL data into list XYdata ∗LGeneral::spell1 : Possible spelling error: new

symbol name "XYdata" is similar to existing symbol "Ydata".

Out[134]= 980, 1<, 9è!!!32

,12=, 9−

è!!!32

,12=, 80, 1<=

In[135]:= ListPlot@XYdata, PlotJoined → TrueD; H∗ Plot XYdata ∗L-0.75 -0.5 -0.25 0.25 0.5 0.75

0.50.60.70.80.9

These are the basic commands. The PlotStyle option can be used to change the style of points or line. You can control the size and color of points, as well and the thickness, color, and style of lines used to connect the points if PlotJoined is set to True:

In[136]:= ListPlot@XYdata, PlotStyle → 8RGBColor@1, 0, 0D, [email protected], 0.05<D<,PlotJoined → True, Axes → FalseD;H∗ Add color, dashed lines, and remove axes ∗L

In[137]:= ListPlot@XYdata, PlotStyle → 8RGBColor@0, 0, 1D, [email protected]<D;H∗ Do not connect points ∗L-0.75 -0.5 -0.25 0.25 0.5 0.75

0.50.60.70.80.9

In[138]:= Show@%, %%D; H∗ Put two previous plots H% and %%L together ∗L-0.75 -0.5 -0.25 0.25 0.5 0.75

0.50.60.70.80.9

Note, to make the geometric figure without internal lines, the order of points matters:

96 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 105: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[139]:= plotdata = 884, 8<, 82, 1<, 86, 27<, 88, 100<< H∗ Out of order points ∗LOut[139]= 884, 8<, 82, 1<, 86, 27<, 88, 100<<

In[140]:= ListPlot@plotdata, PlotJoined → TrueD ; H∗ Out of order plot ∗L

3 4 5 6 7 8

20406080100

à 4.10.4 Numerical Plots: Histograms

In[141]:= << Statistics`DescriptiveStatistics`

In[142]:= data = 8−2., −0.8, 2., .0, −.5, −.5, 1.6, .8, .5, −.5, −.2, −.2, .2, −.1<General::spell1 : Possible spelling error: new

symbol name "data" is similar to existing symbol "Ydata".

Out[142]= 8−2., −0.8, 2., 0., −0.5, −0.5, 1.6, 0.8, 0.5, −0.5, −0.2, −0.2, 0.2, −0.1<

Landau, First Course in Scientific Computing 97

Copyright: Princeton Univ Press, RH Landau, 2005

Page 106: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[143]:= Histogram@dataD

-1 0 1 2 3

1234567

Out[143]= Graphics

98 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 107: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

à 4.10.5 Surface Plots of Data: ListPlot3D

In Section 4.5 we described how to make 3-D or surface plots of analytic functions of two variables, s = f(x, y). Here we describe how to make the same kind of plot when there is no analytic function f(x, y), but just a table of numbers. In Chapter 13 we describe how to use the free plotting program gnuplot to make surface plots of numerical data. (Given a choice, we would recommend gnuplot.)

Most often, realistic calculations produce numerical data rather than analytic functions as their output. This is a conse-quence of the real world being less simple than the assumptions made in those models which lead to purely analytic answers. In realistic cases, the resulting equations can still be solved, only they must be solved numerically. Trying to understand if there is meaning in long lists of numbers obtained as output can be quite the challenge, yet this is exactly where the visualization tools are most valuable.

As was the case with analytic functions, a table or list of numbers may represent a function of one variable, a function of two variables, or even more. While this may sound absolutely dreadful to unravel, the use of matrices and arrays makes the bookkeeping rather straightforward. While we have not yet discussed how Mathematica goes about handling matrices (we do that in Chapter 7), we will use some of those concepts here. Accordingly, you may want to read about matrices and then return to this subsection.

As with all 3-D visualizations, we want to create a surface in a three dimensional space that represents our data. That's what we did when we plotted the temperature T[x,y] as a height, with its functional dependences on x and y displayed by moving to different regions in the x y plane. To be more specific, we can imagine the surface that we are creating is described by a height z[x,y] that varies for different positions x and y in a plane. While it is conventional to draw our 3-D plots so that z corresponds to the vertical direction above the x y plane, once you have your plot, you can rotate it around and, like a pilot flying upside-down too long, you may forget which end is up.

Let us imagine now that we are dealing with data describing the temperature T(x) as a function of distance x along a one dimensional bar. However, the bar is cooling as a function of time and so there are a number of these temperature distribu-tions, each for a different time. It is neat and convenient to place all the data together in a function of both time and position, T(t, x). Note that the bar has only one spatial dimension, the distance x, yet time t is also a variable so we must visualize a function of two variables. We make a graph of T(t,x) with T as a vertical distance, with time t as a horizontal coordinate, and with position x as a different horizontal coordinate. The fact that a 3-D surface of this nature does not truly exist in nature is one reason this approach is called ``visualization''.

The plotting of numerical data is done in two steps:

1) read the data into a matrix with one index for position and one for time

2) have Mathematica plot the matrix

We have placed the data we want to visualize in the file EqHeat_z.dat on the CD. The file should be what is called ``plain, flat, text or ASCII'', that is, one without control characters. Now make sure that file has been moved to the current working directory for Mathematica, or to a place where it can be easily found.

Why Just z Values for Plot?

It may appear obvious that if we want to plot the function z(x,y), then the input data file should contain x and y values and the associated z value. While this might be the most direct approach to describing a function, keeping track of all those numbers can get rather complicated, as well as requiring you to deal with lots of numbers. (However, this is fine for analytic functions, examples of which are found in the section on ContourPlot3D.) For this reason, numerical 3-D plots are usually created using just a set of z values as input, with the assumption that these z values correspond to a rectangular array of uniformly spaced x and y values. This is, in fact, the reason we have placed the subscript _z in the file name EqHeat_z.dat, it is a reminder that the file contains just z values.

Go take a look at the file EqHeat_z.dat with a text editor (not Mathematica). You should see that it contains lines of numbers (11 numbers on each line) separated by spaces. The first three lines should look like this

0.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 100.0 0.0

Landau, First Course in Scientific Computing 99

Copyright: Princeton Univ Press, RH Landau, 2005

Page 108: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

0.0 32.5 59.8 78.9 89.5 92.8 89.5 78.9 59.8 32.5 0.0

0.0 22.7 43.0 59.0 69.1 72.5 69.1 59.0 43.0 22.7 0.0

Think of each line of data as a row of a big matrix. Even though the number of digits used for each number may differ, and so the length of each line may differ, each row has the same number of entries or columns. These data correspond to values of the temperature for increasing x values along the rod. Although explicit values of the time are not given, subse-quent lines (rows of the matrix) contain the temperature distributions for later and later times. In other words, the full matrix is

T@@x, tDD = T@@column, rowDD

where each new row corresponds to the next value of the time. Since no explicit values are input for the time or the position, the plotting program will assume uniform spacing and time steps, and will assign each integer values, 1, 2, 3 ... for the plot. You can think of these as ``the first, second, et cetera times'' and the ``first, second, et cetera'' positions.

Reading in Just z Values of Data

The Import command is very handy for importing data from files. We view each row of the matrix (on separate lines) as a list :

8value_ 1, value_ 2, ..., value_numcols<

and the collection of rows as a list of lists:88row 1 data<, 8row 2 data<, ... 8row numrows data<<

In Mathematica we do not need to know how many rows or columns there are to build the matrix. The first argument for Import is the path and name of the file you wish to import data from. The second argument allows you to specify the format you wish the data to be stored as. If you have a file in which each line consists of a single number, then you can use Import["file","List"] to import the contents of the file as a list of numbers. We, however, have a file where each line consists of a list of numbers separated by spaces, so we want to use Import["file", "Table"] command. This will yield the list of lists of numbers that we are looking for. You will learn in Chapter 7 that a list of lists is a matrix in Mathematica, also known as a Table. If your file has a ".dat" extension you do not have to specify the format in the second argument, the data will automatically be read using Table format with the single argument being the file name and extension. Other import formats are available for text, words, graphics, sound, etc. For more information, look up help on the Import command.

The data (values of z) are read into the variable (object or abstract data type) that we name data with Mathematica's Import command. Since files are stored on your individual computer using its own file system, just how you specify the file name depends somewhat on the computer system you are on, and where the file is on that system. For all but the simple Unix version, we have placed a (* ... *) around the command so that Mathematica will treat the command as a comment. Note the use of quotes in the command around the file name as well as around the type of data the file is to be read in as. To see what works for you, try deleting the comment symbols around the command and seeing if the command completes with no error message:

In[144]:= H∗ data =

Import@"êhomeêrobynwêBookêSummer03êMathematicaêEqHeat_z.dat", "Table"D ∗LH∗ Unix system, file in specified directory ∗L

In[145]:= H∗ data = Import@"EqHeat_z.dat", "Table"D ∗LH∗ Unix system, file in same directory where Mathematica started ∗L

In[146]:= H∗ data = Import@"Mac G3 HD:DMc:EqHeat_z.dat", "Table"D ∗LH∗ Apple MacIntosh ∗L

100 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 109: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[147]:= H∗ data =

Import@"C:\\My Documents\\Rubin\\Books\EqHeat_z.dat", "Table"D ∗LH∗ Windows, needs extra \ ∗L

In[148]:= H∗ data =

Import@"C:êMy DocumentsêRubinêBooksêIntroêMathematicaêEqHeat_z.dat","Table"D ∗L H∗ Works also on Windows ∗L

As you can see in the output cell, the variable data is a list ... containing other lists ..., ..., .... Each sublist is the temperature all along the bar at a different time. In case you have some trouble with reading these files, you may also want to try inputting the data by hand with the list of lists format, data = ..., ..., ...,.....

We can look at any individual part of this list that we want. For example, here is the second row of data (the second list):

In[149]:= data@@2DDOut[149]= −0.8

As a check, let us look at some individual elements. For example, here's the 5th element in the 2nd row:

In[150]:= data@@2, 5DDPart::partd : Part specification 1 is longer than depth of object.

Out[150]= 8−2., −0.8, 2., 0., −0.5, −0.5, 1.6, 0.8, 0.5, −0.5, −0.2, −0.2, 0.2, −0.1<P2, 5T

In[151]:= H∗ Determine the element in row 5, column 2 ∗L

4.10.6 ListPlot3D

The ListPlot3D command creates a 3-D plot of a surface representing a list of lists of numeric values. That is, a visualization of a 2-D matrix. The options are much the same as those for Plot3D. We give an example in which a surface is drawn from our imported data. Rotating the surface is lovely. Try it with the 3D ViewPoint Selector menu, pasting the option into the command:

Landau, First Course in Scientific Computing 101

Copyright: Princeton Univ Press, RH Landau, 2005

Page 110: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[152]:= ListPlot3D@data, ColorFunctionScaling → True,ColorFunction → Hue , ViewPoint −> 8−2.343, 2.209, 1.040<D;

SurfaceGraphics::gmat :

8−2., −0.8, 2., 0., −0.5, −0.5, 1.6, 0.8, 0.5, −0.5, −0.2, −0.2, 0.2, −0.1<is not a rectangular array larger than 2 x 2.

4.11 Plotting a Matrix: ListPlot3D

As we have just shown above, the way to make a 3-D plot of a matrix is with the ListPlot3D command in Mathemat-ica. Unlike Maple, Mathematica does not have a matrixplot command to do it all in one step. When we read in the data from the file, it was stored as a Table format, which is a matrix in Mathematica, therefore no conversion from a list to a matrix is necessary. We verified it was a matrix by accessing the individual rows and elements in the usual way. In Chapter 7 we discuss using matrices in Mathematica, and give examples of plotting matrices and vectors as well. If you have trouble following the procedure below, you may want to learn some more about matrices in Chapter 7.

In[153]:= slant = 881, 5, 9<, 82, 6, 10<, 83, 7, 11<, 84, 8, 12<<;slant êê MatrixFormH∗ Set up matrix with three columns ∗L

Out[154]//MatrixForm=

i

k

jjjjjjjjjjjj

1 5 92 6 103 7 114 8 12

y

zzzzzzzzzzzz

In[155]:= ID = IdentityMatrix@6D; H∗ The identity matrix of specified dimension ∗LID êê MatrixForm

Out[155]//MatrixForm=

i

k

jjjjjjjjjjjjjjjjjjjjjj

1 0 0 0 0 00 1 0 0 0 00 0 1 0 0 00 0 0 1 0 00 0 0 0 1 00 0 0 0 0 1

y

zzzzzzzzzzzzzzzzzzzzzz

In[156]:= ID2 = IdentityMatrix@3D;ID2 êê MatrixForm

Out[157]//MatrixForm=

i

k

jjjjjjj1 0 00 1 00 0 1

y

zzzzzzz

102 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 111: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[158]:= ListPlot3D@slant, BoxRatios → 81, 1, 1<, PlotLabel → " Slant Matrix"D;H∗ A new slant ∗L

Slant Matrix

1 1.5 2 2.53

12

34

0

5

10

1 1.5 2 2.53

12

34

For our data above, different rows correspond to different values for the time t, and different columns correspond to different positions x along the bar. These are plotted along the x and y axis in the plot, that is along the base of the solid figure. The temperature is plotted as the height of the surface above the base. To help with the visualization, we will also use the Lighting->False option to color the surface with gray scales determined by height, white being hot and black being cold, to convey the temperature:

In[159]:= ListPlot3D@data, Lighting → False, ViewPoint −> 8−2.343, 2.209, 1.040<D;SurfaceGraphics::gmat :

8−2., −0.8, 2., 0., −0.5, −0.5, 1.6, 0.8, 0.5, −0.5, −0.2, −0.2, 0.2, −0.1<is not a rectangular array larger than 2 x 2.

We can also color the surface with the ColorFunction->Hue option to yield a range of colors. However, this doesn't help up visualize the hot and cold temperature heights as well:

Landau, First Course in Scientific Computing 103

Copyright: Princeton Univ Press, RH Landau, 2005

Page 112: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[160]:= ListPlot3D@data, ColorFunctionScaling → True,ColorFunction → Hue , ViewPoint −> 8−2.343, 2.209, 1.040<D;

SurfaceGraphics::gmat :

8−2., −0.8, 2., 0., −0.5, −0.5, 1.6, 0.8, 0.5, −0.5, −0.2, −0.2, 0.2, −0.1<is not a rectangular array larger than 2 x 2.

ListPlot3D is similar to other 3-D surface plots. You already have some experience with Plot3D and so you should know how to label the axes and plot, as well as rotate the surface.

è Label the axes indicating row and column. Recall that increasing row numbers correspond to increasing time, while the increasing column numbers correspond to increasing position along the bar.

è Rotate the plot using the 3DViewPointSelector under the Input menu to paste the option in the command.

è Add a title to the plot and remove the grid mesh lines with the Mesh option. Do you think the mesh grid helps give the 3-D impression?

You have the figure above, which is rather complete, but not necessarily an effective visualization. You are probably the best judge of effectiveness, and to do that you need to try out the options and see what works.

Reading in (x, y, z) Data Sets

In a more realistic case our data might be the results of a numerical simulation or a measurement and would reside in an external file. We read in these data as we did before with the Import command, but now with 3 columns for the values of (x, y, z), still importing the data into a Table structure. For this purpose we have supplied the file EqHeat_xyz.dat:

In[161]:= datalistex =

Import@"êhomeêrobynwêBookêSummer03êMathematicaêEqHeat_xyz.dat", "Table"DH∗ Unix read, complete specification ∗L

In[162]:= H∗ datalistex =

Import@"C:\\My Documents\\Rubin\\Books\\Intro\\Maple\\EqHeat_xyz.dat","Table"D ∗L

H∗ Windows read, complete specification ∗L

In[163]:= ListPlot3D@datalistexD;

4.12 Animations of Data*

In the corresponding section in the text is an animated Mathematica plot of the wave motion resulting from plucking a string that is hanging under its own weight, and is affected by friction. This comes from a numerical simulation [CP] that outputs its results to a file in the gnuplot format used for surface [z(x, y)] plots. (As described in Sec. 4.9.5, the data are in the form of a matrix of z values, with the rows of the matrix separated by blank lines. The first row corresponds to time 1, with the place in the row corresponding to different x values. Row two contains all the z values for time 2, and so forth.) As we see in Fig. Waves3D.eps, the surface plot shows many ripples corresponding to oscillations of the string, but is not nearly as effective a visualization as playing the animation below.

104 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 113: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In this section we indicate the steps needed to input numerical data in surface plot format, and convert it into an animation. We start by forming a very long list of data named ``data'' from the file function.dat (Unix reads from present directory, Windows requires full path name as give by Explorer):

In[164]:= data =

Import@"êhomeêrobynwêBookêSummer04êMathematicaêfunction.dat", "List"D ;H∗ Unix system, file in specified directory, .dat uses "Table" format ∗L

data@@1DD H∗ Individual elements in list ∗Ldata@@4DD

We next break up the array data into a list of sublists. The first sublist func[1] corresponds to row 1 of the original matrix, the second sublist, func[2] corresponds to row 2 of original matrix, and so forth:

fdata@x_D := data@@xDD; H∗ Write array as a function ∗L?fdata

func = 8Array@fdata, 101, 1D< H∗ Extract first row into func ∗L

We now use the For looping structure, which we talk about extensively in Chapter 8, to append additional rows as lists to func to create a list of lists:

For@t = 1, t ≤ 199, t = t + 1, 8AppendTo@func, Array@fdata, 101, 101∗t + 1DD<D;As a check, we print out the sublist func[1]. It is the first row of input and will be the first frame of the movie:

func@@1DD H∗ Print out individual row ∗L

Now that we know that the data looks good, we plot several of the frames that we will put together to form the movie:

ListPlot@func@@1DD, PlotJoined → TrueD;ListPlot@func@@10DD, PlotJoined → TrueD;ListPlot@func@@20DD, PlotJoined → TrueD; H∗ Plot individual frames ∗L

To create the movie, we would like to make a sequence (ordered list) of plots and then animate them. We can make an array of all the plots in order, however we have not found a way to display them all on one plot, (the Show command would be the obvious way to do it, but doesn't seem to work with plots as objects). Instead, Mathematica plots all 200 plots. To animate them you need to select the cell containing them all and choose Cell => Animate Selected Graphics. That's why here we plotted several of the rows.

ListPlot@func@@1DD, PlotJoined → TrueD;ListPlot@func@@10DD, PlotJoined → TrueD;...ListPlot@func@@190DD, PlotJoined → TrueD;

Animate them as explained above. Now that is a movie! Control the speed and direction of the animation with the mouse buttons in the bottom left of the window.

Landau, First Course in Scientific Computing 105

Copyright: Princeton Univ Press, RH Landau, 2005

Page 114: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

4.13 Key Words and Concepts

abstract data type abscissa animation contour plots dependent variable implicit plot independent variable list matrix nonlinear functions ordinate set sequence surface plot 2D plot parametric plot polar plot potential energy

1. Does potential energy occur in nature?

2. Is there a reason for electric charge to occur always in integer values?

3. How does an abstract data type differ from an algebraic symbol?

4. How do you decide which is an independent and which is a dependent variable?

5. When might it be a bad idea to use color in your plotting?

6. List three ways in which you may change the apparent meaning of data by changing the way in which it is represented.

7. What might be a dishonest way of presenting your data?

8. Give examples of the type of data that may be appropriate for 1D, 2D, 3D, and 4D visualizations.

9. When are animations a useful way to display data?

10. How, in a mathematical sense, does a phase-space (parametric) plot differ from an ordinary 2D plot?

11. How is a table of numerical data similar to, and different from, a mathematical function?

4.14 Further Exercises

1. On a single graph, display the function x3 SinHxL, x3 CosHxL,and x Log(x), each in a different color. Use an equal negative and positive x range, and pick that range to obtain the most interesting comparison of the three functions.

2. A graphical approach to solving equations plots the right and left hand sides of an equation as two separate functions, and then shows the solution to the equation as the value of the abscissa at which the two functions intersect. In other words, a solution of f(x)=g(x) occurs when the graphs of f(x) versus x intercepts the graph of g(x) versus x. Use Mathemati-ca's ability to plot several functions in the same graph to determine the approximate solutions of the following equationsHaL Sin@xD = x2HbL x2 + 6 x + 1 = 0HcL H3 - 9 H2 + 4 = 0

3. Do a graphical experiment in which you prove to yourself these very useful mathematical facts:

a) the exponent ‰x grows faster than any power xn

106 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 115: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

b) the logarithm ln(x) grows slower than any power xn

Hint: To avoid overflow problems with very large x values, you may want to make semilog plots.

4. Do a graphical experiment to find the value of n for which these equations are true:

a) n Sin(2 x) = Sin(x) Cos (x)

b) n HCosHxLL2 = 1 + Cos(2 x)

5. If two tones very close in frequency are played together, your ear hears them as a single tone with oscillating amplitude. Make plots as a function of time of the results of adding the two sine functions

SinH100 tL + SinHb tLMake a series of plots for b in the range

90 < b < 100

Make sure to plot for a long enough range of t values to see at least three cycles of any periodic behavior.

6. Here are nine measurements given in the form (x, y):

(0,10.6), (25, 16.0), (5, 45.0), (75, 83.5), (100, 52.8), (125, 19.9), (150, 10.8), (175, 8.25), (200, 4.7)

Make a plot of these data points.

7. The orbits of planets and comets are known to be conic sections. Conic sections are the 2-D curves formed when a cone is cut (sectioned) by a plane, and are given by the parametric equations in which s is the parameter:

a) hyperbola: (x (s), y(s)) = (4 Cosh(s), 1.4 Sinh(s))

b) ellipse: (x(s), y(s)) = (4 Cos(s), 1.4 Sin(s))

c) parabola: (x(s), y(s)) = (s Cos(q) - s2 Sin(q), s2 Cos(q) + s Sin(q)), q = arbitrary parameter.

Make parametric plots of these conic sections. Cover as much range as is needed for the parameter s in order to obtain the familiar shapes.

8. In polar coordinates, the conic section is described by the equationaÅÅÅÅÅÅr

= 1 + e Cos@qDwhere e is the eccentricity and 2 a is the latus rectum of the orbit. An ellipse occurs when 0 < e < 1, a hyperbola for e > 1, and a parabola for e = 1. Make polar plots of these three kinds of orbits based on the polar equation of the conic section. Try various values for the parameter a (it is inversely proportional to the energy of the planet).

9. Make a surface plot of the Yukawa potential:

V Hx, yL =‰H-rLÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ

r CosB x

ÅÅÅÅÅrF, r =

è!!!!!!!!!!!!!!!x2 + y2

10. Make a contour plot of this same Yukawa potential.

11. A standing wave is described by the equation

yHx, tL = Sin@10 xD Cos@12 tDwhere x is the distance along the string, y is the height of the disturbance, and t is the time.

a) Create an animation of this function.

Landau, First Course in Scientific Computing 107

Copyright: Princeton Univ Press, RH Landau, 2005

Page 116: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

b) Create a surface plot of this function, and see if you agree with us that it is not as revealing as the animation.

12. A traveling wave is described by the equation

yHx, tL = Sin@10 x - 12 tDwhere x is the distance along the string, y is the height of the disturbance, and t is time.

a) Create an animation of this function.

b) Create a surface plot of this function, and see if you agree with us that it is not as revealing as the animation.

13. Give an example or two of the type of function(s) that would be visualized best with each of the following plots:

a) 2-D plot

b) 3-D plot

c) multifunction plot

d) parametric plot

e) animation

f) 3-d animation

14. Explain in just a few words what is meant by

a) an abstract data type

b) a parametric or phase space plot

c) a function of three variables

d) a list of three variables

15. Plot the function f(x) = Sec(x) + 4 over the interval [0,4 p]. Since Mathematica's automatic scaling does not work well here, you will need to specify a range for the ordinates to obtain a very useful visualization.

16. Given the points (1, 0.53), (1.5, 0.65), (2, 0.91), (2.5, 0.95), and (3, 1.10). Create a plot containing these points as well as the functions

aHxL = SinB xÅÅÅÅÅ2

F, bHxL =x2ÅÅÅÅÅÅÅÅ5

,

and thereby determine which function fits the data better?

108 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 117: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

Chapter 5: Solving Equations, Differentation; Towers

5.1 Problem: Maximum Height of a Building

The Washington Monument is 555 feet tall and is constructed from 36,000 white granite stones. The weighty marble and granite walls at the base are 15 feetthick, tapering to 18 inches thick at the top of the shaft. [USN&WR]

In our quest to rise above our fellow beings,we wish to build a really tall tower. We're not that good with big plans, but we are really good at building one level structures, and so we plan to stack our one level structures on top of one another until we reach the desired height.Your problem is to incorporate the fact that all materials compress when make to bear weight, and to see how this limits the maximum height of the tower.

5.2 Model: Stacking Blocks

0.2 0.4 0.6 0.8 1 1.2

0.5

1

1.5

2

2.5height

Fig. Blocks: A sample stacking of three blocks. Note how the bottom blocks are thinner (0.8 versus 1.0)

We model each level of the tower as a block of thickness t. By working with two blocks in our garage, we have deter-mined that when one block is placed atop another, there is a very small decrease a in the thickness t of the lower block:

t → t − α

After some thought and mental imagery, we deduce that if we have three blocks stacked atop each other, then the top block would have thickness t, the middle block thickness t-a, and the bottom block t-2a. The double compression of the bottom block arises because it must support the weight of the two blocks atop it.

Landau, First Course in Scientific Computing 109

Copyright: Princeton Univ Press, RH Landau, 2005

Page 118: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

5.2.1 Model Problem

Now that we have some idea of the model and tools we are able to apply to our problem, we reformulate it to one we are able to solve. On the other hand, while this is an important part of problem solving, it does means that when we are done solving our problem, we must verify that we have a correct mathematical solution, and then validate that our mathematical solution solves the physical problem.

1. Compute the height of a five-block tower by explicitly entering and summing each of the five block heights. Observe how the sum is accumulated and use that to deduce an algebraic expression for the height.

2. Suppose you had 10,000 blocks. You do not want to type in all those terms. Prove that the height H of a tower composed of n levels is:

H = nt − n Hn − 1L αê2 H5.2LHint: First prove that the sum of the first n integers is n(n+1)/2.

3. Check that your expression gives the same answer for the five-story tower as you worked out by hand.

4. Express H as a Mathematica function H[n,t,a] of three variables.

5. Use your function to determine, for arbitrary t and a, the number of blocks needed to make a tower of height 200.

6. How many blocks are needed to make a tower of height 200 feet for t = 15 feet and a = 0.001 t.

7. One way of defining maximum height is to imagine adding another level to the tower but not have its height increase (later on we will use a different definition of maximum height.) This is equivalent to finding a solution to the equation

H HnmaxL = H Hnmax + 1L H5.3LFind the algebraic value of nmax that satisfies equation (5.3).

8. Show that the solution to (5.3) corresponds to slipping the additional block onto the bottom of the stack and having it shrink to zero thickness.

9. If t = 15 feet and a = 0.001 t, what is the maximum height of the tower?

10. Test your function both numerically and symbolically by verifying that adding another level to the maximum number of levels does not increase the height, that is, that

H Hnmax + 1L = H HnmaxL H5.4L11. If we think of nmax as a continuous variable and take a mathematical point of view, then the maximum height

occurs at the point where an infinitesimal mail change in n leads to no change at all in the tower's height. Calculus tells us that this occurs when the derivative vanishes. That is, when

H Hn, t, aLn = 0 H5.5L

Use Mathematica's derivative function D[f[x],x] to determine „H(n,t,a)/„n.

12. Use Mathematica's Solve function to determine the value of n at which the derivative vanishes.

13. Explain in your own words why this is not the same as the solution to (5.4). What is the relation between the two?

110 Landau, First Course in Scientific Computing

Page 119: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

14. Plot up the results as a check. State in your own words how your graph shows the relation between the two definitions of maximum.

5.3 Math: Equations as Challenges

Consider the equation a x20 + b x = −c

You may think of this equation as a statement of mathematical fact; that the right hand and left hand sides of the equation have the same value.You may also view this equation as a challenge: for given values of the parameters a, b, and c, find some values of x that make both sides equal. Normally equations usually have variables on both sides of the equal sign, nevertheless, it is also legitimate to write them in generic form,

f HxL = 0a x20 + b x + c = 0

where the second version is for our problem. If f(x) is a symbolic expression, then Mathematica will automatically search for a symbolic solution of f(x)=0. If f(x) is numeric (contains floats or decimal points), then Mathematica will conduct a numerical search. We are not using the words ``search'' and ``challenge'' just to make mathematics seem exciting. For an arbitrary f(x), there is no guarantee that a solution exists or that Mathematica will find it even if one does exist.

In many cases, the function f(x) has a form for which no analytic solution exists. To prove the point, even the simple equation

x sin HxL = 1

does not have analytic solutions. However, there may be numeric ones, which leads to the somewhat philosophical ques-tion ``If it is possible to find a numerical solution, does that mean that we should also be able to find an analytic solution if we were smarter?" In some cases the answer is ``no'', in other cases ``yes'', and in others ``maybe''. In any case, it is usually faster for Mathematica to find a numerical solution than an analytic one. Therefore, if your ultimate interest is in a numeri-cal solution, for example to plot a graph, then it makes good sense to have Mathematica solve the equation numerically in the first place. If you truly want an analytic solution, you may have to rearrange or simplify the equation so that Mathemat-ica has a better chance with it, or even try some other program, like Maple, that employs different algorithms.

5.4 Solution of a Single Equation: Solve

Mathematica solves equations with the Solve command. Let us see if it can solve the general quadratic equation:

In[165]:= Solve@a∗x^2 + b∗x + c == 0, xDH∗ Find 2 nd argument that solves 1 st argument ∗LOut[165]= 99x →

−b −è!!!!!!!!!!!!!!!!!!!!b2 − 4 a c2 a

=, 9x →−b +

è!!!!!!!!!!!!!!!!!!!!b2 − 4 a c2 a

==

Landau, First Course in Scientific Computing 111

Copyright: Princeton Univ Press, RH Landau, 2005

Page 120: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[166]:= Solve@a x^2 + b x == −c, xD H∗ Alternate 1 st arg ∗LOut[166]= 99x →

−b −è!!!!!!!!!!!!!!!!!!!!b2 − 4 a c2 a

=, 9x →−b +

è!!!!!!!!!!!!!!!!!!!!b2 − 4 a c2 a

==Note the space between a and x and b and x in the second equation. This is important because it denotes multiplication. Without the space Mathematica would see ax as a single variable. A * for multiplication may be used instead to clarify.

Now let's talk about Mathematica's response. We see that there are two roots, and that Mathematica has returned them in a list, (a comma-separated sequence in braces), of replacement rules (the Ø's). Each replacement rule for x is in braces as well. In the case that the equation has roots of multiplicity m > 1, the replacement rule for the root is repeated m times.

Take note that the first argument to Solve is the equation to be solved and pay careful attention to the necessary double equal sign == in the equation. The double equal sign is a logical equality (LHS == RHS has a value True if and only if LHS and RHS have the same value). The second argument is a list of variables the equation is to be solved for. This argument is a list and hence needs to be enclosed in curly braces . If you do not specify a list of variables, Mathematica will probably not solve for the variable you want. However, if there is only one unknown in the equation, you do not need to include the second argument because Mathematica will be smart enough to solve for the single unknown variable:

In[167]:= Solve@3 x^2 + 2 x + 1 0DOut[167]= 99x →

13I−1 −

è!!!2 M=, 9x →13I−1 +

è!!!2 M==Back in our first example, we suspect that you think it obvious that since a x2 + b x + c = 0 is a quadratic equation in x, that Mathematica should know that you want the x values that solve it. Yet from an algebraic point of view, the parame-ters a, b, and c are also symbols for variables, and you may be interested in the solution of this equation for one of them. So try it and observe the differences:

In[168]:= H∗ Solve quadratic for a ∗LIn[169]:= H∗ Solve quadratic for b ∗LIn[170]:= H∗ Solve quadratic for c ∗L

As mentioned before, the conventional way to present an equation to be solved isf HxL = 0.

One would think that once the convention is known, they would no longer have to include the = 0 part of the equation. However, in Mathematica's Solve command, the first argument must be an equation using a double equal sign. Use of a single equal sign or no equal sign results in an error.

Sometimes the roots of an expression may be a pure number, sometimes a complex number (the  symbol), and sometimes an algebraic expression. As long as the solution is exact, the Solve command can be used. Observe too that Solve is best for linear and polynomial equations:

In[171]:= Solve@x^2 == 1D H∗ Find roots ∗LOut[171]= 88x → −1<, 8x → 1<<In[172]:= Solve@x^2 −1D H∗ Find roots... should be imaginary ∗LOut[172]= 88x → − <, 8x → <<In[173]:= Solve@x^2 + b 0, xD H∗ Find roots ∗LOut[173]= 99x → − è!!!b =, 9x → è!!!b ==

Sometimes even a simple function does not have exact roots:

112 Landau, First Course in Scientific Computing

Page 121: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[174]:= Solve@x Sin@xD − 1 0D H∗ Find the zeroes of x Sin@xD−1=0 ∗LSolve::tdep : The equations appear to involve the

variables to be solved for in an essentially non−algebraic way.

Out[174]= Solve@−1 + x Sin@xD == 0DConfusion seems appropriate after looking at Mathematica's response and the repetition of the command. The blue error message is not an answer, but rather an admission of defeat from the internal algorithm used by Solve. In this case, the transcendental equation x sin(x) -1 = 0 does not have an analytic solution, and so it is no surprise that Mathematica fails. However, because Mathematica does not know that the analytic solution truly does not exist, but only that it was unable to find it, Mathematica gives you an indication of where it failed. Knowledge of how and where Mathematica fails may be useful for advanced work, but for beginners it is easier to rearrange the equation and try again. (Soon we will show you how to solve this equation numerically.)

Various formulas that give closed-form expressions for the roots of quadratic, cubic, and quartic polynomials. And of course Mathematica knows them. For higher-order polynomials Mathematica has tricks, and it will try to use them as much as possible. However, there are some higher-order polynomials whose roots Mathematica cannot find. Here we give a case that works, and invite you to change some powers or add some terms until Mathematica fails (at least for some of the roots).

In[175]:= Solve@x^6 + 2 x^2 + 3 0, xD H∗ Mathematica suceeds here ∗LOut[175]= 98x → − <, 8x → <, 9x → −$%%%%%%%%%%%%%%%%%%%%%%%%%%%1

2−

è!!!!!!112

=,9x → $%%%%%%%%%%%%%%%%%%%%%%%%%%%1

2−

è!!!!!!112

=, 9x → −$%%%%%%%%%%%%%%%%%%%%%%%%%%%12

+è!!!!!!112

=, 9x → $%%%%%%%%%%%%%%%%%%%%%%%%%%%12

+è!!!!!!112

==In[176]:= Solve@x^8 + 2 x^3 + 5 0, xDH∗ Modify the parameters in the equation until Mathematica succeeds ∗LOut[176]= 88x → Root@5 + 2 #13 + #18 &, 1D<, 8x → Root@5 + 2 #13 + #18 &, 2D<,8x → Root@5 + 2 #13 + #18 &, 3D<, 8x → Root@5 + 2 #13 + #18 &, 4D<,8x → Root@5 + 2 #13 + #18 &, 5D<, 8x → Root@5 + 2 #13 + #18 &, 6D<,8x → Root@5 + 2 #13 + #18 &, 7D<, 8x → Root@5 + 2 #13 + #18 &, 8D<<

5.4.1 Verify Solution: The / . Replacement Operator

It is often convenient to use a variable to represent the equation to be solved and thereby avoid writing it many times and having very long commands. Suppose the equation to solve contains the product of factors (which makes it easy for us and Mathematica to know what the solution should be):Hx − aL2 Hx + bL3 Hx − cL = 0

We can use a symbol like eqn to represent the entire equation, and work with the symbol:

In[177]:= eqn = H−a + xL2 H−b + xL3 H−c + xL == 0Out[177]= H−a + xL2 H−b + xL3 H−c + xL == 0

Landau, First Course in Scientific Computing 113

Copyright: Princeton Univ Press, RH Landau, 2005

Page 122: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[178]:= ExpandAll@eqnD H∗ The full form of the equation ∗LOut[178]= a2 b3 c − a2 b3 x − 3 a2 b2 c x − 2 a b3 c x + 3 a2 b2 x2 + 2 a b3 x2 + 3 a2 b c x2 +

6 a b2 c x2 + b3 c x2 − 3 a2 b x3 − 6 a b2 x3 − b3 x3 − a2 c x3 − 6 a b c x3 − 3 b2 c x3 +

a2 x4 + 6 a b x4 + 3 b2 x4 + 2 a c x4 + 3 b c x4 − 2 a x5 − 3 b x5 − c x5 + x6 == 0

In[179]:= Solve@eqn, xDH∗ Solve for roots. Should be obvious from factored form ∗LOut[179]= 88x → a<, 8x → a<, 8x → b<, 8x → b<, 8x → b<, 8x → c<<

Once we have a solution, we verify it by substituting it back into the equation using the replacement operator /. and the transformation rule(s) given as solutions. Several replacements can be made, separated by commas, if braces are used:

In[180]:= eqn ê. 8x → a< H∗ Substituted solution ∗LOut[180]= True

The output is True because the equation was satisfied correctly. The replacement operator is also used with expressions to replace a variable by a value in the expression, and evaluate the expression. We will see this later on in this chapter.

5.4.2 Symbolic Solution: RootsWhile Solve is useful for solving equations, sometimes you may have more specialized needs. For example, you may want to find all the zeros or roots of a polynomial, as well as their multiplicity. The command Roots is a very powerful tool for finding the exact roots of a polynomial (but not the zeros of a transcendental equation). However, Roots is specialized, and we have found its use less robust and less obvious than Solve. Like Solve, Roots will give several identical equations when the roots with multiplicity greater than one occur:

In[181]:= Roots@x^2 − 1 0, xDOut[181]= x == 1 »» x == −1

Observe how the roots are separated by the logical or symbol ||. Roots even works when the zeroes involve imaginary numbers:

114 Landau, First Course in Scientific Computing

Page 123: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[182]:= Roots@x^2 + 1 0, xD H∗ Find root of x4−1 0 ∗LOut[182]= x == »» x == −

5.4.3 Numerical Solution: NSolve and FindRootBoth NSolve and FindRoot are used to find roots of single equation or a system of equations numerically. However, NSolve is limited to linear functions or polynomials while FindRoot is not (although it returns one root at a time). For example, we have seen that Solve cannot find solutions of x sin(x)=1, even though the simple sketch below should convince you that x sin(x) equals 1 for an infinite number of x values. Yet since the solutions can be written as an alge-braic expression, Solve cannot find them.

-100 -50 50 100x

-100

-50

50

x sin@xD

To use FindRoot, you must tell it where to start the search:

FindRoot[LHS==RHS, x, x0]

where the search starts at x = x0 . If Mathematica cannot evaluate the symbolic derivative of the equation, you must give two values of the x as starting points:

FindRoot[LHS=RHS, x, x0, x1].

As an instance, let us try to find a solution to our transcendental equation near x = 1:

In[183]:= FindRoot@x Sin@xD 1, 8x, 1<DOut[183]= 8x → 1.11416<

Of course, this is only one solution out of an infinite number, and is, presumably, the one closest to the starting value. Use the syntax, FindRoot[LHS==RHS, x, xstart, xmin, xmax] to find solutions within a certain range,:

In[184]:= FindRoot@x Sin@xD 1, 8x, 3, 2, 4<D H∗ Start at 3, x range 2−4 ∗LOut[184]= 8x → 2.7726<

Landau, First Course in Scientific Computing 115

Copyright: Princeton Univ Press, RH Landau, 2005

Page 124: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[185]:= FindRoot@x Sin@xD 1, 8x, 2, 0, 4<D H∗ Start at 2, x range 0−4 ∗LFindRoot::regex :

Reached the point 8−8.63058< which is outside the region 880., 4.<<.Out[185]= 8x → −8.63058<

Surprised? Picking good starting points is crucial for FindRoot to find an answer, and in order to pick good starting points, you must understand a little of how FindRoot works. FindRoot uses Newton's method to solve f(x)=0 starting at x0 . Knowledge of the derivative „ f ê„ x is used to take a sequence of steps toward a solution. An important thing to remember about Newton's method is that it gets ``stuck'' if it ever reaches a point where the derivative of the function vanishes.

5.5 Solving Simultaneous Equations (Sets)

5.5.1 Algebraic

If you have a few simultaneous equations to solve, then the Solve command works just fine. If you have a large number, say five or more, then it's probably more convenient and elegant to set your problem up as a matrix problem and use the techniques of linear algebra. We start with two simultaneous equations in two unknowns x and y:

x + 3 y + 4 = 415 x + 6 y + 7 = 20

First we assign an obvious variable name to each equation:

In[186]:= eqn1 = x + 3 y + 4 == 41eqn2 = 5 x + 6 y + 7 20

Out[186]= 4 + x + 3 y == 41

Out[187]= 7 + 5 x + 6 y == 20

Then we group this set of equations together within braces as eqn1, eqn2 to form the first argument to Solve. As the second argument, we enter the set x,y of variables we want to solve for:

116 Landau, First Course in Scientific Computing

Page 125: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[188]:= Solve[eqn1, eqn2, x, y]Out[188]= 99x → −

613

, y →1729

==(In this case the specification of x,y is unnecessary since we have two equations containing just two algebraic symbols. If the number of variable plus algebraic parameters is greater than the number of equations, then you must specify which variables to solve for.) Observe that Mathematica uses curly braces (indicating a set) and replacement rules to present its answer. Verify that the same solution is obtained regardless of the order of the equations eqn1, eqn2 in their set, and without the specification of the variables x,y:

In[189]:= H∗ Solve with interchanged equations ∗LThis example was fairly obvious, in part because we used a standard notation for the unknowns and had numerical values for the parameters. Yet now consider the two simultaneous equations:

a + 3 b + 4 c = 41

5 a + 6 b + 7 c = 20

There are clearly two equations and three unknown symbols a, b, and c. The rules of mathematics being as they are, this means that we can solve for any two of the unknowns in terms of the other one, but one unknown will always remain. As before, we first define variable names as labels for the equations:

In[190]:= Clear@eqn1Deqn1 = a + 3 b + 4 c 41

Out[191]= a + 3 b + 4 c == 41

In[192]:= Clear@eqn2Deqn2 = 5 a + 6 b + 7 c 20

Out[193]= 5 a + 6 b + 7 c == 20

Landau, First Course in Scientific Computing 117

Copyright: Princeton Univ Press, RH Landau, 2005

Page 126: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[194]:= Solve@8eqn1, eqn2<, 8a, b<DOut[194]= 99a →

13H−62 + cL, b →

19H185 − 13 cL==

Note here that we must specify a, b as the variables to solve for because there are three unknowns and we are only solving for two of them. Modify this solution so that it solves for b,c in terms of a:

In[195]:= H∗ Solve for b and c in terms of a ∗L5.5.2 Numeric, Linear

For a change of pace, let us say you want a numerical solution of the same two simultaneous equations we solved exactly before,

x + 3 y + 4 = 415 x + 6 y + 7 = 20

It is faster, and possibly more successful, to set up the problem with floating-point numbers rather than look for an exact solution. So we try NSolve:

In[196]:= H∗ Enter eqn1 and eqn2 ∗LH∗ Use NSolve to solve them ∗LThis clearly demonstrates the difference between NSolve and Solve; feel free to use whichever you prefer for polyno-mial equations.

5.5.3 Nonlinear Equations

Nonlinear equations are exactly what their name implies. They are equations containing functions that are not linear. Whereas quadratic, cubic and quartic equations are all nonlinear by this definition, Mathematica knows the closed-form solutions to these types of equations and has no trouble applying them. However, there may not be analytic solutions to other, even simple, nonlinear equations. In those cases the best that Mathematica does is to find numerical solutions.

Consider the simultaneous equations:sin HxL 3 cos HyL = 1

x 2 + y3 = 12

Enter these equations as a set and try solving them with Solve:

In[197]:= H∗ Enter eqn1 ∗L?eqn1Global`eqn1

eqn1 = a + 3 b + 4 c == 41

In[198]:= H∗ Enter eqn2 ∗L?eqn2Global`eqn2

eqn2 = 5 a + 6 b + 7 c == 20

118 Landau, First Course in Scientific Computing

Page 127: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[199]:= Solve@8eqn1, eqn2<, 8x, y<D H∗ Solve them with Solve ∗LOut[199]= 88<<

As you can see, this didn't exactly give us the results we were looking for. Try solving the equations with FindRoot, starting both x and y at 1:

In[200]:= FindRoot@8eqn1, eqn2<, 8x, 1<, 8y, 1< DFindRoot::frnum :

Function 8−41. + a + 3. b + 4. c, −20. + 5. a + 6. b + 7. c< is not alength 2 list of numbers at 8x, y< = 81., 1.<.

Out[200]= FindRoot@8eqn1, eqn2<, 8x, 1<, 8y, 1<DUse the replacement operator /. to check how well the solution satisfies both eqn1 and eqn2:

In[201]:= eqn1 ê. 8x → 3.19739, y → 1.21117<H∗ replacement operator checks solution ∗LOut[201]= a + 3 b + 4 c == 41

This tells us that the solution does not exactly satisfy the solution, but that is to be expected for a numerical solution. To determine how close we have gotten to a solution, we rewrite our equations as expressions and use the replacement opera-tor to evaluate them at the roots:

In[202]:= H∗ Equations as expressions, equaling 0 ∗Lexp1 = Sin@xD + 3 Cos@yD − 1exp2 = x^2 + y^3 − 12

Out[202]= −1 + 3 Cos@yD + Sin@xDOut[203]= −12 + x2 + y3

In[204]:= H∗ Use ê. to check how well the solution satisfies ∗Lexp1 ê. 8x → 3.19739, y → 1.21117<

Out[204]= 5.06917×10−6

We are close to zero, which means that we have a solution good to 5 parts in a million.

5.6 Solution to Tower Problem

Use Mathematica to find an algebraic expression for the height of a five-block tower.

In[205]:= H = t + Ht − aL + Ht − 2 aL + Ht − 3 aL + Ht − 4 aLOut[205]= −10 a + 5 t

H = 5 t − 10 a

Use Mathematica's Sum function to prove that the sum of the first n integers is n(n+1)/2.

Landau, First Course in Scientific Computing 119

Copyright: Princeton Univ Press, RH Landau, 2005

Page 128: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[206]:= Sum@i, 8i, 1, n<DOut[206]=

12n H1 + nL ‚

i=1

n

i =n Hn + 1L

2

Explain why the height of the tower consisting of n levels is:H = n t − n Hn − 1L aê2

The total height of n uncompressed blocks is nt. However, with our model, each block other than the top one gets com-pressed. Accordingly, the total height is computed by adding the heights of n successively thinner and thinner blocks:

H = t + Ht − aL + Ht − 2 aL + Ht − 3 aL + ... + Hn − 1L a =

n t − a − 2 a − 3 a − ... − Hn − 1L a = n t − a H1 + 2 + 3 + ... + Hn − 1LLHowever, we recognize the series we have summed above and can use that formula. Or we can use Mathematica to evaluate it:

In[207]:= H = n∗t − a∗Sum@i, 8i, 1, n − 1<DOut[207]= −

12a H−1 + nL n + n t

H = n t −1 a n Hn − 1L

2

Check that this expression (not function) gives the same answer for a five-story tower that you worked out.

In[208]:= n = 5H H∗ Now evaluate H for n=5 ∗L

Out[208]= 5

Out[209]= −10 a + 5 t

5

This agrees with the explicit five-term calculation, namely, H = 5t - 10a.

Express H as a Mathematica function of three variables, that is, define Hf[n, t, a].

In[210]:= Clear@H, nDHf@n_, t_, a_D := n∗t − a∗n∗

Hn − 1L2 ;

?HfGlobal`Hf

Hf@n_, t_, a_D := n t − 12 a n Hn − 1LHf@n_, t_, a_D := n t −

12a n Hn − 1L

Use your function and Mathematica's Solve command to determine how many blocks n are needed to make a tower of height 200 for arbitrary t and a.

120 Landau, First Course in Scientific Computing

Page 129: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[213]:= Solve@Hf@n, t, aD 200, 8n<DOut[213]= 99n →

a −è!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

−1600 a + H−a − 2 tL2 + 2 t2 a

=, 9n →a +

è!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!−1600 a + H−a − 2 tL2 + 2 t

2 a==

We see that there are two solutions for arbitrary t and a. This is to be expected for a quadratic equation. We suspect that only one of them will be physically meaningful.

Use your function and Mathematica's Solve command to determine how many blocks of thickness t = 15 feet are needed to make a tower of height 200 feet if the compression a = 0.001 t.

In[214]:= Solve@Hf@n, 15, 0.001∗15D 200, nDOut[214]= 88n → 13.4166<, 8n → 1987.58<<

We get two answers, n = 1987.58, or n=13.4, neither of them an integer. Since 13 * 15 = 195 and 14 * 15 = 210, the 13.4 answer is the one we would expect. The 1988 block tower seems unreasonable, and is related to a flaw in our model (as we shall see).

Is it possible within our model to add another level to the tower, but not have its height increase? Explain how the answer to this question is equivalent to finding a solution to the equation

H HnmaxL = H Hnmax + 1LThis definition of ``maximum'' corresponds to adding another block to the tower and not having it get any higher. So in some sense this is the maximum height, as adding another block will only make the tower shorter. What's happening is that at n = n max , the bottom block is squeezed to zero thickness in our model. Adding another block makes the bottom block negative in thickness. This is clearly a breakdown of our simple model.

Find the algebraic value of nmax that satisfies this last equation.

In[215]:= Clear@Hf, n, t, aDHf@n_, t_, a_D := n∗t − a∗n∗Hn − 1Lê2;?HfGlobal`Hf

Hf@n_, t_, a_D := n t − 12 a n Hn − 1L

In[218]:= Nmax = Solve@Hf@n, t, aD − Hf@n + 1, t, aD 0, nDOut[218]= 99n →

ta==

We should get the answer nmax =tÅÅÅÅa

If t = 15 feet and a = 0.001 t, what is the maximum height of the tower?

In[219]:= t = 15a = 0.001∗t

Out[219]= 15

Out[220]= 0.015

Landau, First Course in Scientific Computing 121

Copyright: Princeton Univ Press, RH Landau, 2005

Page 130: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[221]:= NmaxOut[221]= 88n → 1000.<<88n → 1000.<<

We could also do the evaluation more explicitly using the replacement operator /.:

In[222]:= Clear@n, a, tDNmax = Solve@Hf@n, t, aD − Hf@n + 1, t, aD 0, nD

Out[223]= 99n →ta==

In[224]:= Nmax ê. 8t → 15, a → 0.015<Out[224]= 88n → 1000.<<

Test your function both numerically and symbolically by verifying that adding another level to the maximum number of levels does not increase the height, that is, that

H Hnmax + 1L = H HnmaxL H4LIn[225]:= Nmax = têaOut[225]=

ta

In[226]:= Hf@Nmax + 1, t, aDOut[226]=

12t I1 +

taM

In[227]:= Hf@Nmax, t, aDOut[227]=

t2

a−12t I−1 +

taM

In[228]:= Factor@%D H∗ Factor previous expression ∗LOut[228]=

t Ha + tL2 a

122 Landau, First Course in Scientific Computing

Page 131: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[229]:= Factor@%%%D H∗ Factor expression 3 previous ∗LOut[229]=

t Ha + tL2 a

5.7 Differentiation: Limit, D, Derivative, Dt

Calculus was invented, at least from our point of view, to help solve physics problems. Derivatives arose in the study of kinematics where there was the need to define the velocity of an object at each instant of time. Specifically, the instanta-neous velocity is defined as the limit of the rate of change of position, for infinitesimally small time intervals:

In[230]:= v@t_D := Limit@Hx@t + ∆D − x@tDLê∆, ∆ → 0D;In[231]:= ?v

Global`v

v@t_D := Limit@ x@t+∆D−x@tD∆ , ∆ → 0D

Of course you should recognize this limit as the definition of derivative. Even today calculus is essential for solving scientific problems, and Mathematica is good at calculus. When speaking of calculus, we usually think of differentiation, integration, and differential equations. Differential equations are important in all areas of and levels of science and we discuss them in Chap. 15. For this section too, you may want to skim it, even if you are not yet familiar with the mathemat-ics, in part to make it easier to return to when you need them in your other courses (rest assured, you will).

Mathematica has the three commands D, Dt, and Derivative for differentiation. The one that provides the most elementary derivative is D. You give D an expression and a variable, and it returns the derivative of the expression with respect to that variable. Dt computes a more sophisticated type of derivative, the total derivative, in which it is assumed that all variables depend inherently upon the variable with respect to which you differentiate. We will not talk about Dt here, although we encourage those interested to check the Help Browser. The last type of derivative is Derivative. Rather than just return an answer, it returns the derivative as a Mathematica function or mapping that can be evaluated or plotted for multiple values.

5.7.1 Derivative of Expression: DThe D operator takes the derivative of a function and returns a function:

In[232]:= D@Sin@xD, xDOut[232]= Cos@xD

In the example above we took the derivative of a built-in function Sin[x]. You can also use D to take the derivative of a user-defined function:

In[233]:= f@x_D := Log@xDêH1 − xL; H∗ Define function f@xD=Log@xDêH1−xL ∗L?fGlobal`f

f@x_D := Log@xD1−x

Landau, First Course in Scientific Computing 123

Copyright: Princeton Univ Press, RH Landau, 2005

Page 132: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[234]:= D@f@xD, xDOut[234]=

1H1 − xL x +Log@xDH1 − xL2

You can also use D to take the derivative of an expression or formula:

In[235]:= D@x^7êH1 − xL, xDOut[235]=

7 x6

1 − x+

x7H1 − xL25.7.2 Second and Partial Derivative: DYou obtain a second derivative wrt x either by repeating the D command twice, or differentiating wrt the list x,2:

In[236]:= Clear@f, xDf@x_D := Sin@xD; H∗ Define function f@xD ∗L?fGlobal`f

f@x_D := Sin@xDIn[238]:= D@f@xD, xD H∗ Operate the D command once ∗LOut[238]= Cos@xDIn[239]:= D@%, xD H∗ Operate the D command again ∗LOut[239]= −Sin@xDIn[240]:= D@f@xD, 8x, 2<D H∗ D command for second derivative ∗LOut[240]= −Sin@xD

The D command with multiple derivatives allows you to express higher derivatives in succinct forms:

In[241]:= D@f@xD, 8x, 3<D H∗ Derivative wrt x3 ∗LOut[241]= −Cos@xD

124 Landau, First Course in Scientific Computing

Page 133: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[242]:= D@x^7êH1 − xL, 8x, 2<D H∗ 2 nd derivative ∗LOut[242]=

42 x5

1 − x+

14 x6H1 − xL2 +2 x7H1 − xL3

Exercise: Take the derivative twice of f(x) = logHxL ê H1 - xL and see if you get the same answer as taking the second derivative just once:

Partial Derivatives with D*We all know that you can only take derivatives with respect to some variables, so how come when we use D, we must tell Mathematica the variable to use for the derivative each time? The answer is not trivial. If the expression to differentiate is f(x) = sinHxLb , then Mathematica views both x and b as variables, and so must be told which one to differentiate with respect to. Try it:

In[243]:= H∗ Take derivative of Sin@xDb with respect to x ∗LIn[244]:= H∗ Take derivative of Sin@xDb with respect to b ∗L

When a function contains more than one variable, the differentiation process is called partial differentiation. The resulting derivatives are called partial derivatives and in mathematics are denoted with curly dee's, for example, ∑y f Hx, yL . In addition, since there are several variables, another type of second derivative is formed by differentiating one with respect to each of two different variables. For example, we form ∑y,x

2 sinHxLy by differentiating with respect to x and then y:

In[245]:= Clear@x, y, fDD@HSin@xDL^y, x, yD H∗ Second partial derivative wrt x & y ∗L

Out[246]= Cos@xD Sin@xD−1+y + y Cos@xD Log@Sin@xDD Sin@xD−1+y

Landau, First Course in Scientific Computing 125

Copyright: Princeton Univ Press, RH Landau, 2005

Page 134: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[247]:= D@HSin@xDL^y, y, xD H∗ Another second derivative form ∗LOut[247]= Cos@xD Sin@xD−1+y + y Cos@xD Log@Sin@xDD Sin@xD−1+y

5.7.3 Derivatives as Functions: DerivativeSometimes you may need to have the derivative you calculate to be what is calls a ``mapping'' or a proper function. For cases such as these, the Derivative operator is used to take the derivative of a function (not an expression) and to return the result as another function. This type of derivative and functional analysis is more subtle than the derivatives we have been taking with D, yet sometimes it is needed to get Mathematica to do what you want. In mathematics, operations that act on functions rather than variables are known as functionals. Derivative[1] is the Mathematica differentiation functional, with the full form Derivative[1][f].

To get a feel for the subtleties that arise with functions and operations on them, consider the two expressions for derivatives:

cos HtLt ,

cost HtL

The left expression implies the derivative of cos(t) with respect to t. The right expression indicates a new function, the derivative of cos, that is evaluated at t. In fact, it is the right type of expression that we often want to use as a function. While this may appear as just semantics, note that

∂t cos HπL = ∂t H−1L = 0

Accordingly, if the t in „cosHtL ê„ t indicates some value, then this is the derivative of a constant, which is clearly 0. So we must be careful with arguments when we transform one function, such as cos, into another function, such as „cos ê„ t . The Derivative form of derivative is designed to be used with this type of care. Let us look at some examples to see what this means. Imagine that we are given the position of a mass attached to a nonlinear spring as

x HtL = sin HtL + 0.3 sin HtL2We want to find the velocity v(t) = ∑t xHtL and the acceleration a(t)=∑t vHtL as functions of time. While we can do this

In[248]:= x@t_D := Sin@tD + 0.3 HSin@tDL^2; H∗ Defines function or mapping ∗L?xGlobal`x

x@t_D := Sin@tD + 0.3 Sin@tD2In[249]:= v@t_D := D@x@tD, tD;H∗ This mapping appears to define v@tD as derivative of x@tD ∗L

?vGlobal`v

v@t_D := ∂t x@tDIn[250]:= v@1D H∗ Does not work as proper function when number is given as arg ∗L

General::ivar : 1 is not a valid variable.

Out[250]= ∂1 1.05389

We see the problem here in that Mathematica does not accept v[1] as the velocity at t=1, although that clearly is what we want. The problem arises from the fact that D does not produce a true function as an answer. We will see now that Derivative does produce a function that is equal to the derivative of an old function:

126 Landau, First Course in Scientific Computing

Page 135: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[251]:= Clear@x, v, tDx@t_D := Sin@tD + 0.3 HSin@tDL^2; H∗ A true function or mapping ∗L?xGlobal`x

x@t_D := Sin@tD + 0.3 Sin@tD2In[253]:= Derivative@1D@xDH∗ Form a new ``pure'' function equal to the derivative of x ∗LOut[253]= Cos@#1D + 0.6 Cos@#1D Sin@#1D &In[254]:= %@tD H∗ Apply the function to a specific t ∗LOut[254]= Cos@tD + 0.6 Cos@tD Sin@tDIn[255]:= v@t_D := Derivative@1D@xD@tD ;H∗ Form v@tD = H∂t xL@tD true mapping. Applied arg in command ∗L

?vGlobal`v

v@t_D := x @tDIn[256]:= v@1DOut[256]= 0.813092

The derivative functions can be used as regular functions for plotting and so forth. For example, here we plot position, velocity, and acceleration:

In[257]:= a@t_D := Derivative@1D@vD@tD; H∗ Form new function for acceleration ∗L?aGlobal`a

a@t_D := v @tDIn[258]:= Plot@8x@tD, v@tD, a@tD<, 8t, 0, 10<,

PlotStyle → 8RGBColor@1, 0, 0D, RGBColor@0, 1, 0D, RGBColor@0, 0, 1D<D;H∗ Plot three functions ∗L2 4 6 8 10

-1.5

-1

-0.5

0.5

1

Let us look at some more examples of the use of Derivative for creating the derivative of a function or mapping. Consider the derivative of an arbitrary function g:

Landau, First Course in Scientific Computing 127

Copyright: Princeton Univ Press, RH Landau, 2005

Page 136: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[259]:= Clear@gDDerivative@1D@gD

Out[260]= g

Okay, we get back what we entered, which may be correct, but is not exciting. This is probably related to the fact that Mathematica does not know anything about g because it is arbitrary. But this does help us understand that if we give Derivative a function in which the argument is implicit (not stated or explicitly given), then Mathematica returns the derivative as an implicit function:

In[261]:= Derivative@1D@SinD H∗ Take derivative of Sin, an implicit function ∗LOut[261]= Cos@#1D &In[262]:= %@xD H∗ Evaluate the pure function with specific argument x ∗LOut[262]= Cos@xDIn[263]:= f@x_D := Log@xDêH1 − xL; H∗ An explicit function of x ∗L

?fGlobal`f

f@x_D := Log@xD1−x

In[264]:= Derivative@1D@fD@xD H∗ Derivative of f in explicit form with x ∗LOut[264]=

1H1 − xL x +Log@xDH1 − xL2

It is probably best to think of Derivative[1][f] as the name of an entirely new function, the derivative, and not as an operator acting on f(x). This is often a point of confusion in the mathematical notation for mappings and transformations. To evaluate this new function obtained by differentiation, we add the argument to Derivative[1][f], or in this case, Derivative[1][Sin]:

In[265]:= Derivative@1D@SinD@πDOut[265]= −1

In[266]:= Derivative@1D@SinD@tDOut[266]= Cos@tD

This makes sense if we think that first Sin is the argument to the Derivative[1] functional and that it creates a new function. This new function, in turn, is evaluated at an argument x. This naturally leads us to taking the function Derivative[1][f] and expressing it with any argument we want.

In[267]:= Derivative@1D@fD@xDOut[267]=

1H1 − xL x +Log@xDH1 − xL2

128 Landau, First Course in Scientific Computing

Page 137: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[268]:= Derivative@1D@fD@yDOut[268]=

1H1 − yL y +Log@yDH1 − yL2

Note that we do not indicate the fact that f is a function of some variable by giving an argument to f within the brackets of f, for example, as Derivative[1][f[x]]. However, we do state that we are taking the derivative with respect to the first variable of f only once with the [1] in the first place of the Derivative operator brackets. Since we are not indicating the derivative is taken with respect to x, Mathematica does not view x as a simple argument, but rather as a general variable or function which has yet to be defined. So if you ask Derivative to differentiate f[x], it assumes that x is some arbitrary function that may have a derivative of its own:

In[269]:= Clear@f, x, y, tDf@x_D := Log@xDêH1 − xL;?fGlobal`f

f@x_D := Log@xD1−x

In[272]:= Derivative@1D@f@xDDH∗ Derivative not evaluated bc x may have a derivative itself ∗LOut[272]= J Log@xD

1 − xN

Likewise, since f[15] is just a number, Derivative[1][f[15]] is the derivative of a constant, which of course, when evaluated numerically is zero:

In[273]:= Derivative@1D@f@15DDOut[273]= J−

Log@15D14

NIn[274]:= N@%DOut[274]= 0. &

As we have said before, if you want to evaluate the derivative function for argument 15, then you should think of Derivative[1][f] as the function:

In[275]:= Derivative@1D@fD@15DOut[275]= −

1210

+Log@15D196

5.7.4 Second and Partial Derivative: Derivative If f is a function of several variables, then you indicate which variable i (or variables) are to differentiated ni times by placement in the brackets, e.g., Derivative[2,1][f] or Derivative[2,0,1][f]. Second derivatives with the Derivative operator are formed by applying Derivative just once using the correct calling sequence,

Derivative@n1, n2, ...D@fD ,

where a function is obtained from f by differentiating n1 times with respect to the first argument, n2 times with respect to the second argument, and so on:

Landau, First Course in Scientific Computing 129

Copyright: Princeton Univ Press, RH Landau, 2005

Page 138: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[276]:= Clear@f, x, t, yDf@x_D := Log@xDêH1 − xL;?fGlobal`f

f@x_D := Log@xD1−x

In[279]:= Derivative@2D@fD@xD H∗ Second derivative on first argument of f ∗LOut[279]= −

1H1 − xL x2 +2H1 − xL2 x +

2 Log@xDH1 − xL3In[280]:= Derivative@2D@SinD H∗ Second derivative on built−in function ∗LOut[280]= −Sin@#1D &

When we have functions of several variables (multivariate functions) such as g(x,y) = sin(x) cos(y), then we can form different second derivatives by taking the partial derivative with respect to either x or y. You indicate the desired operation by including a sequence of numbers, where the number indicates which derivative you wish to take of the function with respect to the variable in that ``slot''. A ``slot'' for each argument of the function must be filled, even if filled with zero:

In[281]:= g@x_, y_D := Sin@xD∗Cos@yD; H∗ A function of two variables ∗L?gGlobal`g

g@x_, y_D := Sin@xD Cos@yDIn[282]:= Derivative@1, 0D@gD@x, yD H∗ 1 st derivative wrt 1 st variable only ∗LOut[282]= Cos@xD Cos@yDIn[283]:= Derivative@0, 1D@gD@x, yD H∗ 1 st derivative wrt 2 nd variable only ∗LOut[283]= −Sin@xD Sin@yDIn[284]:= Derivative@1, 1D@gD@x, yD H∗ Derivative wrt 1 st & 2 nd vars ∗LOut[284]= −Cos@xD Sin@yDIn[285]:= Derivative@1, 1D@gD@π ê4, π ê4DH∗ Second derivative with explicit arguments ∗LOut[285]= −

12

If the function does not have an explicit definition, then the Derivative operator yields as abstract form:

130 Landau, First Course in Scientific Computing

Page 139: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[286]:= Derivative@1, 1D@nD H∗ 2 nd partial derivative undefined function ∗LOut[286]= nH1,1L

Partial derivatives are generally independent of order, and in this case the command is the same either way because we wish to take the partial derivative with respect to each variable just once.

à 5.7.5 Inert Forms: Hold and ReleaseHold

We have seen that the D operator takes the derivative of a function and returns a function:

In[287]:= D@Sin@xD, xDOut[287]= Cos@xD

Sometimes it is important to see what command Mathematica thinks you have given it without having Mathematica actually do it. You accomplish this by telling Mathematica to defer execution:

HoldForm[command]

To see this happen, try this

In[288]:= HoldForm@D@Sin@xD, xDDOut[288]= ∂x Sin@xD

While the expression may be entered again and evaluated, you can also evaluate it via the ReleaseHold command:

In[289]:= ReleaseHold@%DOut[289]= Cos@xD

5.8 Numerical Derivatives

Normally when using Mathematica we are happy to have it calculate derivatives exactly, and it if cannot do that, then let Mathematica calculate the derivative numerically. We now ask the question, "How does one calculate a derivative numeri-cally?" This is interesting, as it is useful to understand how Mathematica does things under cover, as well as something we will need in Chapter 15, where we undertake a numerical study of projectile motion with friction. Determining a numeri-cal derivative is essentially determining the slope of a function, that is, drawing a tangent to a curve. This is not hard to do.

To be concrete, let us say we want a numerical approximation to the derivative of f HxL = Sin HxL

We know the exact answer here:

Landau, First Course in Scientific Computing 131

Copyright: Princeton Univ Press, RH Landau, 2005

Page 140: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[290]:= f@x_D := Sin@xD;Derivative@1D@fD@xD

Out[291]= Cos@xDThe exact derivative is defined as the limit:

In[292]:= Limit@Hf@x + ∆D − f@xDLê∆, ∆ → 0DOut[292]= Cos@xD

Numerical approximations use a similar approach, except that one skips the limiting process and simply does the division for a small but finite value of D:

fapproxx =

f Hx + ∆L − f HxL∆

So let us try this out for some typical values. We'll start with x = 1.0, and D = 0.1 (decimal points to ensure that Mathemat-ica does numerical computations), and compare the approximation to the exact answer:

In[293]:= PrintA" fexactx = ", [email protected] H∗ Use Print for nice format ∗L

fexactx

= 0.540302

In[294]:= PrintA" fapproxx = ", HSin@1 + 0.1D − Sin@1DLê.1E

fapproxx

= 0.497364

We see that the approximation is at least close. We can make the approximation better by using smaller, and smaller values for D:

In[295]:= PrintA" fapproxx = ", HSin@1. + 0.01D − [email protected]ê0.01E

fapproxx

= 0.536086

In[296]:= PrintA" fapproxx = ", HSin@1. + 0.001D − [email protected]ê0.001E

fapproxx

= 0.539881

The numerical derivative rule we have just outlined is called the forward difference approximation since it moves again by D and samples how the function changes. A more balanced rule, which requires no extra computation, is known as the central difference approximation. It evaluates the function on either side of x and takes that difference:

fCenDiffx =

f Hx + ∆ê2L − f Hx − ∆ê2L∆

We apply it now, using the same values for D as used for the forward difference rule:

In[297]:= PrintA" fexactx = ", [email protected] H∗ Exact answer ∗L

fexactx

= 0.540302

132 Landau, First Course in Scientific Computing

Page 141: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[298]:= PrintA" fCenDiffx = ", HSin@1. + 0.05D − Sin@1. − 0.05DLê0.1E

fCenDiffx

= 0.540077

In[299]:= PrintA" fCenDiffx = ", HSin@1. + 0.025D − Sin@1. − 0.025DLê0.05E

fCenDiffx

= 0.540246

In[300]:= PrintA" fCenDiffx = ", HSin@1. + 0.005D − Sin@1. − 0.005DLê0.01E

fCenDiffx

= 0.5403

We see that even the largest value of D yields three places of precision, with the approximation still improving as D is made smaller still. While serious scientific work uses even more precise algorithms, our exercise here should convince you that numerical derivatives can generally be trusted.

5.9 Alternate Solution: Maximum Tower Height

If we think of nmax as a continuous variable and take a mathematical point of view, then the maximum height occurs at the point where an infinitesimal change in n leads to no change at all in the tower's height. We know from calculus that this occurs when the derivative vanishes, that is, when

„H(n,t,a)/„n = 0.

Use Mathematica's derivative function D to determine „H(n,t,a)/„n.

In[301]:= Clear@n, t, a, x, vDHf@n_, t_, a_D := n∗t − a∗n∗Hn − 1Lê2;?HfGlobal`Hf

Hf@n_, t_, a_D := n t − 12 a n Hn − 1L

In[304]:= D@Hf@n, t, aD, nDOut[304]= −

12a H−1 + nL −

a n2

+ t

In[305]:= Expand@%DOut[305]=

a2

− a n + t

Use Mathematica's Solve function to determine the value of n that gives the mathematical maximum height.

Landau, First Course in Scientific Computing 133

Copyright: Princeton Univ Press, RH Landau, 2005

Page 142: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[306]:= Print@"Nmax = ", Solve@D@Hf@n, t, aD, nD 0, nDDNmax = 99n → −

− a2 − ta

==Explain in your own words why this is not the same as nmax .

Our previous definition of Nmax was one for which Nmax and Nmax + 1 both gave the same height. That definition gave

Nmax =ta and Nmax + 1 =

t + aa

as producing the same height. The derivative vanishes at t+ aÅÅÅÅ2ÅÅÅÅÅÅÅÅÅÅÅÅÅa , which is right between our previous two answers. Neither one is really more correct, but they do correspond to different definitions of maximum.

Plot up the results as a check.

We cannot make plots of symbolic functions, so lets assign values to t and a. We know from our computations that the maximum, in some sense of the word, occurs near n = 1000, so we'll narrow our plot to that region:

In[307]:= t = 15;a = 0.001∗t;Print@"t = ", tDPrint@"a = ", aDt = 15

a = 0.015

In[311]:= Plot@Hf@n, t, aD, 8n, 0, 1200<D ;H∗ View shows linear growth at first and curvature near maximum ∗L

200 400 600 80010001200

1000200030004000500060007000

134 Landau, First Course in Scientific Computing

Page 143: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[312]:= Plot@Hf@n, t, aD, 8n, 998, 1003<D;H∗ Plot over narrow range to highlight behavior near maximum ∗L999 1000 1001 1002 1003

7507.46

7507.47

7507.48

7507.49

So we do indeed see that the maximum height, as determined by the zero of the derivative with respect to the height, occurs at the true maximum of the graph, n = 1000.5, but that in terms of integer block numbers, there are maxima at n = 1000, and 1001.

5.10 Assessment & Exploration

1. What relevance might this model have to the building of actual skyscrapers? Specifically, can the same structural design be used on the top and bottom floors?

2. Although this occurs within our model, it is not realistic to have the addition of levels make the tower shorter. Explain in words whether an assumption is at fault or whether we have applied the model beyond its range of applicability.

3. Rather than equation (5.1), a more realistic model might assume that the blocks get harder to compress at some point and so their thickness never gets negative. An equation that describes this model is

t =t0

1 + b N2

where t is the thickness of a single block supporting N blocks above it, and b = 1/100 is a small number. Obtain and expression from Mathematica for the total height of a tower of N blocks. Hint: while the sum is simple, Mathematica may not be able to come up with a simple answer. However, you can always evaluate it numerically.

4. Derive a Mathematica function that calculates the height of a tower containing N blocks.

5. Is there a maximum height for the tower now? Plot up the results to be sure.

6. The rate of increase of the tower height with number of blocks is given by the derivative ∑n H . Is there some value of n which the rate of increase is a maximum? What is the numerical value for the maximum height now (use similar parameter values as before)?

Landau, First Course in Scientific Computing 135

Copyright: Princeton Univ Press, RH Landau, 2005

Page 144: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

5.11 Auxiliary Problem: Nonlinear Oscillations

1. A mass m = 2 kg is attached to a spring as in the figure above. The mass is moved from its equilibrium (rest) position and then released so that it oscillates about the equilibrium position . When the mass is a small distance x from the equilib-rium position, the restoring force f tending to bring the mass back to equilibrium is directly proportional to x:

f = −k x

Here k is the spring's force constant, and has the value k = 25 Newton / m The dynamical equation of motion for this system is Newton's second law of motion:

f = m a

−k x =m 2xt2

As shown in the study of simple harmonic motion, the solution for the position x as a function of time t is given by a trigonometric function, for example,

x HtL = Sin Hω tLω = $%%%%%%k

m

a) Write a Mathematica function which returns the position x(t) for any input argument t. (You know the numerical values of m and k, and therefore of w.

b) Plot the position as a function of time for times in the range 0 < t < 12.

c) Add labels and a title to your plot, and keep doing this for the rest of your life!

d) In mechanics we learn that velocity v is the first derivative of x with respect to time, and that acceleration a is the second derivative:

v HtL =xt

a HtL =vt =

2xt2

Use Mathematica's D operator to determine analytic expressions for velocity and acceleration as functions of time.

e) Determine whether equation (1) is true for this oscillator, that is, compare m a to the force -k x.

f) Plot on the same graph, x(t), v(t), and a(t) versus time for t between 0 and 10 with different colors for each of the three functions.

g) Take your plot and change the lines to dotted and then to bold. Decide if this makes it any clearer.

h) Make a phase space (parametric) plot for this system; that is, plot v(t) as the ordinate and x(t) as the abscissa. (This gives a new function v(x), the velocity

as a function of position.)

2. A more realistic model for an oscillator has the restoring force acting upon the mass depend slightly upon whether the

136 Landau, First Course in Scientific Computing

Page 145: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

mass is to the right or to the left of the origin (nonharmonic terms). For this case, the position as a function of time would be described by a function which is not purely harmonic:

x HtL = sin Hω tL + b@sin Hω tLD2where the small right-left asymmetry of this functional dependence means that b is a small number compared to 1. Note that the square bracket used in the mathematical expression shown cannot be entered into Mathematica without causing Mathematica to think you are referring to a function.

a) Modify your Mathematica function x(t) to a new one x(b,t), that is, a function of two variables. Test that for b=0 you get the harmonic oscillator back.

b) For this new oscillator, what are the velocity, acceleration and force as functions of time? Make several plots for a range of b values between 0 and 1. Add comments to your worksheet indicating for what b values the functions no longer looks sinusoidal.

c) Use a 3-D plot with axis and labels to examine x as a function of time for the entire range of b values. Examine the different options for displaying your surface, as well as different viewing angles. Print out several of the best representa-tions (assume that the printer can print gray scale only). Make sure one of your plots is of only the actual points that are calculated (no connecting lines), and that another one is of contours.

d) Examine the phase space (parametric) plot for this anharmonic oscillator for a range of b values.

e) Make a parametric plot of the force as a function of position for this anharmonic oscillator. Hint: In all cases, the force is given by

f = m a

but, for an anharmonic oscillator, this is not equal to -k x. Determining an analytic expression for this force as a function of x is more difficult.

f) Create two animations of this function, one in which the different frames correspond to different b values, and a second in which the different frames correspond to different times. Look at both and decide which produces the best visualization (animations are usually best to show time dependence).

5.12 Key Words and Concepts

derivative derivative operator limit mapping maximum

numerical/algebraic solutions partial derivative roots simultaneous

equations theory vs. model

Give three possible meanings of the words maximum height.

Are mathematical equations always true?

Must all equations have analytic solutions?

If an equation has a numeric solution, must it also have an analytic solution?

Do nonlinear equations occur in nature?

How are simultaneous equations different from other types?

Landau, First Course in Scientific Computing 137

Copyright: Princeton Univ Press, RH Landau, 2005

Page 146: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

Are all solutions to an equation equally valid?

Are nonlinear equations harder to solve than linear ones? If so, why?

Do you have to take a limit to evaluate a derivative?

Does it make sense to take the derivative of a function of several variables?

What is the difference in Mathematica between taking the derivative of an expression and a function?

Can you take the derivative of a number?

5.13 Supplementary Exercises

1. Use Solve, NSolve, and FindRoot to find as many solutions as you can of the equation

x3 + x2 + x = 1

2. Use Solve, NSolve, and FindRoot to find as many solutions as you can of the equation

x4 + c x3 + x2 + x = 1

Hint: you may need to assign numeric values to the constant c.

3. Use Solve, NSolve, and FindRoot to find as many solutions as you can of the equationHsin HxLL2 = x

Make a plot to check that your answer is reasonable. (Hint: negative x values should not be ignored).

4. Determine the limit, as e approaches zero of sinHx+ eL- sinHx LÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅe .

5. Determine the limit, as e approaches zero of sinHx+ eÅÅÅÅ2 L- sinHx- eÅÅÅÅ2 LÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅe .

6. Determine the limit, as c approaches infinity, of g(v) = 1ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ"###############1- v2ÅÅÅÅÅÅÅc2

.

7. Determine the first and second derivatives with respect to x of the following expressions:

a) xn

b) xH-nLc) 1ÅÅÅÅx

d) tan(x)

e) sin(sin(x))

f) a x2+ b x+ cÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅd x2 + e x+ f

g) è!!!!!!!!!!!!!!!1 - x4

8. Nonlinear equations are more interesting, but more challenging to solve, than linear equations. They are called nonlinear because the unknown appears to a higher power than the first. Find the solutions of the nonlinear, simultaneous equations:

138 Landau, First Course in Scientific Computing

Page 147: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

x2 − 4 y2 = 1x − 8 y3 = 3

9. You are given the mathematical expression

10 x4 sin(k x) to use in Mathematica.

a) If you enter this as a Mathematica expression (an object that takes no explicit arguments), how would you determine when the expression equals 0?

b) If you enter this as a Mathematica expression, how would you evaluate the first and second derivatives of the expression?

c) If you enter this as a Mathematica function, how would you determine when the function equals 0?

d) If you enter this as a Mathematica function, how would you evaluate the first and second derivative of the function?

10. In mechanics, we often study the position x of an object as a function of time t. If we take the first derivative of the position with respect to time, we get the velocity v as a function of time. In turn, the acceleration a is the second derivative of x with respect to time. In the following exercises, calculate x(t), v(t), and a(t) for each case, and plot all the functions on the same graph as a function of time 0 < t < 10. Use different colors for each function.

a) x(t) = 3 t2 + 5 t - 13

b) x(t) = è!!!!t3

c) x(t) = H ‰tLt

11. Here is a real function of the variables x, y, and, z:

g Hx, y, zL =1è!!!!!!!!!!!!!!!!!!!!!!!!!!!!x2 + y2 + z2

a) Define this function in Mathematica.

b) Check whether g is a solution of Laplace's differential equations by showing that the sum of the three deriva-tives equals 0: H∂x2 L g + H∂y2 L g + H∂z2 L g = 0

12. Find the first and second derivatives with respect to x of the following functions:

a) y = xÅÅÅÅÅÅÅÅÅÅÅÅx+ 1

b) y = ( 4 x2 + 3 x) ln(x)

c) y = tanh(3 x) ‰Iè!!!!!!!5 x Md) y = è!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!x3 + 4 x2 + 7 x + 1

13. A rock is hurled upward, and its distance above the ground is given by y = 210 t - 34 t2 . Use Mathematica to calculate

a) the maximum height from the ground of the rock.

b) the time at which the rock reaches the maximum height

c) the time at which the rock strikes the ground

d) the rock's speed when it hits the ground

14. Simplify

Landau, First Course in Scientific Computing 139

Copyright: Princeton Univ Press, RH Landau, 2005

Page 148: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

1R =

1R1

+1R2

HSolve for RLand then take the limit as R2 approaches infinity. Does your answer make sense?

140 Landau, First Course in Scientific Computing

Page 149: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

Chapter 7: Matrices and Vectors; Rotations

7.1 Problem: Rigid-Body Rotations

The study of rotations in classical mechanics is an excellent example of the use of vectors and matrices in science. The problem we study is basically an exercise that we work out in full and ask you to repeat for another case. For comparison, we repeat this same problem using Java matrices in Chap. 17. Even if you are not familiar with the physics, we suggest that you work with us through these examples as a review of matrices and as a preview as what is to come; it should also make learning the physics easier in the future.

-0.50

0.5x

-0.5

00.5y

-0.5

0

0.5

z

-0.50

0.5x

-0.5

00.5y

Fig. 7.1: A barbell consisting of two masses rotating about a fixed axis in the z direction.

Problem a (we work this one through for you): Consider Fig. 7.1 showing a barbell consisting of a mass m1 attached to mass m2 by a massless rigid body of length 2a. The barbell is fixed at an angle q with respect to the z axis, and is being rotated with an angular velocity vector w along the z axis.

a) Use Mathematica to determine the vector angular momentum L of this barbell by adding up the angular momenta of the individual masses.

b) Use Mathematica to evaluate the inertia tensor I for a barbell.

c) Form the matrix product of the inertia tensor and angular velocity I. w for the barbell and check that you get the same value for L as in a).

d) Make some 3-D plots of L and w for different times and thereby show that L rotates about a fixed w. From this we can deduce that there must be an external torque applied to the barbell.

Landau, First Course in Scientific Computing 152

Copyright: Princeton Univ Press, RH Landau, 2005

Page 150: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

-1-0.5

00.5

1

-1-0.5

00.5

1

-1

-0.5

0

0.5

1

-1-0.5

00.5

1

-1-0.5

00.5

1

-1-0.5 00.5 1

-1-0.5

00.51

-1-0.5

00.51

-1-0.5 00.5 1

-1-0.5

00.51

Fig. 7.2 Left: A 2-D rectangular plate of side 2; Bottom: A cube of side b.

Problem b: Consider a 2-D square plate having a mass m at each of four corners, as shown in Fig. 7.2. It is rotated with these three possible values for the angular velocity:

ω = J 10N, ω = J 0

1N, ω = J 1

1N

1. Use Mathematica to determine the angular momentum vector L of the plate by adding up the angular momenta of the individual masses.

2. Use Mathematica to evaluate the inertia tensor I for this plate. Hint: if this were a solid plate, its inertia tensor would be

I = J 1 00 4

N

3. Form the matrix product I. w of the inertia tensor I and the angular velocity w for the plate, and check that you get the same value for L as in 1.

4. Make some 3-D plots of L and w for different times and thereby show that L rotates about a fixed w. From this we can deduce that there must be an external torque applied to the plate.

5. (optional) Determine the torque acting on the plate.

Problem c: Consider now a 3-D cube having a mass m at each of eight corners, as shown in Fig. 7.2. Consider three possible values for the angular velocity,

iL ω = J 10N, ω = J 0

1N, ω = J 1

1N

153 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 151: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

1. Use Mathematica to determine the angular momentum vector L of the cube by adding up the angular momenta of the individual masses.

2. Use Mathematica to evaluate the inertia tensor I for this cube. Hint: if this were a solid cube, its inertia tensor would be

I =

i

k

jjjjjjjjjj

23 − 1

4 − 14

− 14

23 − 1

4

− 14 − 1

423

y

zzzzzzzzzz

3. Form the matrix product of the inertia tensor and angular velocity I. w for the cube and check that you get the same value for L as in a).

4. Make some 3-D plots of L and w for different times. Thereby show that L rotates about a fixed w. From this we can deduce that there must be an external torque applied to the cube.

5. (optional) Determine the torque acting on the cube.

7.2 Math: Vectors and Matrices

0.5 1 1.5 2

0.5

1

1.5

2

Fig. 7.3 Left: Representation of a vector as an arrow in 2-D space. Right: Representation of a vector as an arrow in a 3-D space. The projection of the arrow along each axis equals the components of the vector.

Classical mechanics is an area of physics that studies the motion of particles and objects. Before we describe the motion of a particle, we must first develop a system to specify the location of a particle in space. As illustrated in Fig. 7.2, we describe the location R of a point in space by drawing a set of perpendicular x and y axes, and then drawing a line from the origin O to the point R. An arrow head is usually added to this line segment to show its direction. An arrow in space is the most elementary representation of a vector.

We view Fig. 7.2 as showing a graphical representation of the displacement vector R. This vector has length or magnitude R = |R|, and a direction specified by giving the angle q that the vector makes with the x axis. A vector is usually denoted by a bold symbol, such as R, or sometimes by a symbol with an arrow over it. By convention, the magnitude of a vector is denoted by the same symbol used to denote the vector, only without the bold font or arrows. Even though the direction and magnitude of a vector is a good way to visualize a vector, calculations on vectors are usually easier to perform with the individual components of the vector. For our vector R, its components are just its projections along the positive x and y axes:

x = R cosHqL y = R sinHqL

Landau, First Course in Scientific Computing 154

Copyright: Princeton Univ Press, RH Landau, 2005

Page 152: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

Thus, if we know R and q, it is easy to use these equations to calculate x and y. In turn, if we know x and y, these equations can be solved for R and q:

R =è!!!!!!!!!!!!!!!!!!x2 + y2 q = arctanJ y

ÅÅÅÅÅÅx

NUsually these components are put together inside some kind of parenthesis to indicate that they are the components of a single object. Within the text of a document, they may be written in a horizontal row as (x, y), while in an equation they may be grouped as a vertical column:

R =ikjjj x

yyzzz

Whether a vector is viewed as an abstract symbol R or as the collection of components, it is the same object being viewed. Multiple representations are a good thing because sometimes it is easier to perform formal manipulations with abstract symbols rather than individual components, while other times it is easier to perform explicit calculations with the components.

We have drawn the vector R as if it were in a plane. If you spent more time away from the computer screen, you might realize that the real world has three dimensions (at least), and we really should be drawing our vectors in a 3-D space with components along the x, y, and z axes. As shown in Fig. 7.4, while the trigonometry is more complicated for 3-D vectors than 2-D ones, working with components stays much the same, only now we have three components to associate with R:

R =ikjjjjjjjj x

yz

yzzzzzzzzOther vectors in addition to the displacement vector $\mathbfR$ occur regularly in science. Examples include velocity, acceleration, force, and electric and magnetic fields (so you may as well start to understand them now if you do not already). Fortunately, the rules for decomposition into components are the same for all vectors, as are the rules for various algebraic manipulations.

7.2.1 Vector Operations and Matrices

Operating upon vectors that are represented by components is really quite easy since all you have to do is operate on the individual components using the ordinary rules of algebra. To illustrate, let us say that we have vectors A and B repre-sented by their three components,

A =ikjjjjjjjj Ax

AyAz

yzzzzzzzz, B =ikjjjjjjjj Bx

ByBz

yzzzzzzzzAddition and subtraction are defined as

A + B =ikjjjjjjjj Ax + Bx

Ay + ByAz + Bz

yzzzzzzzz, A - B =ikjjjjjjjj Ax - Bx

Ay - ByAz - Bz

yzzzzzzzzMultiplication of a vector by the constant c is defined by,

c A =ikjjjjjjjj cAx

cAycAz

yzzzzzzzzTwo vectors may multiply each other in two ways. The dot product is the sum of the product of their corresponding components:

155 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 153: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

A. B = Ax* Bx + Ay* By + Az* Bz

where the * next to the components of A indicate complex conjugate (the definition Mathematica uses). Geometrically, the dot product A . B is just the projection of A along the direction of B. Since this is just the sum of ordinary numbers, the result of dot multiplication produces a scalar (a quantity with no direction), and so is sometimes also called scalar multipli-cation.The second kind of multiplication of two vectors is called the cross product A ä B:

A ä B =ikjjjjjjjj Ay Bz - Az By

Az Bx - Ax BzAx By - Ay Bx

yzzzzzzzzGeometrically, the cross product A ä B is a new vector perpendicular to the plane formed by A and B, with magnitude | A | | B | sin(q), where q is the angle between the vectors A and B.

7.3 Theory: Angular Momentum Dynamics

A rigid body is one in which the distance between the particles that comprise the body do not change [M&T 88]. We imagine such an object rotating about a fixed point O (or about the center of mass of the body). In spite of it being true that each part of a rotating body has a different velocity, all parts have the same angular velocity w. The velocities of part i is related to w via:

v i = ω ri

where ri is a vector from the origin O to the particle i, and ä represents the vector cross product.

-1-0.5

00.5

1

-1-0.5

00.5

1

-1-0.5

0

0.5

1

-1-0.5

00.5

1

-1-0.5

00.5

1

Fig. 7.5 A cube of side b sitting in the center of a three-dimensional coordinate system.

Angular momentum is introduced into mechanics as the rotational analog of linear momentum. Angular momentum measures the tendency of a rotating object to remain rotating, and has a direction associated with it that is related to the angular velocity vector of the object. For the highly-symmetric cases usually studied in elementary physics, the angular momentum and angular velocity vectors are parallel to each other,

L = I w

with the proportionality constant I called the moment of inertia. However, when an object rotates about an axis that is not one of high symmetry, then L and w will not be parallel to each other, and a generalization of this equation is needed. The general relation between the angular momentum and the angular velocity follows from expressing the angular momentum of a group of particles as the sum of the angular momentum of each particle:

Landau, First Course in Scientific Computing 156

Copyright: Princeton Univ Press, RH Landau, 2005

Page 154: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

L = ‚i

ri ä pi

where pi = m i vi is the linear momentum of particle i. If we restrict ourselves to the rotation of a rigid body about a fixed point, then the velocity is related simply to the angular velocity and we have,

L = ‚mi ri ä Hw ä riL H7.14Lwhere the right-most vector cross product is performed first.

We now skip over the details of the derivation and give you the final result. For general problems, such as rotation of the cube in Fig. 7.4 about axes along a side of the cube, the angular velocity w and angular momentum vector L are related by what Maple calls the dot product of vector w with the inertia tensor

L = 8I<.wObserve how in the above equation we have placed braces around the symbol I. This indicates a type of mathematical object, a tensor, that transforms one vector into another vector. If the vectors are represented by columns (the usual thing), then we can represent the action of a tensor on a vector by the multiplication of that vector by a matrix:ikjjjjjjjj Lx

Ly

Lz

yzzzzzzzz =ikjjjjjjjj Ixx Ixy Ixz

Iyx Iyy Iyz

Izx Izy Izz

yzzzzzzzz ikjjjjjjjj wx

wy

wz

yzzzzzzzzWe see by looking at this equation, and by applying the rules of matrix algebra, that this one matrix equation is really an elegant way of presenting the three simultaneous linear equations relating the individual angular velocity and angular momentum components to each other:

Lx = Ixx wx + Ixy wy + Ixz wz

Ly = Iyx wx + Iyy wy + Iyz wz

Lz = Izx wx + Izy wy + Izz wz

It is, of course, easier to write this as one matrix equation L = I.w. In addition, it is much easier to manipulate the matrix equation than the individual equations.

The diagonal elements Ixx , Iyy , Izz of the inertia tensor are called the moments of inertia about the x, y, and z axes, respec-tively. They are the same as those used in elementary physics. The off-diagonal elements, such as Ixy = Iyx , are negatives of what are called products of inertia, and they are responsible for making w and L nonparallel. An explicit expression for the elements of I is [M&T 88]

Iij = ‡ r@vD ikjjjjjdijikjjjjj‚k

xk2yzzzzz - xi x j

yzzzzz „ v

for continuous mass, and

Ii, j = „a

maikjjjjjdij

ikjjjjj‚k

xa,k2yzzzzz - xa,i xa, j

yzzzzzfor discrete masses. Here the symbol dij is the Kronecker delta function,

dij = 1 Hif i = jL; = 0 HotherwiseL.

157 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 155: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

7.4 Mathematica: Linear Algebra Tools

In computing and science, confusion often arises from speaking of arrays and matrices as much the same thing. An array refers to the bookkeeping device used to store items by placing them in designated rows and columns. A matrix also has its elements stored in rows and columns, but it has well-defined mathematical properties. We shall speak more about this in Chapter 18, where we discuss these objects within the Java framework of programming with a compiled language. Now we shall look at some of the facilities Maple has for handling matrices and their algebraic manipulations. The more elemen-tary tone of the Java chapter on matrices may be more accessible to beginners than this chapter, where Maple's mathemati-cal sophistication requires a higher-level understanding of linear algebra.

In mathematics, the row or column is usually given by a subscript, with the row and column numbers starting from 1. As a case in point, Mi, j for an element in row i and column j, with M1,1 the first element of the matrix. In computer science, the rows and columns are indicted by indices, for example, Mi, j , with M0,0 the first element. There is essentially no limit to the number of indices an array may have, yet the maximum value that an index may have is limited by the finite amount of computer memory available. (At times the largest value that an index assumes is called the dimension of the array, while at other times the number of indices is called the dimension of the array. So, be careful! We call the number of indices the dimension.)

A vector in Mathematica is represented as a simple list, where the objects are contained within braces, elements. A matrix in Mathematica is represented as a list of vectors. This means we will be working with lists in Mathematica rather than the more general arrays. So beware, this means that subscripts begin at 1 and not 0 as they do in Java and C. Vectors and matrices play key roles in science and mathematics.Vectors are abstract objects that can be thought of as arrows in space, and matrices can be thought of as the operators that convert one vector into another. While vectors and matrices are represented by arrays and lists, there are many mathematical operations possible with these objects that permit us to define new algebras and spaces. The branch of mathematics called linear algebra deals with matrices.

Mathematica has several packages containing extensions for linear algebra, but, not-to-worry, the basic creation and mathematical operations for vectors and matrices can be done without loading any packages. Even some specialized commands for matrices such as Inverse, Det, and Transpose are built-in. However, the LinearAlgebra`Ma-trixManipulation` package is very useful for working with problems in linear algebra. It must be loaded prior to use (as discussed in Chapter 4 with the graphics packages) and the Names command can be used to get a list of the functions the package contains.

In[377]:= << LinearAlgebra`MatrixManipulation` H∗ Loads necessary package ∗L

Landau, First Course in Scientific Computing 158

Copyright: Princeton Univ Press, RH Landau, 2005

Page 156: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[378]:= Names@"LinearAlgebra`MatrixManipulation`∗"DOut[378]= 8AppendColumns, AppendRows, BlockMatrix, HankelMatrix, HilbertMatrix,

InverseMatrixNorm, LinearEquationsToMatrices, LowerDiagonalMatrix,LUMatrices, MatrixConditionNumber, MatrixNorm, PolarDecomposition,SquareMatrixQ, SubMatrix, TakeColumns, TakeMatrix, TakeRows,TridiagonalMatrix, UpperDiagonalMatrix, VectorNorm, ZeroMatrix<

Other useful packages in the LinearAlgebra folder include: FourierTrig.m, Gaussian-Elimination.m, Master.m, Orthogonalization.m, Tridiagonal.m, Vandermonde.m, and Cholesky.m. When you are doing linear algebra using Mathematica, take the time to load these packages and see what they have to offer.

à 7.4.1 Defining Matrices and Vectors

Vectors can be input manually as a list using List, or by using curly braces, elements. Here elements represents the elements of the list, with the elements separated by commas. Probably the easiest way to input vectors is with the built-in commands:

Table[expression, (i,n)] construct an n-dimensional vector with elements expression for i = 1, 2, 3, ... n

Array[f,n] makes an n-dimensional vector with elements f[1], f[2], ..., f[n], where f is a func-tion

In[380]:= cubes = 81, 8, 27, 64< H∗ Manually build vector of cubes ∗LOut[380]= 81, 8, 27, 64<

In[381]:= cubes = Table@i3, 8i, 4<D H∗ Build vector using Table ∗LOut[381]= 81, 8, 27, 64<

Matrices can be input in a variety of ways as well. The first is the direct entry using the menu

Input => Create Table/Matrix/Palette

Once chosen, a window pops up allowing you to choose the construct you want, the number of rows and columns, and other options. A 3 x 3 non-filled matrix will look like:

i

kjjjjjj

y

zzzzzz

You then enter the elements using the Tab key to navigate from cell to cell. Built-in commands and examples follow for producing matrices (see Help for short cut). Since matrices are represented as lists, Mathematica normally shows them as lists within curly braces. Matrices can be viewed as matrices using the MatrixForm[list] command, or using //Ma-trixForm to the right of a matrix or list in a command. This is for display purposes only and cannot be used in the definition of the matrix.

Table[expression, i, m, j, n]

constructs an m x n matrix whose elements are the values of expression for (i, j) = (1,1), ..., (m, n):

159 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 157: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[382]:= H∗ Construct 3 x 4 matrix ∗Lmatrix = Table@i − j, 8i, 3<, 8j, 4<DH∗ Build matrix using the Table ∗Lmatrix êê MatrixForm

Out[382]= 880, −1, −2, −3<, 81, 0, −1, −2<, 82, 1, 0, −1<<Out[383]//MatrixForm=

i

k

jjjjjjj0 −1 −2 −31 0 −1 −22 1 0 −1

y

zzzzzzz

Another command

Array[f, m, n]

produces an m x n matrix whole elements are f[1,1], ..., f[m,n],with f a function of two variables:

In[384]:= f@i_, j_D = i − j H∗ Same example with Array command ∗Lmatrix = Array@f, 83, 4<D H∗ 3 x 4 matrix ∗Lmatrix êê MatrixForm

Out[384]= i − j

Out[385]= 880, −1, −2, −3<, 81, 0, −1, −2<, 82, 1, 0, −1<<Out[386]//MatrixForm=

i

k

jjjjjjj0 −1 −2 −31 0 −1 −22 1 0 −1

y

zzzzzzz

Another command DiagonalMatrix[list] generates a diagonal matrix. Its diagonal elements are a one-dimensional list, and its off-diagonal elements are zeroes:

In[387]:= mylist = 8a, b, c, d, e, f<;m = DiagonalMatrix@mylistD;m êê MatrixForm

Out[389]//MatrixForm=

i

k

jjjjjjjjjjjjjjjjjjjjjj

0.015 0 0 0 0 00 2 0 0 0 00 0 9 0 0 00 0 0 d 0 00 0 0 0 e 00 0 0 0 0 f

y

zzzzzzzzzzzzzzzzzzzzzz

IdentityMatrix[n] creates the identity matrix of n dimension.

In[390]:= H∗ Try this with MatrixForm! ∗L

What do you suppose the MatrixForm command does for a simple one-dimensional vector? Try it:

In[391]:= H∗ Try MatrixForm on a vector ∗L

Matrix and vector elements are assigned and accessed by carefully using the [[ ]] notation or the Part command, just as with lists:

Landau, First Course in Scientific Computing 160

Copyright: Princeton Univ Press, RH Landau, 2005

Page 158: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[392]:= H∗ A matrix created by lists of lists,given row by row, and viewed using Print and MatrixForm ∗LB = 88−2, 2, −3<, 82, 1, 6<, 8−1, −2, 0<<;Print@"B = ", MatrixForm@BDDB =

i

k

jjjjjjj−2 2 −32 1 6

−1 −2 0

y

zzzzzzz

In[394]:= B@@3, 2DD H∗ Extract the element in row 3, column 2 ∗LOut[394]= −2

In[395]:= B@@3, 2DD = 7 H∗ Assign row 3, column 2 element ∗LPrint@"B = ", MatrixForm@BDD

Out[395]= 7

B =i

k

jjjjjjj−2 2 −32 1 6

−1 7 0

y

zzzzzzz

The matrix B is assigned as a list of lists (recall order matters in these lists), with each sublist being a row of the matrix, and the major list being a list of rows. Therefore you enter the elements row by row. You can extract the entire third row, by taking out the third sublist from B.

In[397]:= B@@3DD H∗ Getting third row of matrix B ∗LOut[397]= 8−1, 7, 0<

And the entire third column can be extracted by using the All directive.

In[398]:= B@@All, 3DD H∗ Getting third column of matrix B ∗LOut[398]= 8−3, 6, 0<

Once you have a matrix with numerical elements, you can visualize it easily via Mathematica's ListPlot3D command:

In[399]:= ID = IdentityMatrix@5D;In[400]:= ListPlot3D@ID, PlotLabel → "Identity Matrix",

AxesLabel → 8"column", "row", " "<D;Identity Matrix

12

34

5

column1

2

3

4

5

row0

0.250.5

0.751

12

34

5

column

161 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 159: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[401]:= ListPlot3D@B, PlotLabel −> "B Matrix", AxesLabel → 8"column", "row", ""<D;B Matrix

11.5

22.5

3column

1

1.5

2

2.5

3

row

-2.50

2.55

11.5

22.5

3column

Next we use the VectorQ and MatrixQ commands to see if the objects we have created are vectors or matrices. MatrixQ returns True if the argument is a list of lists that can represent a matrix. VectorQ gives True if the argument is a list, whose elements are not lists:

In[402]:= f@i_, j_D := x^Hi + 2∗j − 1L; H∗ Define function f ∗L?f

Global`f

f@x_D := Sin@xD

f@i_, j_D := xi+2 j−1

In[404]:= M = Table@f@i, jD, 8i, 2<, 8j, 2<D;H∗ Create a 2 x2 matrix, values given by f ∗LPrint@"M = ", MatrixForm@MDDM =

ikjjj x

2 x4

x3 x5yzzz

In[406]:= MatrixQ@MD H∗ Is M a matrix? ∗LOut[406]= True

In[407]:= VectorQ@MD H∗ Is M a vector? ∗LOut[407]= False

7.4.2 Column and Row Vectors

In physics we usually deal with vectors that represent objects having a magnitude and direction in space. In terms of components, we can specify the velocity vector by giving its three components:

v = Hvx, vy, vzL

We do this in Mathematica by entering a list of the three components with the MatrixForm command:

Landau, First Course in Scientific Computing 162

Copyright: Princeton Univ Press, RH Landau, 2005

Page 160: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[408]:= Clear@B, M, m, matrix, v, fDv = 8vx, vy, vz< H∗ Create v ∗LPrint@"v = ", MatrixForm@vDDH∗ As column vector ∗L

Out[409]= 8vx, vy, vz<

v =i

kjjjjjjvxvyvz

y

zzzzzz

In[411]:= v@@1DD H∗ First element of vector ∗LOut[411]= vx

Since Mathematica uses lists to represent vectors, there is no distinction as to whether the vector is a row or column vector. While this is a nice feature, if desired, we can create a row vector as a matrix with one row, i.e., a 1 x N matrix. Likewise, a column vector is the same as an N x 1 matrix. Remember, since explicit input of matrix elements are done row-by-row, a column matrix requires a list of lists, with each sublist containing the item for that row:

In[412]:= Ucol = 8810<, 820<, 830<<; H∗ Explicit column vector via list of lists ∗LPrint@"Ucol = ", MatrixForm@UcolDDUcol =

i

k

jjjjjjj102030

y

zzzzzzz

In[413]:= Ucol@@2, 1DD H∗ Look at element in matrix ∗LOut[413]= 20

In[414]:= Urow = 88a, b, c<<; H∗ Explicit row vector via list of lists ∗LPrint@"Urow = ", MatrixForm@UrowDDUrow = H 0.015 2 9 L

In[416]:= Urow@@1, 3DD H∗ Look at individual element, OK because matrix ∗LOut[416]= 9

In[417]:= Urow@@3DD H∗ Look at vector, not OK because is matrix ∗LPart::partw : Part 3 of 880.015, 2, 9<< does not exist.

Out[417]= 880.015, 2, 9<<P3T

à 7.4.3 Arrays

Arrays in Mathematica are essentially lists. They can be multi-dimensional and are then considered lists of lists, an exam-ple of which is a matrix. Arrays contain sequences of expressions, each specified by a certain index. Each expression is an element of the array and usually given by a function. The Array[f,n] command generates a list of length n with specified elements, f[i], or nested lists with elements f @i1, i2, ...D . You access the elements as you would from a list with the [[ ]] notation:

In[418]:= Clear@fD

163 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 161: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[419]:= f@x_D = 0;A1D = Array@f, 4D H∗ 1 D array with all same value ∗L

Out[420]= 80, 0, 0, 0<

In[421]:= A1D = Array@x, 4DOut[421]= 8x@1D, x@2D, x@3D, x@4D<

In[422]:= A2D = Array@x + y, 82, 2<D H∗ Create 2 D array ie a matrix ∗LOut[422]= 88Hx + yL@1, 1D, Hx + yL@1, 2D<, 8Hx + yL@2, 1D, Hx + yL@2, 2D<<

In[423]:= VectorQ@A1DD H∗Verify A1D is a vector ∗L

In[423]:= MatrixQ@A2DD H∗ Verify A2D is a matrix ∗LOut[423]= True

Implementing arrays as lists has a drawback in that you must fill in all the elements when you create the list. A more convenient approach is to fill elements as needed by making definitions for expressions such as a[i]:

In[424]:= a@1D = 9 H∗ Put values in a@1D and a@3D ∗La@3D = 7

Out[424]= 9

Out[425]= 7

In[426]:= ?a (* This shows all the values in a[] so far *)

Global`a

a = 0.015

In[427]:= Table@a@iD, 8i, 5<D H∗ Generates list of values of a@iD ∗LOut[427]= 80.015@1D, 0.015@2D, 0.015@3D, 0.015@4D, 0.015@5D<

In[428]:= a@3D =. H∗ Removes the value in a@3D ∗L

It is also possible to convert an indexed variable to an explicit List of length n using the Array[a, n]:

Landau, First Course in Scientific Computing 164

Copyright: Princeton Univ Press, RH Landau, 2005

Page 162: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[429]:= lista = Array@a, 3D;Print@"lista = ", listaDlista = 80.015@1D, 0.015@2D, 0.015@3D<

7.5 Matrix Arithmetic and Operations

Mathematica has straightforward ways of doing matrix arithmetic. Since n-dimensional vectors can be considered row vectors, (1 ä n matrices), or column vectors, (n ä 1 matrices), most of the commands apply to vectors as well.

7.5.1 Multiplication

Scalar Multiplication of each element of m by the scalar c is accomplished with the c * m command:

In[431]:= Clear@A, BDA = Table@Hi xL^j, 8i, 3<, 8j, 3<D ; H∗ Define matrix A ∗LPrint@"A = ", MatrixForm@ADDH∗ Display A in matrix form ∗L

A =i

k

jjjjjjjj

x x2 x3

2 x 4 x2 8 x3

3 x 9 x2 27 x3

y

zzzzzzzz

In[434]:= B = Table@i^j, 8i, 3<, 8j, 3<D; H∗ Define matrix B ∗LPrint@"B = ", MatrixForm@BDDH∗ Display B in matrix form ∗L

B =i

k

jjjjjjj1 1 12 4 83 9 27

y

zzzzzzz

In[436]:= 3∗ A êê MatrixForm H∗ Multiply A by a numeric constant and display ∗LOut[436]//MatrixForm=

i

k

jjjjjjjj

3 x 3 x2 3 x3

6 x 12 x2 24 x3

9 x 27 x2 81 x3

y

zzzzzzzz

Results were as we expected, however, what happens if the scalar is symbolic?

165 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 163: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[437]:= c∗ A êê MatrixForm H∗ Multiply A by a symbolic scalar and display ∗LOut[437]//MatrixForm=

i

k

jjjjjjjj

9 x 9 x2 9 x3

18 x 36 x2 72 x3

27 x 81 x2 243 x3

y

zzzzzzzz

This is right too, the scalar was distributed to all elements. [Not true in Maple.]

Matrix Multiplication follows the basic mathematical rule:

AM äN = BM äL CLäN

where the subscripts indicate the dimensions of the matrices. The Mathematica command for matrix multiplication and for the vector dot product is the dot .. For example, A.B computes the matrix product AB as a list of lists (matrix). The vector dot product command V1.V2 computes the dot product and returns a single number (discussed further soon). To avoid errors using the dot, place a space on either side of the dot:

In[438]:= Print@"A . B = ", [email protected]∗ Multiply square matrices A and B from above, and display ∗L

A . B =i

k

jjjjjjjj

x + 2 x2 + 3 x3 x + 4 x2 + 9 x3 x + 8 x2 + 27 x3

2 x + 8 x2 + 24 x3 2 x + 16 x2 + 72 x3 2 x + 32 x2 + 216 x3

3 x + 18 x2 + 81 x3 3 x + 36 x2 + 243 x3 3 x + 72 x2 + 729 x3

y

zzzzzzzz

In[439]:= Print@"B . A = ", MatrixForm @B.ADDH∗ Multiply two square matrices in reverse order ∗L

B . A =i

k

jjjjjjjj

6 x 14 x2 36 x3

34 x 90 x2 250 x3

102 x 282 x2 804 x3

y

zzzzzzzz

Note how easy it is to do matrix multiplication, especially with square matrices! However, pay careful attention to the fact that multiplying A by B is not the same as multiplying B by A; matrix multiplication does not commute (and unless the matrices are square it is not even possible).

The identity or unit matrix is always square and must be defined for a specific dimension. It's always worth checking, too, that is works on either side:

In[440]:= ID = IdentityMatrix@3D;ID êê MatrixForm

Out[441]//MatrixForm=

i

k

jjjjjjj1 0 00 1 00 0 1

y

zzzzzzz

Landau, First Course in Scientific Computing 166

Copyright: Princeton Univ Press, RH Landau, 2005

Page 164: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[442]:= A . ID êê MatrixForm H∗ Check R & L matrix multiplication ∗LID . A êê MatrixForm

Out[442]//MatrixForm=

i

k

jjjjjjjj

x x2 x3

2 x 4 x2 8 x3

3 x 9 x2 27 x3

y

zzzzzzzz

Out[443]//MatrixForm=

i

k

jjjjjjjj

x x2 x3

2 x 4 x2 8 x3

3 x 9 x2 27 x3

y

zzzzzzzz

Mathematica has the command MatrixPower[m,n] that raises the matrix m to the nth power:

In[444]:= MatrixPower@A, 3D êê MatrixForm H∗ A3 ∗LOut[444]//MatrixForm=

i

k

jjjjjjjj

x Hx2 + 2 x3 + 3 x4L + x2 H2 x2 + 8 x3 + 24 x4L + x3 H3 x2 + 18 x3 + 81 x4L x Hx3 + 4 x4

2 x Hx2 + 2 x3 + 3 x4L + 4 x2 H2 x2 + 8 x3 + 24 x4L + 8 x3 H3 x2 + 18 x3 + 81 x4L 2 x Hx3 + 4 x4 +

3 x Hx2 + 2 x3 + 3 x4L + 9 x2 H2 x2 + 8 x3 + 24 x4L + 27 x3 H3 x2 + 18 x3 + 81 x4L 3 x Hx3 + 4 x4 +

Matrix-Vector Multiplication takes a vector (a J x 1 matrix) and multiplies it by a J x J matrix and produces another J x 1 vector:

In[445]:= vec = 8a, b, c<; H∗ Make a column−vector ∗LPrint@"vec = ", MatrixForm@vecDDvec =

i

k

jjjjjjj0.01529

y

zzzzzzz

In[446]:= B = Table@i^j, 8i, 3<, 8j, 3<D; H∗ Define matrix B ∗LPrint@"B = ", MatrixForm@BDDH∗ Display B in matrix form ∗L

B =i

k

jjjjjjj1 1 12 4 83 9 27

y

zzzzzzz

In[448]:= B . vec êê MatrixForm H∗ Multiply matrix by vector ∗LOut[448]//MatrixForm=

i

k

jjjjjjj11.01580.03261.045

y

zzzzzzz

In[449]:= vec . B êê MatrixForm H∗ Multiply vector by matrix ∗LOut[449]//MatrixForm=

i

k

jjjjjjj31.01589.015259.015

y

zzzzzzz

In[450]:= urow = 88a, b, c<<; H∗ Make an explicit 3 column row−vector ∗LPrint@"urow = ", MatrixForm@urowDDurow = H 0.015 2 9 L

167 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 165: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[451]:= B . urow êê MatrixForm H∗ 3 x3 matrix times 1 x3 vector ?? ∗LOut[451]//MatrixForm=

881, 1, 1<, 82, 4, 8<, 83, 9, 27<<.880.015, 2, 9<<

Because Mathematica uses lists to represent vectors, there is no distinction between row and column vectors, so both B .vec and vec . B are defined, although in general they produce different results, as was the case here. To make an explicit row-vector in Mathematica, we made a matrix with only one row, urow. Then we tried to multiply B times urow, which produced an expected error from the incompatible sizes of B and urow. What if you switch order of the vector and matrix?

In[452]:= urow . B êê MatrixForm H∗ Try the switch here,do urow . B ∗LOut[452]//MatrixForm=

H 31.015 89.015 259.015 L

Matrix Addition and Subtraction use the + and - operators, with parentheses (... ) used to group operations. Beware: these commands are real smart and will do the ``obvious'' thing if you try to add together different combinations of vectors, matrices, and scalars; however, you must ensure that what is obvious to Mathematica is what you want:

In[453]:= Clear@A, B, vec, v1, v2, ucol, urowDA = Table@Hi xL^j, 8i, 3<, 8j, 3<D; H∗ Define matrix A ∗LPrint@"A = ", MatrixForm@ADDA =

i

k

jjjjjjjj

x x2 x3

2 x 4 x2 8 x3

3 x 9 x2 27 x3

y

zzzzzzzz

In[455]:= B = Table@i^j, 8i, 3<, 8j, 3<D; H∗ Define matrix B ∗LPrint@"B = ", MatrixForm@BDDB =

i

k

jjjjjjj1 1 12 4 83 9 27

y

zzzzzzz

In[456]:= vec1 = 8a, b, c<; H∗ Two 3 D vectors ∗Lvec2 = 81, 2, 3<;Print@"vec1=", MatrixForm@vec1DDPrint@"vec2=", MatrixForm@vec2DDvec1=

i

k

jjjjjjj0.01529

y

zzzzzzz

vec2=i

k

jjjjjjj123

y

zzzzzzz

In[459]:= A + B êê MatrixForm H∗ Try matrix addition ∗LOut[459]//MatrixForm=

i

k

jjjjjjjj

1 + x 1 + x2 1 + x3

2 + 2 x 4 + 4 x2 8 + 8 x3

3 + 3 x 9 + 9 x2 27 + 27 x3

y

zzzzzzzz

Landau, First Course in Scientific Computing 168

Copyright: Princeton Univ Press, RH Landau, 2005

Page 166: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[460]:= A − B êê MatrixForm H∗ Try matrix subtraction ∗LOut[460]//MatrixForm=

i

k

jjjjjjjj

−1 + x −1 + x2 −1 + x3

−2 + 2 x −4 + 4 x2 −8 + 8 x3

−3 + 3 x −9 + 9 x2 −27 + 27 x3

y

zzzzzzzz

In[461]:= vec1 + vec2 êê MatrixForm H∗ Try vector addition ∗LOut[461]//MatrixForm=

i

k

jjjjjjj1.015412

y

zzzzzzz

In[462]:= ID = IdentityMatrix@3DOut[462]= 881, 0, 0<, 80, 1, 0<, 80, 0, 1<<

In[463]:= A + H2 IDL êê MatrixForm H∗ Addition of matrix and scalar times ID ∗LOut[463]//MatrixForm=

i

k

jjjjjjjj

2 + x x2 x3

2 x 2 + 4 x2 8 x3

3 x 9 x2 2 + 27 x3

y

zzzzzzzz

In[464]:= A + 2 êê MatrixForm H∗ Addition of 2 to ALL elements of matrix A ∗LOut[464]//MatrixForm=

i

k

jjjjjjjj

2 + x 2 + x2 2 + x3

2 + 2 x 2 + 4 x2 2 + 8 x3

2 + 3 x 2 + 9 x2 2 + 27 x3

y

zzzzzzzz

In[465]:= A − Hλ IDL êê MatrixForm H∗ Subtraction of scalar lambda times ID ∗LOut[465]//MatrixForm=

i

k

jjjjjjjj

x − λ x2 x3

2 x 4 x2 − λ 8 x3

3 x 9 x2 27 x3 − λ

y

zzzzzzzz

In[466]:= vec1 + 1 êê MatrixForm H∗ Addition of 1 to each element of vector ∗LOut[466]//MatrixForm=

i

k

jjjjjjj1.015310

y

zzzzzzz

In[467]:= 2 A + 3 B êê MatrixForm

Out[467]//MatrixForm=

i

k

jjjjjjjj

3 + 2 x 3 + 2 x2 3 + 2 x3

6 + 4 x 12 + 8 x2 24 + 16 x3

9 + 6 x 27 + 18 x2 81 + 54 x3

y

zzzzzzzz

169 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 167: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[468]:= 4∗vec1 + 3∗vec2 êê MatrixForm

Out[468]//MatrixForm=

i

k

jjjjjjj3.061445

y

zzzzzzz

7.5.2 Other Matrix Operations

Now we define a 3 x 3 and a 4 x 4 matrix. The matrix A has three rows, each proportional to the others, and the matrix ID is the 4-D identity matrix:

In[469]:= Clear@A, B, ID, vec1, vec2DA = 881, 2, 3<, 82, 4, 6<, 83, 6, 9<<;Print@"A = ", MatrixForm@ADDA =

i

k

jjjjjjj1 2 32 4 63 6 9

y

zzzzzzz

In[472]:= ID = IdentityMatrix@4D;Print@"ID =", MatrixForm@IDDDID =

i

k

jjjjjjjjjjjj

1 0 0 00 1 0 00 0 1 00 0 0 1

y

zzzzzzzzzzzz

Before we go ahead and evaluate the determinant of each, we observe that the rows in A are not independent, and so its determinant should vanish, while the determinant of a diagonal matrix, such as the identity matrix, is just the product of the diagonal elements:

In[474]:= Det@AD H∗ Proportional rows, determinant should vanish ∗LOut[474]= 0

In[475]:= Det@IDD H∗ Should be product of diagonal elements ∗LOut[475]= 1

In[476]:= B = Table@i^j, 8i, 3<, 8j, 3<D; H∗ Matrix B with independent rows ∗LPrint@"B = ", MatrixForm@BDDB =

i

k

jjjjjjj1 1 12 4 83 9 27

y

zzzzzzz

In[478]:= Det@BDOut[478]= 12

Landau, First Course in Scientific Computing 170

Copyright: Princeton Univ Press, RH Landau, 2005

Page 168: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[479]:= Binv = Inverse@BD;Binv êê MatrixForm H∗ If determinant nonzero, inverse exists ∗L

Out[480]//MatrixForm=

i

k

jjjjjjjjjj

3 − 32

13

− 52 2 − 1

212 − 1

216

y

zzzzzzzzzz

In[481]:= B . Binv êê MatrixForm H∗ B times its inverse ∗LOut[481]//MatrixForm=

i

k

jjjjjjj1 0 00 1 00 0 1

y

zzzzzzz

In[482]:= Binv . B êê MatrixForm H∗ B inverse times B ∗LOut[482]//MatrixForm=

i

k

jjjjjjj1 0 00 1 00 0 1

y

zzzzzzz

(We remind you again that even though MatrixForm displays the matrix in columns and rows, Mathematica still stores it as a list. )

In[483]:= Transpose@AD êê MatrixFormH∗ Check for interchanged rows & columns ∗L

Out[483]//MatrixForm=

i

k

jjjjjjj1 2 32 4 63 6 9

y

zzzzzzz

In[484]:= Tr@ADH∗ Check trace = sum of diagonal elements ∗L

Out[484]= 14

In[485]:= Tr@IDD H∗ Check for ID ∗LOut[485]= 4

In[486]:= A = 88a, b, c<, 8a^2, b^2, c^4<, 8a, b, c^4<<;Print@"A = ", MatrixForm@ADDA =

i

k

jjjjjjj0.015 2 9

0.000225 4 65610.015 2 6561

y

zzzzzzz

In[488]:= Ainverse = Inverse@AD;Ainverse êê MatrixForm

Out[489]//MatrixForm=

i

k

jjjjjjj33.6314 −33.5852 33.53910.248452 0.251889 −0.25223

−0.000152625 0. 0.000152625

y

zzzzzzz

171 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 169: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[490]:= MatrixPower@A, −1D êê MatrixForm H∗ Find inverse as A−1 ∗LOut[490]//MatrixForm=

i

k

jjjjjjj33.6314 −33.5852 33.53910.248452 0.251889 −0.25223

−0.000152625 0. 0.000152625

y

zzzzzzz

In[491]:= FullSimplify@%D êê MatrixForm H∗ Try to get a simplified answer ∗LOut[491]//MatrixForm=

i

k

jjjjjjj33.6314 −33.5852 33.53910.248452 0.251889 −0.25223

−0.000152625 0. 0.000152625

y

zzzzzzz

In[492]:= A . Ainverse êê MatrixFormH∗ Check if result is identity matrix ∗L

Out[492]//MatrixForm=

i

k

jjjjjjjjj

1. −8.0231×10−18 6.17453×10−17

−4.51028×10−17 1. 1.65883×10−17

−4.4886×10−17 −8.0231×10−18 1.

y

zzzzzzzzz

In[493]:= Map@FullSimplify, %D êê MatrixFormH∗ Simplify for humans, should get identity ∗L

Out[493]//MatrixForm=

i

k

jjjjjjjjj

1. −8.0231×10−18 6.17453×10−17

−4.51028×10−17 1. 1.65883×10−17

−4.4886×10−17 −8.0231×10−18 1.

y

zzzzzzzzz

As we have just seen, the Map command applies a function to each element of its second argument, whether it be a matrix or a list, and displays the result. If the first argument is a matrix, then each element of the matrix has the function applied to it, and the resulting matrix is displayed. However, it will not place the result back into the original expression, as it does in Maple. You may assign the result to a new variable if you wish to keep it. Map can be used on expressions other than lists as well:

In[494]:= Map@f, x + y∗zD H∗ Use Map on ordinary function ∗LOut[494]= 0

In[495]:= Map@f, 8a, b, c<D H∗ Map used on list ∗LOut[495]= 80, 0, 0<

In[496]:= Clear@A, fDA = Table@Hi∗xL^j, 8i, 3<, 8j, 3<D;Print@"A = ", MatrixForm@ADDH∗ Define matrix A again ∗L

A =i

k

jjjjjjjj

x x2 x3

2 x 4 x2 8 x3

3 x 9 x2 27 x3

y

zzzzzzzz

Landau, First Course in Scientific Computing 172

Copyright: Princeton Univ Press, RH Landau, 2005

Page 170: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[499]:= Map@f, AD êê MatrixForm

Out[499]//MatrixForm=

i

k

jjjjjjjj

f@8x, x2, x3<Df@82 x, 4 x2, 8 x3<Df@83 x, 9 x2, 27 x3<D

y

zzzzzzzz

An option with the Map command in Mathematica is to specify how many levels of the expression on which to apply the function. In the previous command, the default level 1 was used and f was applied to the first level of the matrix A, that is, f was applied to each row but not each element. Let us see what specifying level 2 does:

In[500]:= Map@f, A, 2D êê MatrixForm H∗ f is applied to each element of A ∗LOut[500]//MatrixForm=

i

k

jjjjjjjj

f@8f@xD, f@x2D, f@x3D<Df@8f@2 xD, f@4 x2D, f@8 x3D<Df@8f@3 xD, f@9 x2D, f@27 x3D<D

y

zzzzzzzz

In[501]:= A êê MatrixForm H∗ A not mapped function ∗LOut[501]//MatrixForm=

i

k

jjjjjjjj

x x2 x3

2 x 4 x2 8 x3

3 x 9 x2 27 x3

y

zzzzzzzz

In[502]:= A = Table@Hi∗xL^j, 8i, 3<, 8j, 3<D;Print@"A = ", MatrixForm@ADD H∗ A again ∗L

A =i

k

jjjjjjjj

x x2 x3

2 x 4 x2 8 x3

3 x 9 x2 27 x3

y

zzzzzzzz

In[504]:= Map@D, AD êê MatrixFormH∗ Try to take derivative of each element in A ∗L

Out[504]//MatrixForm=

i

k

jjjjjjjj

x x2 x3

2 x 4 x2 8 x3

3 x 9 x2 27 x3

y

zzzzzzzz

We must admit that this is not what we expected! If the function you wish to map on each element takes an argument on its own, then Map will not work properly. This was shown above with the D function. However, you can take the deriva-tive of a matrix by putting the matrix into the argument of the D function:

In[505]:= D@A, xD êê MatrixForm H∗ Take derivative of each element wrt x ∗LOut[505]//MatrixForm=

i

k

jjjjjjjj

1 2 x 3 x2

2 8 x 24 x2

3 18 x 81 x2

y

zzzzzzzz

à 7.5.3 Vector Operations

Not only can Mathematica deal with matrices, but it does vector operations including calculus. We start by setting up a matrix and some vectors with which to experiment. We intermix symbolic and numerical objects:

173 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 171: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[506]:= Clear@A, ucol, urowDA = 881, 2, 3<, 82, 4, 6<, 83, 6, 9<<;Print@"A = ", MatrixForm@ADDA =

i

k

jjjjjjj1 2 32 4 63 6 9

y

zzzzzzz

In[509]:= ucol = 810, 20, 30<; H∗ A column matrix HvectorL ∗LPrint@"ucol =", MatrixForm@ucolDDucol =

i

k

jjjjjjj102030

y

zzzzzzz

In[510]:= urow = 88a, b, c<<; H∗ A row matrix HvectorL ∗LPrint@"urow =" , MatrixForm@urowDDurow =H 0.015 2 9 L

In[511]:= vec = 8x, y∗x^2, Sin@xD<Out[511]= 8x, x2 y, Sin@xD<

We start by multiplying vectors by matrices.

In[512]:= A . vec êê MatrixFormH∗ Note this is multiply and NOT dot product ∗L

Out[512]//MatrixForm=

i

k

jjjjjjjj

x + 2 x2 y + 3 Sin@xD2 x + 4 x2 y + 6 Sin@xD3 x + 6 x2 y + 9 Sin@xD

y

zzzzzzzz

In[513]:= A . ucol êê MatrixForm H∗ Multiply vector by matrix, OK ∗LOut[513]//MatrixForm=

i

k

jjjjjjj140280420

y

zzzzzzz

In[514]:= A . urow êê MatrixForm H∗ Fails due to dimensions mismatch ∗LDot::dotsh : Tensors 881, 2, 3<, 82, 4, 6<, 83, 6, 9<<

and 880.015, 2, 9<< have incompatible shapes.

Out[514]//MatrixForm=

881, 2, 3<, 82, 4, 6<, 83, 6, 9<<.880.015, 2, 9<<

As we indicated in Sec. 7.2 with the mathematics, there are a number of ways in which one vector can get multiplied by another. We will look at a few of them here.

In[515]:= Print@"vec =", MatrixForm @vecDD H∗ Recall vec ∗L

vec =i

k

jjjjjjjx

x2 ySin@xD

y

zzzzzzz

Landau, First Course in Scientific Computing 174

Copyright: Princeton Univ Press, RH Landau, 2005

Page 172: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[516]:= vec2 = 81, 2, 3<; H∗ Define another vector ∗LPrint@"vec2 = ", MatrixForm@vec2DDvec2 =

i

k

jjjjjjj123

y

zzzzzzz

In[518]:= vec3 = 84, 5, 6<;Print@"vec3 = ", MatrixForm@vec3DDvec3 =

i

kjjjjjj456

y

zzzzzz

In[520]:= dt = vec . vec2 H∗ Mathematica dot product ∗LOut[520]= x + 2 x2 y + 3 Sin@xD

As you may recall, the dot product of vectors A and B equals the product of the lengths of each vector times the cosine of the angle between them:

A . B = » A »» B » cos HθL = A B cos HθL

where A = |A| is the length (or magnitude, or norm, or modulus) of vector A. To check if this relation holds, we will need to determine the length or magnitude of a vector.The basic version of Mathematica does not appear to have a command for finding the magnitude of a vector (the Length command gives the dimension). However, it is easy enough to determine the length as the square root of the dot product of a vector with itself, or by summing its components:

Length = "###################################Vx 2 + Vy2 + Vz2

We determine the lengths L2 and L3 of the two vectors, and then check that the deduced value of cos(q) is less than 1:

In[521]:= L2 = Sqrt@vec2 . vec2D H∗ Length of vector vec2 ∗LOut[521]=

è!!!!!!14

In[522]:= L3 = Sqrt@vec3 . vec3D H∗ Length of vector vec3 ∗LOut[522]=

è!!!!!!77

In[523]:= costheta = Hvec2 . vec3LêL2 êL3 H∗ Cosine of angle btn vec2 & vec3 ∗L

Out[523]=16"#######2

11

7

In[524]:= N@%DH∗ Check that floating point value of »cos HθL» is <1 ∗L

Out[524]= 0.974632

Now we form the cross product of two vectors and check that it is perpendicular to the plane formed by the original two vectors (their dot products must vanish). Mathematica contains the Cross[v1, v2] command which returns the cross product of v1 and v2, but it only works for 3-D vectors. The cross product symbol, ä, can be inserted into the calculation by keying ``esc cross esc'', without spaces.

175 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 173: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[525]:= Clear@A, BDA = 8Ax, Ay, Az< H∗ Two general vectors ∗LB = 8Bx, By, Bz<

Out[526]= 8Ax, Ay, Az<Out[527]= 8Bx, By, Bz<

In[528]:= Cross@A, BD êê MatrixForm H∗ General form of cross product ∗LOut[528]//MatrixForm=

i

kjjjjjj

−Az By + Ay BzAz Bx − Ax Bz

−Ay Bx + Ax By

y

zzzzzz

In[529]:= vcross = vec2 vec3;H∗ Vector cross product of vec2 with vec3 ∗Lvcross êê MatrixForm

Out[530]//MatrixForm=

i

k

jjjjjjj−36

−3

y

zzzzzzz

In[531]:= vcross . vec2H∗ Should get 0 if vectors are orthogonal ∗L

Out[531]= 0

In[532]:= vcross . vec3H∗ Should get 0 if vectors are orthogonal ∗L

Out[532]= 0

We also know that the cross product has a length equal to the product of the lengths of vec2 and vec3 times the sine of the angle between them. So let us compute sin(q) and see if it agrees with the cos(q) we computed from the dot product:

In[533]:= sintheta = HSqrt@vcross . vcrossDLêL2 êL3Out[533]=

3"#######311

7

In[534]:= N@%D H∗ Check that »sin HθL» <1 ∗LOut[534]= 0.223814

In[535]:= costheta^2 + sintheta^2 H∗ Check if Cos@θD and Sin@θD agree ∗LOut[535]= 1

One last method of multiplication occurs if v1 is an n x 1 matrix (column vector) and v2 is an 1 x n matrix (row vector). The direct or outer product should be an n x n matrix:

Landau, First Course in Scientific Computing 176

Copyright: Princeton Univ Press, RH Landau, 2005

Page 174: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[536]:= Outer@Times, vec, vecD êê MatrixFormH∗ Outer product should produce a matrix ∗L

Out[536]//MatrixForm=

i

k

jjjjjjjj

x2 x3 y x Sin@xDx3 y x4 y2 x2 y Sin@xD

x Sin@xD x2 y Sin@xD Sin@xD2

y

zzzzzzzz

In[537]:= vec . vec êê MatrixFormH∗ Dot product should produce a number ∗L

Out[537]//MatrixForm=

x2 + x4 y2 + Sin@xD2

à 7.5.5 Vector Calculus*

Vector calculus may appear a little advanced for beginners, but you will have it here when needed. You first need to load the Calculus`VectorAnalysis` package (load the VectorAnalysis.m file from the Calculus package folder):

In[538]:= << Calculus`VectorAnalysis`

In[539]:= vec = 8x, y∗x^2, Sin@xD<;Print@"vec =", MatrixForm@vecDDvec =

i

k

jjjjjjjx

x2 ySin@xD

y

zzzzzzz

In[541]:= SetCoordinates@Cartesian@x, x, xDDH∗ Derivatives wrt the set coordinates ∗LCurl@vecD

Out[541]= Cartesian@x, x, xDOut[542]= 8−2 x y + Cos@xD, 1 − Cos@xD, −1 + 2 x y<

In[543]:= SetCoordinates@Cartesian@y, y, yDDCurl@vecD H∗ Take curl of vector vec ∗L

Out[543]= 8−x2 Cartesian@y, y, yD, 0, x2 Cartesian@y, y, yD<

In[544]:= f = 8x^2, y^3, z^4<;Print@"f =", MatrixForm@fDDf =

i

k

jjjjjjjj

x2

y3

z4

y

zzzzzzzz

In[546]:= SetCoordinates@Cartesian@x, y, zDDDiv@fD H∗ Take the divergence of vector f ∗L

Out[546]= Cartesian@x, y, zDOut[547]= 2 x + 3 y2 + 4 z3

177 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 175: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[548]:= SetCoordinates@Cartesian@x, y, xDDGrad@x^3D H∗ Take the gradient of x^3 ∗L

Out[548]= Cartesian@x, y, xDOut[549]= 83 x2, 0, 3 x2<

à 7.5.5 Eigenvalues and Eigenvectors*

The command EigenSystem[A] solves the eigenvalue problem for matrix A:

AX i = li Xi

That is, Eigensystem searches for a set of eigenvectors X with corresponding eigenvalues l, and returns a list l, X of the eigenvalues and eigenvectors of the square matrix A. Alternatively, you can find the eigenvalues and eigenvec-tors separately by using the Eigenvalues and Eigenvectors commands, which may be easier if you wish to store them separately. Note that if eigenvalues are repeated, they appear with their appropriate multiplicity:

In[550]:= A = 88−2, 2, −3<, 82, 1, −6<, 8−1, −2, 0<<;Print@"A =", MatrixForm@ADDH∗ Matrix A by rows ∗L

A =i

k

jjjjjjj−2 2 −32 1 −6

−1 −2 0

y

zzzzzzz

In[552]:= Eigensystem@ADH∗ Find eigenvalues and eigenvectors of A ∗L

Out[552]= 88−3, −3, 5<, 883, 0, 1<, 8−2, 1, 0<, 8−1, −2, 1<<<

In[553]:= lambda = Eigensystem@AD@@1DD;H∗ Place eigenvalues in vector λ by accessing the 1 st element ∗LPrint@"lambda = ", MatrixForm@lambdaDDlambda =

i

k

jjjjjjj−3−35

y

zzzzzzz

In[555]:= VecMatrix = Eigenvectors@AD;H∗ Place eigenvectors into matrix VecMatrix via Eigenvectors ∗LPrint@"VecMatrix = ", MatrixForm@VecMatrixDDVecMatrix =

i

k

jjjjjjj3 0 1

−2 1 0−1 −2 1

y

zzzzzzz

In[557]:= lambda@@1DD H∗ Extract three eigenvalues ∗Llambda@@2DDlambda@@3DD

Out[557]= −3

Out[558]= −3

Out[559]= 5

Landau, First Course in Scientific Computing 178

Copyright: Princeton Univ Press, RH Landau, 2005

Page 176: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[560]:= vec1 = VecMatrix@@1DD;H∗ Extract 1 st sublist ie. 1 st eigenvector ∗LPrint@"vec1 = ", MatrixForm@vec1DDvec1 =

i

k

jjjjjjj301

y

zzzzzzz

In[562]:= vec2 = VecMatrix@@2DD; H∗ Extract 2 nd eigenvector ∗LPrint@"vec2 = ", MatrixForm@vec2DDvec2 =

i

k

jjjjjjj−210

y

zzzzzzz

In[564]:= vec3 = VecMatrix@@3DD; H∗ Extract 3 rd eigenvector ∗LPrint@"vec3 = ", MatrixForm@vec3DDvec3 =

i

k

jjjjjjj−1−21

y

zzzzzzz

In[566]:= A . vec1 ==

lambda@@1DD ∗ vec1 H∗ Test 1 st eigenvalue with 1 st eigenvector ∗LOut[566]= True

This particular eigenvalue problem is a degenerate situation in which two of the eigenvalues are equal and so we do not expect the degenerate eigenvectors to be orthogonal. (Because the matrix A is not Hermitian we have no guarantee of orthogonality). We will check if they are orthogonal, and then use the Gram-Schmidt orthogonalization procedure to make them orthogonal. For that we need the LinearAlgebra`Orthogonalization` package:

In[567]:= << LinearAlgebra`Orthogonalization`

In[568]:= vec1 . vec2 H∗ Are 1 st 2 eigenvectors orthogonal? ∗LOut[568]= −6

In[569]:= NewVecs = GramSchmidt@8vec1, vec2, vec3<, Normalized → FalseDH∗ Produce orthogonal, unnormalized set; default = normalized ∗L

Out[569]= 983, 0, 1<, 9−15, 1,

35=, 9−

47, −

87,

127

==

In[570]:= NewVecs@@2DD êê MatrixForm H∗ Check out new second eigenvector ∗LOut[570]//MatrixForm=

i

k

jjjjjjjjj

− 15

135

y

zzzzzzzzz

Now we test if these new vectors are orthogonal:

In[571]:= NewVecs@@1DD . NewVecs@@2DDOut[571]= 0

179 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 177: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[572]:= NewVecs@@2DD . NewVecs@@3DDOut[572]= 0

In[573]:= NewVecs@@3DD . NewVecs@@1DDOut[573]= 0

These same matrix calculations can be undertaken with symbolic matrix elements , although this usually take more time as the matrices get bigger. The solution starts with the computation of the characteristic polynomial and the solution for its roots (the eigenvalues li ). Next, the eigenvectors are found for each eigenvalue. The solution routine finds symbolic solutions only for algebraic numbers or algebraic functions. Accordingly, the input matrix A must contain rationals, complex numbers, polynomials, algebraic numbers, or algebraic functions. As we see below, even with matrices, we sometimes have to coerce Mathematica into distributing the multiplication and then expanding the products so that the answer looks the way we want it to:

In[574]:= A = 88x, −3<, 83 x, 4 x<<; H∗ Algebraic form form matrix A ∗LA êê MatrixForm

Out[574]//MatrixForm=

J x −33 x 4 x

N

In[575]:= lambda = Eigenvalues@AD H∗ Store eigenvalues in list HvectorL ∗L

Out[575]= 9 12I−3 è!!!!!!!!!!!!!!−4 + x è!!!x + 5 xM, 1

2I3 è!!!!!!!!!!!!!!−4 + x è!!!x + 5 xM=

In[576]:= Xs = Eigenvectors@AD H∗ Store eigenvectors ∗L

Out[576]= 99−è!!!!!!!!!!!!!!

−4 + x +è!!!x

2 è!!!x, 1=, 9−

−è!!!!!!!!!!!!!!

−4 + x +è!!!x

2 è!!!x, 1==

In[577]:= X1 = Xs@@1DD H∗ Extract first eigenvector ∗L

Out[577]= 9−è!!!!!!!!!!!!!!−4 + x + è!!!x

2 è!!!x, 1=

In[578]:= X2 = Xs@@2DD H∗ Extract second eigenvector ∗L

Out[578]= 9−−è!!!!!!!!!!!!!!−4 + x + è!!!x

2 è!!!x, 1=

In[579]:= A . X1 lambda@@1DD ∗ X1 H∗ Test first eigenvalue ∗L

Out[579]= 9−3 −12Iè!!!!!!!!!!!!!!−4 + x +

è!!!x M è!!!x , −32Iè!!!!!!!!!!!!!!−4 + x +

è!!!x M è!!!x + 4 x= ==

9−Iè!!!!!!!!!!!!!!−4 + x + è!!!x M I−3 è!!!!!!!!!!!!!!−4 + x è!!!x + 5 xM

4 è!!!x,

12I−3 è!!!!!!!!!!!!!!−4 + x è!!!x + 5 xM=

In[580]:= Map@Expand, %D H∗ Expand each element to compare ∗LOut[580]= True

In[581]:= lambda@@2DD H∗ The second eigenvalue ∗L

Out[581]=12I3 è!!!!!!!!!!!!!!−4 + x è!!!x + 5 xM

Landau, First Course in Scientific Computing 180

Copyright: Princeton Univ Press, RH Landau, 2005

Page 178: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[582]:= X2 H∗ The second eigenvector ∗L

Out[582]= 9−−è!!!!!!!!!!!!!!−4 + x + è!!!x

2 è!!!x, 1=

In[583]:= H∗ Test the second eigenvector here ∗L

As is true for other Mathematica calculations, if any of the numbers in the matrix A contain a decimal point, then Mathemat-ica will interpret this as a request for a floating-point calculation. For matrix calculations, this means that the eigenvectors and eigenvalues will be computed numerically and that all elements should be of numeric type. Alternatively, you could use the Eigenvalues[N[m],k] command, which finds numerical eigenvalues, starting with k-digit precision. There are similar commands for finding eigenvectors and the eigensystem. Although, if the calculation is really big, then we recommend a compiled language with a scientific matrix library (we do that in Chap. 18). Here is an example of using a numerical form of the previous matrix:

In[584]:= A = [email protected]∗iL^j, 8i, 10<, 8j, 10<D;A êê MatrixForm

Out[585]//MatrixForm=

i

k

jjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjj

0.1 0.01 0.001 0.0001 0.00001 1.×10−6 1.×10−7 1.×10−8 1.×10−9

0.2 0.04 0.008 0.0016 0.00032 0.000064 0.0000128 2.56×10−6 5.12×10−7

0.3 0.09 0.027 0.0081 0.00243 0.000729 0.0002187 0.00006561 0.0000196830.4 0.16 0.064 0.0256 0.01024 0.004096 0.0016384 0.00065536 0.0002621440.5 0.25 0.125 0.0625 0.03125 0.015625 0.0078125 0.00390625 0.001953130.6 0.36 0.216 0.1296 0.07776 0.046656 0.0279936 0.0167962 0.01007770.7 0.49 0.343 0.2401 0.16807 0.117649 0.0823543 0.057648 0.04035360.8 0.64 0.512 0.4096 0.32768 0.262144 0.209715 0.167772 0.1342180.9 0.81 0.729 0.6561 0.59049 0.531441 0.478297 0.430467 0.387421. 1. 1. 1. 1. 1. 1. 1. 1.

In[586]:= Eigenvalues@ADOut[586]= 81.53717, 0.17076, 0.128814, 0.0505783, 0.0164759,

0.00365218, 0.000550434, 0.000053397, 2.99371×10−6, 7.35387×10−8<

181 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 179: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[587]:= Eigenvectors@N@ADDOut[587]= 88−6.73733×10−8, −1.75676×10−6, −0.0000257834, −0.00024355,

−0.00161298, −0.0081143, −0.0330176, −0.113801, −0.343594, −0.931576<,8−0.000153185, −0.000669381, −0.00269892, −0.0101181, −0.0326379,

−0.0870385, −0.185614, −0.286617, −0.158728, 0.921657<,8−0.00101914, −0.00254599, −0.00397273, −0.00172563, 0.0150605,0.0677544, 0.177703, 0.311641, 0.224169, −0.903441<,8−0.000522552, 0.00141551, 0.008941, 0.0236725, 0.0363778,0.01275, −0.107072, −0.341779, −0.422873, 0.831127<,80.000492131, −0.00365398, −0.00604235, 0.00865176, 0.0518304,0.0943556, 0.0279585, −0.280181, −0.612238, 0.730868<,8−0.000408656, 0.00493381, −0.00705272, −0.0295639, −0.00777959,0.103905, 0.194888, −0.0777371, −0.770741, 0.591717<,80.000300539, −0.00490637, 0.0202258, −0.00237627, −0.0804471,

−0.0348035, 0.245981, 0.251029, −0.826046, 0.431281<,80.000187533, −0.00379675, 0.0249453, −0.0579395, −0.0113818,0.194692, −0.0295252, −0.581564, 0.737686, −0.273318<,80.0000931055, −0.0022307, 0.0197437, −0.0826161, 0.15855,

−0.0381997, −0.394027, 0.719335, −0.522766, 0.142118<,80.0000319488, −0.000880579, 0.00971147, −0.0573667, 0.202749,

−0.44906, 0.628147, −0.538452, 0.257989, −0.0528698<<

In[588]:= H∗ Check the precision of some of these solutions via substitution ∗L

à 7.5.7 Solution of Linear Equations*

A set of simultaneous linear equations can be written in the matrix form

A X = b

If we have n equations for n unknowns, then A will be a square matrix of dimension n, b a vector of constants with length n, and X a vector containing the n unknowns we wish to solve for:

X =

ikjjjjjjjjjjjjjj

x1

x2

x3

xn

yzzzzzzzzzzzzzz

The Mathematica command LinearSolve[A,b] finds the vector X that solves this equation:

In[589]:= Clear@A, bDA = 884, −2, 1<, 83, 6, −4<, 82, 1, 8<<; H∗ Define matrix A ∗LPrint@"A = ", MatrixForm@ADDA =

i

k

jjjjjjj4 −2 13 6 −42 1 8

y

zzzzzzz

Landau, First Course in Scientific Computing 182

Copyright: Princeton Univ Press, RH Landau, 2005

Page 180: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[591]:= b = 812, −25, 32<; H∗ Define vector b ∗LPrint@"b = ", MatrixForm@bDDb =

i

k

jjjjjjj12

−2532

y

zzzzzzz

In[592]:= X = LinearSolve@A, bD;H∗ Solve A X = b for unknown vector X ∗LPrint@ "X = ", MatrixForm@XDDX =

i

k

jjjjjjj1

−24

y

zzzzzzz

In[594]:= H∗ Check your answer here ∗L

If you are solving a problem in which you have n equations in m unknowns, then A will have n rows and m columns. For a solution to exist, this then requires b to be a vector of dimension n and X a vector of dimension m. If A X = b has no solution, or if LinearSolve cannot find one, then a blue error message is returned. If A X = b has multiple solutions, then LinearSolve will return one of the possible solutions.

In[595]:= A = 881, 2<, 81, 3<, 81, 2<<; H∗ Matrix A is 3 x 2 ∗LPrint@"A = ", A êê MatrixFormDA =

i

k

jjjjjjj1 21 31 2

y

zzzzzzz

In[596]:= b = 81, −2, 1< ; H∗ Vector b is dimension 3 ∗LPrint@"b = ", b êê MatrixFormDb =

i

k

jjjjjjj1

−21

y

zzzzzzz

In[598]:= X = LinearSolve@A, bD;Print@ "X = ", X êê MatrixFormDX = J 7

−3 N

In[600]:= H∗ Check your answer here ∗L

In yet another variation, LinearSolve[A, B] finds the matrix X which solves the matrix equation A X = B, in the sense that each column of X satisfies

A colHX , iL = colHB, iL

183 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 181: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[601]:= A = 885, 7<, 810, 14<<;Print@"A = ", MatrixForm@ADDB = 883, 0<, 86, 0<<;Print@"B = ", MatrixForm@BDDA = J 5 7

10 14 N

B = J 3 06 0

N

In[605]:= X = LinearSolve@A, BD;Print@"X = ", MatrixForm@XDDX =

ikjjj

35 00 0

yzzz

7.6 Solution: Rotating Rigid Body

We now apply the Mathematica's linear algebra tools to the barbell problem of Fig. 7.1. Seeing that the barbell is rotating, means that the geometry of this figure is correct only for one instant of time, or for all times in a reference frame rotating with the barbell. We will use that rotating frame and then transform to a stationary frame later.

0 0.5 1 1.5 2x -0.200.2y

11.251.5

1.752

z

-0.200.2y

11.251.5

1.752

z

Fig. 7.6 The angular velocity vector w on the left, and the angular momentum vector L on the right.

We are told that the angular velocity vector of the barbell w lies along the z axis and so the barbell is rotating about the z axis. Clearly, then, is a 3-D problem so we define w as a 3-D vector W with only a z component:

In[607]:= Omega =.Clear@Omega, LD

Landau, First Course in Scientific Computing 184

Copyright: Princeton Univ Press, RH Landau, 2005

Page 182: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[609]:= Omega = 80, 0, ω<;Print@"Ω =", MatrixForm@OmegaDDΩ =

i

k

jjjjjjj00ω

y

zzzzzzz

We want to use Mathematica to evaluate the angular momentum via (7.15), which for a barbell with two masses has the simple form:

L = Hr1 ä p1 + r2 ä p2L = m1 r1 ä Hw ä r1L + m 2 r2 äHw ä r2LWe first enter the vectors using the trigonometry shown in Fig. 7.1:

In[611]:= r1 = 8−a Sin@θD, 0, a Cos@θD<;Print@"r1 = ", MatrixForm@r1DDr1 =

i

k

jjjjjjj−0.015 Sin@θD

00.015 Cos@θD

y

zzzzzzz

In[613]:= r2 = 8a Sin@θD, 0, −a Cos@θD<;Print@"r2 = ", MatrixForm@r2DDr2 =

i

k

jjjjjjj0.015 Sin@θD

0−0.015 Cos@θD

y

zzzzzzz

This makes sense since we know that r1 = -r2 from the figure. Rather than have some very long expressions, we proceed in steps and compute the momentum of each particle next using the cross product:

In[615]:= p1 = m1 ∗ Cross@Omega, r1D;Print@"p1 = " , MatrixForm@p1DDp1 =

i

k

jjjjjjj0

−0.015 m1 ω Sin@θD0

y

zzzzzzz

In[617]:= p2 = m2 ∗ Cross@Omega, r2D;Print@"p2 = ", MatrixForm@p2DDp2 =

i

k

jjjjjjj0

0.015 m2 ω Sin@θD0

y

zzzzzzz

As expected, m1 is moving into the paper (negative y velocity), and m2 is moving out of the paper. We now compute the angular momentum arising from each mass and add the results:

In[619]:= L1 = Cross@r1, p1D;Print@"L1 = ", MatrixForm@L1DDL1 =

i

k

jjjjjjjj

0.000225 m1 ω Cos@θD Sin@θD0

0.000225 m1 ω Sin@θD2

y

zzzzzzzz

185 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 183: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[621]:= L2 = Cross@r2, p2D;Print@"L2 = ", MatrixForm@L2DDL2 =

i

k

jjjjjjjj

0.000225 m2 ω Cos@θD Sin@θD0

0.000225 m2 ω Sin@θD2

y

zzzzzzzz

In[623]:= L = L1 + L2;Print@"L = ", MatrixForm@LDDL =

i

k

jjjjjjjj

0.000225 m1 ω Cos@θD Sin@θD + 0.000225 m2 ω Cos@θD Sin@θD0

0.000225 m1 ω Sin@θD2 + 0.000225 m2 ω Sin@θD2

y

zzzzzzzz

In[625]:= Print@"L = ", FullSimplify@LD êê MatrixFormDH∗ Simplified L with nice output ∗L

L =i

k

jjjjjjjj

H0.000225 m1 + 0.000225 m2L ω Cos@θD Sin@θD0

H0.000225 m1 + 0.000225 m2L ω Sin@θD2

y

zzzzzzzz

We see that even though the angular velocity is always along the z axis, the angular momentum has an x component, in addition to a z component. In addition, since we are viewing the system in a rotating frame, an observer in a fixed frame would see the x component of L rotate (precess) continuously about a fixed z component.

To visualize this solution, we need to assign numerical values to the masses, lengths, angular velocity, and angles:

In[626]:= m1 = 1;Print@"m1 = ", m1Dm2 = 1;Print@"m2 = ", m2Da = 1;Print@"a = ", aDω = 2;Print@"ω = ", ωDθ = Piê4;Print@"θ = ", θDm1 = 1

m2 = 1

a = 1

ω = 2

θ =π4

In[636]:= L êê MatrixForm

Out[636]//MatrixForm=

i

k

jjjjjjj0.00045

00.00045

y

zzzzzzz

Landau, First Course in Scientific Computing 186

Copyright: Princeton Univ Press, RH Landau, 2005

Page 184: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[637]:= Omega êê MatrixForm

Out[637]//MatrixForm=

i

k

jjjjjjj002

y

zzzzzzz

We now have variables to plot that are numbers and not symbols.

7.6.1 Visualization of Vectors with Arrow3D

Often, it is valuable to view a vector as an arrow in space. There is a package written for Mathematica containing a neat graphics object, Arrow3D, that does just that. Here we use it [Note: The Arrow3D.m file must be placed in the Graph-ics folder under the StandardPackages folder, and can be found on the disk that came with your text book. You can put it in another directory if you wish, but must use the uncommented version of the Get command below accordingly.]:

In[638]:= << Graphics`Arrow3D`

In[639]:= H∗ Get@"Arrow3D.m",Path→8"êusrêlocalêmathematicaêAddOnsêStandardPackagesêGraphicsê" <D ∗L

In[640]:= Omega2 = Arrow3D@80, 0, 0<, OmegaDIn[641]:= Show@Graphics3D@Omega2D, Axes → TrueD; H∗ Plot Omega as 3−D arrow ∗L

-0.100.1

-0.2-0.100.10.2

1

1.25

1.5

1.75

2-0.2-0.100.10.2

In[642]:= L2 = Arrow3D@80, 0, 0<, LD

187 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 185: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[643]:= Show@Graphics3D@L2D, Axes → TrueD; H∗ Plot L as 3−D arrow ∗L

0.00020.00030.0004-0.0000500.00005

0.0002

0.0003

0.0004

-0.0000500.00005

0.0002

0.0003

0.0004

So now we have visualizations of both L and W. We can place them on the same plot by putting two Graphics3D objects into our Show command:

In[644]:= Show@Graphics3D@Omega2, PlotLabel −> "Omega and L"D,Graphics3D@L2D, Axes → TrueD;

Notice that when we created the arrows we did not have any options for the color and shape of the arrows. While there are no options for the Arrow3D command except the starting and ending position, the Graphics3D and Show commands permit the usual ones possible for 2-D and 3-D plots (see too Chapter 4). So it is with the Show command that we placed labels and titles on the plot.

Now we would like to convey the notion that the angular momentum vector L is rotating about the W vector (which is fixed along the z axis). We do that by creating vectors with the components that L would acquire as it rotates without changing magnitude, and then displaying them all in one plot along with W.

In[645]:= L3 = Arrow3D@80, 0, 0<, 80, 2, 2<D;L4 = Arrow3D@80, 0, 0<, 8−2, 0, 2<D;L5 = Arrow3D@80, 0, 0<, 80, −2, 2<D;

Landau, First Course in Scientific Computing 188

Copyright: Princeton Univ Press, RH Landau, 2005

Page 186: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[648]:= Show@Graphics3D@Omega2, AxesLabel → 8"x", "y", "z"<,PlotLabel −> "Omega and L"D, Graphics3D@L2D,Graphics3D@L3D, Graphics3D@L4D, Graphics3D@L5D, Axes → TrueD;H∗ Display all 5 arrows on one graph ∗L

Omega and L

-2-1.5-1-0.50x

-2

-1

01

2

y

00.51

1.52

z

-2-1.5-1-0.50x

-2

-1

01

2

y

7.6.2 Moment of Inertia for Barbell

ensor of barbell11.52 2.5 3Row

1 1.5 2 2.5 3Column

00.511.52

00.511.52

We have just evaluated the angular momentum of our barbell by using the elementary definition of angular momentum for each individual mass, and then adding up the two angular momenta. Even though it is possible to follow this approach for any rigid object, it is easier to get the angular momentum by just multiplying the angular velocity w by the inertia tensor:

L = 8I< . ω

However, to do that we must first evaluate the inertia tensor for the object under study. We start with the basic definition and apply it to the barbell

Ii, j = „a

maikjjjjjdij

ikjjjjj‚kxa,k

2yzzzzz - x a,i xa, j

yzzzzzwhere the sum over a is over the two masses, and i, j, and k take on the values x, y, and z. The x's in this equation describe the location of the two masses in Fig. 7.1 in terms of Cartesian coordinates (what we called r1 and r2 before):

In[649]:= Clear@θ, ω, Omega, a, m1, m2DOmega = 80, 0, ω<;Print@"Ω = ", MatrixForm@OmegaDDΩ =

i

k

jjjjjjj00ω

y

zzzzzzz

189 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 187: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[652]:= x1 = 8−a Sin@θD, 0, a Cos@θD<;Print@"x1 = ", MatrixForm@x1DDx1 =

i

k

jjjjjjj−a Sin@θD

0a Cos@θD

y

zzzzzzz

In[654]:= x2 = 8a Sin@θD, 0, −a Cos@θD<;Print@"x2 = ", MatrixForm@x2DDx2 =

i

k

jjjjjjja Sin@θD

0−a Cos@θD

y

zzzzzzz

The angular velocity vector and the positions of the masses are now known. In order to apply the equation above for the moment of inertia, we see that x has subscripts indicating both the mass it corresponds to, and its component along the x and y axis. Accordingly, we form a matrix x that has two indices:

In[656]:= x = 8x1, x2<;Print@"x = ", MatrixForm@xDDx = J −a Sin@θD 0 a Cos@θD

a Sin@θD 0 −a Cos@θD N

In[658]:= x@@1, 3DD H∗ Check that the right answer comes up ∗LOut[658]= a Cos@θD

In[659]:= x1@@3DD H∗ Check that these agree ∗LOut[659]= a Cos@θD

In[660]:= m = 8m1, m2<;Print@"m = ", MatrixForm@mDDm = J m1

m2N

To keep this treatment simple, we will explicitly write out the a index over particles and have Mathematica sum over i and j as subscripts. We start by determining the contribution of mass 1 to the moment of inertia:

In[662]:= B = Table@i^j, 8i, 3<, 8j, 3<D; H∗ Test case from before ∗LPrint@"B = ", MatrixForm@BDDB =

i

k

jjjjjjj1 1 12 4 83 9 27

y

zzzzzzz

In[663]:= δ = IdentityMatrix@3D;Print@"δ = ", MatrixForm@δDDδ =

i

k

jjjjjjj1 0 00 1 00 0 1

y

zzzzzzz

In[665]:= Print@"Delta@1,2D = ", δ@@1, 2DDDDelta@1,2D = 0

Landau, First Course in Scientific Computing 190

Copyright: Princeton Univ Press, RH Landau, 2005

Page 188: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[666]:= Print@"Delta@2,2D = ", δ@@2, 2DDDDelta@2,2D = 1

In[667]:= Inertia = Table@ m1∗Hδ@@i, jDD∗Sum@Hx1@@kDDL^2, 8k, 1, 3<D − x1@@iDD∗x1@@jDDL,8i, 3<, 8j, 3<D;Print@"Inertia = ", MatrixForm@InertiaDH∗ Same matrix formed a different way ∗L

In[668]:= Inertia =

Table@ m1∗Hδ@@i, jDD∗Sum@Hx@@1, kDDL^2, 8k, 1, 3<D − x@@1, iDD∗x@@1, jDDL,8i, 3<, 8j, 3<D;Print@"Inertia = ", Inertia êê MatrixFormDInertia =

i

k

jjjjjjjjj

a2 m1 Cos@θD2 0 a2 m1 Cos@θD Sin@θD0 m1 Ha2 Cos@θD2 + a2 Sin@θD2L 0

a2 m1 Cos@θD Sin@θD 0 a2 m1 Sin@θD2

y

zzzzzzzzz

In[670]:= Inertia = Table@Sum@m@@ADD∗Hδ@@i, jDD∗Sum@x@@A, kDD^2, 8k, 1, 3<D − x@@A, iDD∗x@@A, jDDL,8A, 1, 2<D, 8i, 3<, 8j, 3<D;

Print@"Inertia = ", Inertia êê MatrixFormDInertia =

i

k

jjjjjjjjj

a2 m1 Cos@θD2 + a2 m2 Cos@θD2 0

0 m1 Ha2 Cos@θD2 + a2 Sin@θD2L + m2

a2 m1 Cos@θD Sin@θD + a2 m2 Cos@θD Sin@θD 0

To simplify this, let us assign the numerical values we had before for the masses, lengths, angular velocity, and angles:

In[672]:= m1 = 1;Print@"m1 = ", m1Dm2 = 1;Print@"m2 = ", m2Da = 1;Print@"a = ", aDω = 2;Print@"ω = ", ωDθ = Piê4;Print@"θ = ", θDm1 = 1

m2 = 1

a = 1

ω = 2

θ =π4

191 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 189: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[682]:= Inertia êê MatrixForm

Out[682]//MatrixForm=

i

k

jjjjjjj1 0 10 2 01 0 1

y

zzzzzzz

In[683]:= Inertia . Omega êê MatrixForm

Out[683]//MatrixForm=

i

k

jjjjjjj202

y

zzzzzzz

In[684]:= ListPlot3D@Inertia, PlotLabel → "Inertia tensor ofbarbell ", AxesLabel → 8"Row", "Column", ""<Dor of barbell

11.5

22.5

3Row

1

1.522.53

Colum0

0.51

1.52

11.5

22.5

3Row

Landau, First Course in Scientific Computing 192

Copyright: Princeton Univ Press, RH Landau, 2005

Page 190: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[685]:= Inertia êê MatrixForm H∗ Let us see if Inertia is still there ∗LOut[685]//MatrixForm=

i

k

jjjjjjj1 0 10 2 01 0 1

y

zzzzzzz

7.7 Exploration: Principal Axes of Rotation*

We have seen that when the inertia tensor contains off diagonal elements (products of inertia), the angular momentum and angular velocity of a spinning body are not parallel to each other. It would clearly be simpler if we did not have those off-diagonal elements with which to deal. In general, what is ``simpler'' in life depends upon one's view of the world, and the inertia tensor is no different. If we rotate the coordinate system that we use to calculate the moment of inertia (still keeping it fixed to the body at the center of mass), then it is usually possible to find an orientation for which the inertia tensor is diagonal. In terms of individual elements, a diagonal matrix is expressed as:

Ii, j = Ii dij

while in terms of the matrix representation this is, 8I< =ikjjjjjjjj I1 0 0

0 I2 00 0 I3

yzzzzzzzzwhere we are using (1,2,3) to label the x, y, and z axes in this new system. The set of axes in which the inertia tensor becomes diagonal is called the principal axes of inertia.

Finding the principal axes of inertia is actually simpler than you may think (as well as letting us show off some of the other features of Mathematica's linear algebra package). The whole idea is that the angular momentum, as a vector in space (an arrow), does not change when we choose to view it from different coordinate systems. Accordingly, we take the expres-sions for L in the two systems and set them equal. This gives us the equations that Mathematica will solve for us.

We assume that in the principal axes system, the body is rotating along one of the principal axes, that is, along the 1, 2, or 3 directions. Then the angular momentum L and the angular velocity w will be parallel,

L = I w

where I is the moment of inertia along the principal axis of rotation (which we cannot yet calculate since we do not know where those axes point). Yet L is still the same vector that we expressed previously in (Eq. 2) in terms of the products and moments of inertia. By setting the two expressions equal we obtain three, simultaneous linear equations for the unknowns I and w:

I wx = Lx = Ixx wx + Ixy wy + Ixz wz

I wy = Ly = Iyx wx + Iyy wy + Iyz wz

I wz = Lz = Izx wx + Izy wy + Izz wz

We can write these three equations in the matrix form

193 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 191: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[686]:= Imatrix = 88"Ixx" − "I", "Ixy", "Ixz"<,8"Iyx", "Iyy" − "I", "Iyz"<, 8"Izx", "Izy", "Izz" − "I"<<;Imatrix êê MatrixForm

General::spell1 : Possible spelling error: newsymbol name "Imatrix" is similar to existing symbol "matrix".

Out[687]//MatrixForm=

i

k

jjjjjjj−I + Ixx Ixy IxzIyx −I + Iyy IyzIzx Izy −I + Izz

y

zzzzzzz

[Note: The quotes around the I's of the matrix elements in the above command are used to restrain Mathematica from using I as the imaginary number  (its ususal meaning). ] The trivial solution is w = 0. For a nontrivial solution to exist, the matrix on the LHS of this equation must have no inverse, and this requires that the determinant of the matrix vanish:

In[688]:= Det@ImatrixDOut[688]= −I3 + I2 Ixx + I Ixy Iyx + I2 Iyy − I Ixx Iyy + I Ixz Izx − Ixz Iyy Izx + Ixy Iyz Izx + Ixz Iyx Izy +

I Iyz Izy − Ixx Iyz Izy + I2 Izz − I Ixx Izz − Ixy Iyx Izz − I Iyy Izz + Ixx Iyy Izz

When the determinant is expanded (something we dare you to try), we are left with a cubic equation in I. The three solutions of this cubic are the three principal moments of inertia, Ix , Iy , and Iz . Once these I's are known, they can be substituted back into the matrix equation to determine the angular momenta:

Lx = Ix ωxLy = Iy ωyL z = Iz ωz

We enter the inertia tensor for a cube as part of the Problem:

In[689]:= Clear@Inertia, Omega, ω, LDInertia = 882ê3, −1ê4, −1ê4<, 8−1ê4, 2ê3, −1ê4<, 8−1ê4, −1ê4, 2ê3<<;Inertia êê MatrixForm

Out[691]//MatrixForm=

i

k

jjjjjjjjjj

23 − 1

4 − 14

− 14

23 − 1

4

− 14 − 1

423

y

zzzzzzzzzz

Now we form a diagonal matrix with the value Iprin along the diagonal:

In[692]:= Idiag = Iprin∗IdentityMatrix@3D;Idiag êê MatrixForm

Out[693]//MatrixForm=

i

k

jjjjjjjIprin 0 00 Iprin 00 0 Iprin

y

zzzzzzz

Next we form the matrix whose determinant must vanish. We build the matrix up explicitly from its elements:

Landau, First Course in Scientific Computing 194

Copyright: Princeton Univ Press, RH Landau, 2005

Page 192: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[694]:= Inertia − Idiag êê MatrixForm

Out[694]//MatrixForm=

i

k

jjjjjjjjjj

23 − Iprin − 1

4 − 14

− 14

23 − Iprin − 1

4

− 14 − 1

423 − Iprin

y

zzzzzzzzzz

Now we calculate the determinant of this matrix and ask Mathematica to solve for the value of Iprin for which the determi-nant vanishes:

In[695]:= Det@Inertia − IdiagDOut[695]=

121864

−55 Iprin

48+ 2 Iprin2 − Iprin3

In[696]:= Solve@Det@Inertia − IdiagD 0, IprinD H∗ Solve equation for Iprin ∗L

Out[696]= 99Iprin →16=, 9Iprin →

1112

=, 9Iprin →1112

==

We should see three principal moments, two of which are equal (a consequence of symmetry). The inertia tensor in the principal axes frame is thus the diagonal matrix:

In[697]:= Idiag = 881ê6, 0, 0<, 80, 11ê12, 0<, 80, 0, 11ê12<<;Idiag êê MatrixForm

Out[698]//MatrixForm=

i

k

jjjjjjjjjj

16 0 0

0 1112 0

0 0 1112

y

zzzzzzzzzz

Although we cannot go into the details here, the indicial equation that we have deduced above is the same one that arises in the eigenvalue problem. For our problem, the eigenvalues are principal moments of inertia, and the eigenvectors are three values for the angular velocity vector w. Since each eigenvector is associated with one eigenvalue, the principal moment of inertia, the eigenvectors correspond to values of w for which L and w are parallel. Accordingly, the directions of the eigenvectors are the directions of the principal axes in space. Let us see for our cube problem:

In[699]:= Clear@Omega, BDInertia êê MatrixForm

Out[700]//MatrixForm=

i

k

jjjjjjjjjj

23 − 1

4 − 14

− 14

23 − 1

4

− 14 − 1

423

y

zzzzzzzzzz

195 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 193: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[701]:= Is = Eigenvalues@InertiaD;Is êê MatrixFormOmegas = Eigenvectors@InertiaD;Omegas êê MatrixForm

Out[702]//MatrixForm=

i

k

jjjjjjjjjj

1611121112

y

zzzzzzzzzz

Out[704]//MatrixForm=

i

k

jjjjjjj1 1 1

−1 0 1−1 1 0

y

zzzzzzz

Ignoring the warning about spelling errors, we see that Mathematica returns a column vector with the same three values as the eigenvalues we found above. The Eigenvectors command produces the matrix containing the corresponding three eigenvectors as its rows. Here we separate the eigenvalues and vectors:

In[705]:= Is1 = Is@@1DDomega1 = Omegas@@1DD; H∗ Extract first eigenvector ∗Lomega1 êê MatrixForm

Out[705]=16

Out[706]//MatrixForm=

i

k

jjjjjjj111

y

zzzzzzz

In[707]:= Is2 = Is@@2DDomega2 = Omegas@@2DD; H∗ Extract second eigenvector ∗Lomega2 êê MatrixForm

Out[707]=1112

Out[708]//MatrixForm=

i

k

jjjjjjj−101

y

zzzzzzz

In[709]:= Is3 = Is@@3DDomega3 = Omegas@@3DD; H∗ Extract third eigenvector ∗Lomega3 êê MatrixForm

Out[709]=1112

Out[710]//MatrixForm=

i

k

jjjjjjj−110

y

zzzzzzz

We see that the third eigenvalue corresponds to rotations along the diagonal of the cube, while the first two are perpendicu-lar to the diagonal. To actually visualize these eigenvectors, let us represent them as arrows with Mathematica's Arrow3D command:

Landau, First Course in Scientific Computing 196

Copyright: Princeton Univ Press, RH Landau, 2005

Page 194: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[711]:= Show@Graphics3D@Arrow3D@80, 0, 0<, omega3D, PlotLabel −> "Omega3"D,Axes → True, AxesLabel → 8"x", "y", "z"<D;

Omega3

-1-0.8

-0.6-0.4x 0.4

0.60.81

y-0.1

00.1z

-1-0.8

-0.6-0.4x

This shows us that, indeed, w is along the axis of the cube. As before, we now represent three omega's as graphics objects and display them together:

197 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 195: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[712]:= o1 = Arrow3D@80, 0, 0<, omega1D;o2 = Arrow3D@80, 0, 0<, omega2D;o3 = Arrow3D@80, 0, 0<, omega3D;Show@Graphics3D@o1D, Graphics3D@o2D,Graphics3D@o3D, Axes → True, AxesLabel → 8"x", "y", "z"<D;

-1-0.5

00.5

1x 0

0.250.50.751

y

00.250.5

0.751

z

-1-0.5

00.5

1x

7.8 Key Words and Concepts

angular momentum angular velocity column & rows determinant diagonalization* dot product eigenvalues* eigenvectors* inertia tensor linear algebra linear equations inverse matrix matrix arithmetic moment of inertia polar coordinates rigid body rotation vector scalar multiplication vector components vector magnitude & phase

1. Is a vector also a matrix?

2. Is a row vector a matrix?

3. Is a column vector also a matrix?

4. What is the difference between a row and column vector in Mathematica?

5. Why is the study of matrices and vectors also called linear algebra?

6. How many coordinates are needed to locate a point in space?

7. What meaning is there to a vector having more than three components?

8. Can you add, subtract, and multiply matrices?

9. Can you divide matrices?

10. How are eigenvalues and eigenvectors related?

11. What is the relation between simultaneous equations and matrix equations?

Landau, First Course in Scientific Computing 198

Copyright: Princeton Univ Press, RH Landau, 2005

Page 196: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

7.9 Supplementary Exercises

1. Use Mathematica's linear algebra commands to find the solution of the simultaneous equations

3 x + 2 y + z = 112 x + 3 y + z = 13x + y + 4 x = 12

2. Find the inverse of the matrix

A =ikjjjjjjjj 4 -2 1

3 6 -42 1 8

yzzzzzzzz3. Verify that the inverse 1ÅÅÅÅÅA found in question 2 works in both directions, that is, that

A1ÅÅÅÅÅÅÅA

=1

ÅÅÅÅÅÅÅA

A = 1

4. Use the same matrixAas in problem 2,find and verify the solution of

A X = B

B =ikjjjjjjjj 12

-2532

yzzzzzzzz5. In quantum mechanics, the electron spin is described by three Pauli matrices

σ1 = J 0 11 0

N, σ2 = J 0 −

0N, σ3 = J 1 0

0 1N

a) Enter these three matrices into Mathematica.

b) Use Mathematica to show thatσ1 σ1 = σ2 σ2 = σ3 σ3 = 1

c) Use Mathematica to show thatσ1 σ2 = σ3, σ2 σ3 = σ1, σ3 σ1 = σ2

d) Use Mathematica to show that for (i, j, k) in cyclic order [that is (1,2,3), (2,3,1), (3,1,2)],σi σj − σj σi = 2 σk

e) Use Mathematica to show that the trace of each of these matrices vanishes, that is, thatTrace σi = 0

6. (You do not have to understand the physics here to do this problem.) Consider a hydrogen atom in a magnetic field B that points in the y direction. If the electron within the atom is described by the Pauli matrices of problem 5, then the Hamiltonian for this system is a Hermitian matrix of the form:

199 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 197: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

H = J h − BB h

N

where  is the imaginary number and h is the energy of the atom when there is no magnetic field.

a) The energy of this system is the eigenvalues of this Hamiltonian matrix. Find an analytic expression for the two possi-ble energies for an electron in a magnetic field, that is, find the two eigenvalues of this matrix.

b) Determine the corresponding eigenvectors and show that they are complex yet orthogonal to each other. (Orthogonality is a consequence of the matrix being Hermitian).

7. Determine the relation between the angular momentum and the angular velocities of a uniform plate and cube. Compare that relation to the one we worked out for a plate and cube composed of discrete masses.

8. Consider the matrix

A = J α β

−β αN

Solve for the complex eigenvalues and eigenvectors of this matrix. Hint: Your eigenvalues should be l = a -Âb, l = a + Âb.

9. In quantum mechanics, a spin 1 particle is described with the three, 3x3 matrices:

M1 =

i

k

jjjjjjj0 1 01 0 00 1 0

y

zzzzzzzè!!!2

, M 2 =

i

k

jjjjjjj0 − 0

0 −

0 0

y

zzzzzzzè!!!2

, M3 =i

k

jjjjjjj1 0 00 0 00 0 −1

y

zzzzzzz

Show that

a) [Mx , My ] = Â Mz

as well as for cyclic permutation of the indices, that is, for the index orders yzx, and zxy.

b) Mx2 + My

2 + Mz2 = 2 1

where 1 is the 3-D identity matrix.

Landau, First Course in Scientific Computing 200

Copyright: Princeton Univ Press, RH Landau, 2005

Page 198: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

Chapter 6: Integration; Power & Energy Usage (14 too)

6.1 Problem: Power and Energy Usage

The use of electrical power is characterized by variations of different sorts. There are fluctuations related to the day-night cycle, fluctuations related to the change of seasons (approximately monthly), fluctuations due to weather patterns (daily and long-term), and others [Energy]. As an instance, observe the hourly use of power for Australia during a one-year period shown in Fig. 6.1 [D&A 00]. Generally, power consumption peaks in the winter due to heating demands, and peaks again in the summer due to cooling demands. Power usage also shows a year-to-year growth that may be related to popula-tion growth and economic development, as well as the seasonal variation is the most evident, especially when the daily fluctuations are removed by taking averages over weekly periods.

Problem: Determine the total energy over a three year period.

6.2 Problem: Empirical Model

The data for power usage is just a series of numbers, each for a different time, and therefore not in an appropriate form for analytic integration. (In Chap. 14 we do this integration numerically with Java. That type of integration is possible with just a table of numbers.. We model it approximately with the three formulas:

1. P@tD = 4 + H2 + Sin@2 p tDL SinB 1 p tÅÅÅÅÅÅÅÅÅÅÅÅÅÅ91

F2. P@tD =

ikjjjjj4 +1 t

ÅÅÅÅÅÅÅÅÅÅÅÅÅ365

+1 Sin@ 1 p tÅÅÅÅÅÅÅÅÅÅ91 DÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ

2yzzzzz ikjjjj2 +

1 Sin@2 p tD2ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ

2yzzzz

3. P@tD =ikjjjjj4 +

1 tÅÅÅÅÅÅÅÅÅÅÅÅÅ365

+1 Sin@ 1 p tÅÅÅÅÅÅÅÅÅÅ91 DÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ

2yzzzzz H2 + ‰H-Sin@2 p tDLL

where the power P(t) is in GW (109 watts) and the time t in days. These formulas try to incorporate the various time dependencies of power usage. Since t is in days, a function of the form sin(2p t/T) is periodic with period T days. There-fore sin(2p t) in these models represents a daily variation of power. Likewise, sin(2p t/91) has a period of 182 days (half of a year), and so represents a variation that peaks twice during the year. Models 2 and 3 have a term that grows linearly with time to account for year-to-year growth. Finally, model 3 incorporates an exponential time dependence of power use on a daily time scale.

To see if these models look anything like the data, we plot them:

Landau, First Course in Scientific Computing 141

Copyright: Princeton Univ Press, RH Landau, 2005

Page 199: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[313]:= H∗ Plot of model 1 ∗LPlot@H4 + H2 + Sin@2∗ π ∗tDL∗Sin@H1ê91L∗ π ∗tDL, 8t, 0, 700<,

AxesLabel → 8"t", ""<, PlotLabel −> "Power HGWL vs Time HdaysL"D;

100 200 300 400 500 600 700t

1234567Power HGWL vs Time HdaysL

In[314]:= H∗ Plot model 2 here ∗LIn[315]:= H∗ Plot model 3 here ∗L

Indeed, there is a bi-yearly variation about a non-zero average, a daily variation, and, for models 2 and 3, a long-term growth of the average.

6.3 Theory: Power and Energy Definitions

In everyday usage, the words ``power'' and ``energy'' may be used with meanings that are not totally consistent with their scientific meanings (like when you pay the ``power bill'' although you are really buying energy). Power is defined as the rate at which work is done, or energy used:

P =Wt.

Consequently, if energy is measured in joules (System International), then power is measured in joules/second or watts.

The power company charges you for kilowatt-hours. A kilowatt is 1000 watts, an hour is 3600 seconds, and so 1 kilowatt-hour = 1000 watts x 3600 sec = 3.6 106 joules. Typical costs for a kWh is between 2 and 20 cents, depending on where you live and politics. In any case, you are paying for energy, not power. To set the scale for some realistic numbers, one horsepower (hp) equals 746 W. One energy worker, the average output power of a human body, is 100 W, significantly less than a horse. A nuclear power plant produces energy at the rate of 1150 MW, significantly more than a horse.

In our problem we are given the power used as a function of time, and asked to compute the energy used in three years. Rearranging the definition of power gives the energy used during infinitesimal time dt as

„ W = P@tD „ t

which gives the total energy used from some time 0 to T as

W @TD = ‡o

TP@tD „ t

This means that to solve our problem we need to integrate the three power functions given in the problem definition, which is equivalent to finding the area under the P[t] vs t curves. If an analytic integration is possible, then we will have a

142 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 200: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

function W(T) to use for predicting future energy usage. Otherwise we just have to evaluate the integral numerically and plot the numbers up to see the trends.

6.4 Mathematica: Tools for Integration

Integrals were invented to determine quantities such as the potential energy in the interior of a spherical planet:

V HRL = ‡0

R4 rHrL pr „ r

Calculus is still essential for solving scientific problems, and Mathematica is good at calculus. In the previous chapter we studied the derivative, here we study the integral, which is essentially the inverse of the derivative (antiderivative). An integral without explicit limits, such as Ÿ f @xD „ x , is an indefinite integral. An integral with limits, such as Ÿa

b f @xD „ x , is a definite integral. The difference is important. An indefinite integral is still a function of x, while a definite integral is just a number. As we are about to see, Mathematica can handle both types of integrals.

à 6.4.1 Indefinite Integration

The Mathematica command for integration is Integrate[f[x], x]. The symbol Ÿ Ñ „ Ñ from the BasicInput palette may also be used:

In[316]:= Integrate@yêSqrt@1 + xD, xDH∗ Evaluate indefinite integral ∗LOut[316]= 2 è!!!!!!!!!!!1 + x y

In[317]:= PrintA" Ÿ y xè!!!!!!!!!!!!!!!!!1 + \n x

= ", Integrate@yêSqrt@1 + xD, xDEH∗ Answer in illuminating form ∗LŸ y xè!!!!!!!!!!!!!!!!!1 + \n x= 2 è!!!!!!!!!!!1 + x y

In[318]:= H∗ Evaluate integral using palette symbol ∗LLook at the second argument to Integrate. It is the variable with respect to which we want the integration performed. Be careful, it does not have to be x:

In[319]:= Integrate@yêSqrt@1 + xD, yD H∗ Note if x or y is integration var ∗LOut[319]=

y2

2 è!!!!!!!!!!!1 + x

Notice too that Integrate does not write out a constant of integration for these indefinite integrals. You'll need to include that by hand, if needed. We check the answer by differentiation:

In[320]:= D@Integrate@yêSqrt@1 + xD, yD, yDOut[320]=

yè!!!!!!!!!!!1 + x

Landau, First Course in Scientific Computing 143

Copyright: Princeton Univ Press, RH Landau, 2005

Page 201: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[321]:= ∂y ‡ y yè!!!!!!!!!!!1 + x

H∗ Symbolically ∗LOut[321]=

yè!!!!!!!!!!!1 + x

In[322]:= D@Integrate@yêSqrt@1 + xD, yD, xDH∗ Note integrationêdifferentiation variables ∗LOut[322]= −

y2

4 H1 + xL3ê2In[323]:= D@Integrate@yêSqrt@1 + xD, xD, xDOut[323]=

yè!!!!!!!!!!!1 + x

à 6.4.2 Definite Integration

Definite integration includes the integration limits as the second and third items in the list entered as the second argument:

In[324]:= Integrate@xêSqrt@1 + xD, 8x, a, b<DH∗ Definite Integral ∗LOut[324]= 1.33322 + J−1.33333 +

2 b3

N è!!!!!!!!!!!!!1. + b

Notice that the second argument of Integrate is now a list, with the integration variable listed first, followed by the lower and upper integration limits. In spite of Mathematica's awesome powers for doing integrals, some functions cannot be integrated analytically:

In[325]:= Integrate@Exp@−xD∗Sin@xDêSqrt@1 + xD, 8x, 0, 1<DOut[325]= −

12 è!!!!!!!!!!!1 −

è!!!!!!!!!!!1 +I−è!!!!!!!!!!!!!!!!!!!!H1 − L π Cos@1D +

è!!!!!!!!!!!!!!!!!!!!H1 + L π Cos@1D −è!!!!!!!!!!!!!!!!!!!!H1 + L π Cos@1D ErfAè!!!!!!!!!!!1 − E +è!!!!!!!!!!!!!!!!!!!!H1 − L π Cos@1D ErfAè!!!!!!!!!!!1 + E +

è!!!!!!!!!!!!!!!!!!!!H1 − L π Sin@1D +è!!!!!!!!!!!!!!!!!!!!H1 + L π Sin@1D −è!!!!!!!!!!!!!!!!!!!!H1 + L π ErfAè!!!!!!!!!!!1 − E Sin@1D −

è!!!!!!!!!!!!!!!!!!!!H1 − L π ErfAè!!!!!!!!!!!1 + E Sin@1DM +

14 è!!!!!!!!!!!1 −

è!!!!!!!!!!!1 +I−2 è!!!!!!!!!!!!!!!!!!!!H1 − L π Cos@1D + 2 è!!!!!!!!!!!!!!!!!!!!H1 + L π Cos@1D −

2 è!!!!!!!!!!!!!!!!!!!!H1 + L π Cos@1D ErfAè!!!!!!!!!!!!!!2 − 2 E + 2 è!!!!!!!!!!!!!!!!!!!!H1 − L π Cos@1D ErfAè!!!!!!!!!!!!!!2 + 2 E +

2 è!!!!!!!!!!!!!!!!!!!!H1 − L π Sin@1D + 2 è!!!!!!!!!!!!!!!!!!!!H1 + L π Sin@1D −

2 è!!!!!!!!!!!!!!!!!!!!H1 + L π ErfAè!!!!!!!!!!!!!!2 − 2 E Sin@1D − 2 è!!!!!!!!!!!!!!!!!!!!H1 − L π ErfAè!!!!!!!!!!!!!!2 + 2 E Sin@1DMThis answer is not illuminating. However, even if Mathematica can't figure out an exact value for the integral, it should be able to evaluate it numerically. Just tell Mathematica to use numerical methods with the NIntegrate command:

144 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 202: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[326]:= NIntegrate@Exp@−xD∗Sin@xDêSqrt@1 + xD, 8x, 0, 1<DH∗ Numerical integration ∗LOut[326]= 0.196519

Now and then you may to try different approaches to get a workable form for a needed integral, for example

S = Ÿ è!!!!!!!!!!!!!!!!!!!!!!!!!!!!1 + b t + c t2 „ t .

Have Mathematica evaluate this expression for S as an indefinite integral:

In[327]:= H∗ Enter the expression for S here ∗LIn[328]:= Simplify@%D

Have Mathematica evaluate this expression for S as a definite integral Ÿ0Tè!!!!!!!!!!!!!!!!!!!!!!!1 + bt + ct2 „ t

In[329]:= H∗ Enter S as a definite integral ∗LIn[330]:= H∗ Try FullSimplify@%D ∗L

FullSimplify@%DEven the definite integral is terribly complicated. See if substituting some numerical values for the constants helps:

In[331]:= H∗ Assign values to b,c, and T ∗Lb = 2; c = 9; T = 5;

In[332]:= ‡0

T

è!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1 − b∗t + c ∗ t2 t H∗ Evaluate the definite integral ∗L

à 6.4.3 Integrals as Functions

It should be noted that Integrate, like D, produces an expression, not a function. We make the value of an indefinite integral I[x] = Ÿ f HxL „ x into a function in the usual way:

In[333]:= myInt@x_D := Integrate@yêSqrt@1 + xD, xD H∗ Form function I@xD ∗L? myInt

Global`myInt

myInt@x_D := Ÿ yè!!!!!!!!!1+x x

In[335]:= myInt@zD H∗ Evaluate function for argument z ∗LOut[335]= 2 y è!!!!!!!!!!!1 + z

In[336]:= D@myInt@xD, xD H∗ Differentiate I@xD ∗LOut[336]=

yè!!!!!!!!!!!1 + x

Since definite integrals are over a specific range, we can imagine the integral as a function of both its upper and lower integration limits, as well as the variable to integrate over. Let's look at the definite integral again:

Landau, First Course in Scientific Computing 145

Copyright: Princeton Univ Press, RH Landau, 2005

Page 203: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[337]:= ‡y

z

xè!!!!!!!!!!!1 + x

x H∗ Integrate@xêSqrt@1+xD,8x,y,z<D ∗LOut[337]=

23H2 − yL è!!!!!!!!!!!1 + y −

23H2 − zL è!!!!!!!!!!!1 + z

The integral clearly depends upon y and z, the endpoints of the interval. Thus we make the integral a function of the endpoints:

In[338]:= Clear@myIntDIn[339]:= myInt@x_, a_, z_D := Integrate@xêSqrt@1 + xD, 8x, a, z<D

? myInt

Global`myInt

myInt@x_, a_, z_D := Ÿaz xè!!!!!!!!!1+x x

In[341]:= myInt@x, a, zDOut[341]= 1.33322 + J−1.33333 +

2 z3

N è!!!!!!!!!!!!!1. + z

In[342]:= D@myInt@x, a, zD, zDH∗ Should give us integrand back, but it doesn' t look it ∗LOut[342]=

−1.33333 + 2 z3

2 è!!!!!!!!!!!!!1. + z+2 è!!!!!!!!!!!!!1. + z

3

In[343]:= FullSimplify@%D H∗ This now looks like the integrand ∗LOut[343]=

−4.44089×10−16 + 6 z6 è!!!!!!!!!!!!!1. + z

6.5 Problem Solution: Energy from Power

We now know how to evaluate integrals, so let's do some! We will investigate models 1 and 3 here, and leave model 2 for you. For model 1, let's first define a function for the power, and then look at it to see if it looks OK:

In[371]:= P@t_D := 4 + H2 + Sin@2∗Pi∗tDL∗Sin@HPi∗tLê91D?P

Global`P

P@t_D := 4 + H2 + Sin@2 π tDL Sin@ π t91 D

146 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 204: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[375]:= Plot@P@tD, 8t, 0, 365<,PlotLabel −> "Model 1 P@tD, for one year", AxesLabel → 8"t", ""<D;

50 100150200250300350t

1234567Model 1 P@tD, for one year

Now that we know the integrand looks reasonable, let's integrate it:

In[376]:= Integrate@P@tD, tDThe integration may take a bit of time (anywhere from a couple seconds to an hour!) depending on your version of Mathe-matica and the computer system you are using. The answer should look like:

4 t -182 Cos@ p tÅÅÅÅÅÅÅ91 DÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ

p+

91 Sin@ 181 p tÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ91 DÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ

362 p-

91 Sin@ 183 p tÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ91 DÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ

366 p

The expression for the integral is neat and show that the total energy used has some terms that oscillate as a function of time, as well as a term that increases linearly with time. However, it is missing the integration constant, which is clear since the t=0 value of the integral is -182/p, when it should be 0. One way of eliminating the need for us to personally include the integration constant, is to evaluate the integral as a definite integral:

In[348]:= Integrate@P@tD, 8t, 0, T<DAnswer:

182ÅÅÅÅÅÅÅÅÅÅÅÅÅ

p+ 4 T -

182 Cos@ p TÅÅÅÅÅÅÅÅÅ91 DÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ

p+

91 Sin@ 181 p TÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ91 DÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ

362 p-

91 Sin@ 183 p TÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ91 DÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅ

366 p

This expression vanishes for T = 0, as it should. If we can find a way to treat this integral as a function of the upper limit T, then we can proceed on our way. We define the energy function Energy(t) as the power integrated up to time T:

In[349]:= Energy@T_D := Integrate@P@tD, 8t, 0, T<D;?Energy

Global`Energy

Energy@T_D := Ÿ0TP@tD t

We now evaluate the energy used after no years and one year:

In[351]:= Energy@0DIn[352]:= Energy@365D

Mathematica is returning the one year result as an exact number, which really does not make much sense here since we want a floating point number to tell the stockholders. So we modify the definition Energy(t) to float the answer and look at answers for zero, one, and two years:

In[353]:= Energy@T_D := N@Integrate@P@tD, 8t, 0, T<DD;?Energy

Landau, First Course in Scientific Computing 147

Copyright: Princeton Univ Press, RH Landau, 2005

Page 205: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[355]:= Energy@[email protected]ê [email protected]

Out[355]= NIntegrate@4. + 2. [email protected] 3.14159D, 815., 0., 0.<DOut[356]=

NIntegrate@4. + 2. [email protected] 3.14159D, 815., 0., 365.<DN

Out[357]= NIntegrate@4. + 2. [email protected] 3.14159D, 815., 0., 730.<DThe energy used does appear to be growing year-by-year, something we can check with a simple plot for 1000 days:

In[358]:= Plot@Energy@TD, 8T, 0, 1000<D;This calculation seems to take Mathematica an extremely long time! Feel free to abort it and refer to the corresponding plot output in the text. We see a small fluctuation about a linear increase. This does not bode well for the planet!

We now study model 3 as we did model 1. First we define a function for the power:

In[359]:= P3@t_D := H4 + 1ê365 + 1ê2∗Sin@1ê91∗ π ∗tDL∗H2 + Exp@−Sin@2∗ π ∗tDDL;?P3

Global`P3

P3@t_D := H4 + 1365 + 1

2 Sin@ π t91 DL H2 + −Sin@2 π tDL

148 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 206: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[361]:= Plot@P3@tD, 8t, 0, 30<,PlotLabel −> "Model 3 P@tD, for one month", AxesLabel → 8"t", ""<D;

Plot@P3@tD, 8t, 0, 365<, PlotLabel −> "Model 3 P@tD, for one year",AxesLabel → 8"t", ""<D;

5 10 15 20 25 30t

12

14

16

18

20

Model 3 P@tD, for one month

50 100 150 200 250 300 350t

101214161820

Model 3 P@tD, for one year

That looks good and shows an interesting daily and yearly variation. Now that we know that the integrand looks reason-able, let us integrate it:

In[363]:= Integrate@P3@tD, tDMathematica appears to give up on us (just repeating the input), so let us try the definite integral form:

In[364]:= Integrate@P3@tD, 8t, 0, T<DOut[364]= ‡

0

5

3 J 1461365

+12SinA 15 π

91EN 15

Again Mathematica fails us. Maybe we can do it numerically?

In[365]:= NIntegrate@P3@tD, 8t, 0, 365<DOut[365]= 4800.01

Did it work? The correct answer should be 5364.72. If your answer is less than this, read the error messages carefully and note at what value of t the integrations stopped. Most likely, Mathematica did not integrate the whole interval from 0 to 365 due to lack of accuracy. We suspect inadequacies in Mathematica's algorithm for integrations because Maple can do these integrals with no problems. If the above integral didn't work, please refer to the Maple text for the rest of the model 3 exploration. Otherwise continue:

Landau, First Course in Scientific Computing 149

Copyright: Princeton Univ Press, RH Landau, 2005

Page 207: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[366]:= Energy3@T_D := NIntegrate@P3@tD, 8t, 0, T<D;?Energy3

Global`Energy3

Energy3@T_D := NIntegrate@P3@tD, 8t, 0, T<DIn[368]:= Energy3@0D

Energy3@365DEnergy3@730D

We see, again, a rather linear increase in energy use for the next few years.

à 6.5.1 Your Solution to Model 2

1. Analyze model 2 of energy usage in a manner similar to that used in the text. [Note: The algorithms in Mathematica seem to have problems integrating these types of integrands and Maple may be a better choice here.]

2. These models show a rather linear increase in integrated energy over time. This is a long-range concern because their is no way for a finite amount of energy to sustain this growth. Although you may not be able to dictate energy use to the world, modify models 1 and 3 so that the total energy-use growth rate is approximately 10% per year.

3. Devise a model in which the total energy used becomes a constant in time.

6.6 Key Words and Concepts

(in)definite integral integration constant power vs. energy integration limits

1. If you buy a truck, do you want it to have lots of power or lots of energy?

2. If an integral represents the area under a curve, how does indefinite integration make sense?

3. How can an integral be thought of as a function?

4. If the definite integral of some expression exists, does that mean that the indefinite integral must also exist?

5. If the indefinite integral of some expression exists, does that mean that the definite integral must also exist?

6. Is it possible to integrate an integral?

7. If the numerical integral of some expression exists, does that mean that the analytic integral must also exist?

8. Is it possible to integrate a function that becomes singular (equal to infinity) in the region of integration?

150 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 208: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

6.7 Supplementary Exercises

1. Evaluate the following integrals:

a) Ÿ 3 x2 - 5 x + 8 „ x

b) Ÿ è!!!!!!!!!!!!!!!!!x3 + 5 x „ x

c) Ÿ01

‰è!!!!!!!!!!!!!!!!x3+ 5 x „ x

d) Ÿ 1ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅx2 + 2 x + 4 „ x

e) Ÿ-11

1ÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅHx-2L2 „ x

f) Ÿ0¶

‰H-xL2 „ x

g) Ÿ lnHxL „ x

Landau, First Course in Scientific Computing 151

Copyright: Princeton Univ Press, RH Landau, 2005

Page 209: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

c:1

Appendix B: Mathematica Quick Reference

c:2

Basic Operations & Representations

In[189]:= 3*45- 7^6 (* Comment field *)(2+3) 3 (* Mult implied *)(2+3)*3 (* Mult explicit *)Sin[3.] Sqrt[10.] Cos[Pi] Log[E]N[1/3] ( * Numerical, floating pt *)1/3//N ( * Numerical, floating pt *) N[1/3, 20] (* 20 digit float *)(2 + 2*I)/(2 - 2*I) (* Complex *)

c:3

Sums, Products, Strings, Printout

In[193]:= Sum@HH−1L^i ∗ x^H2∗iLLêH2∗iL!, 8i, 0, Infinity< D H∗ Sum series ∗LFullSimplify@%Dstrng == "George" H∗ Assignment ∗LPrint@"cosHPiL = ", Cos@PiDD

Landau, First Course in Scientific Computing 230

Copyright 2005: Princeton Univ Press, RH Landau

Page 210: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

Statements, Expressions & Functions

In[197]:= Exp[x]-1 (* Symbolic *)Clear[x,y] (* Unassign x & y *)x = 10 x := 10 (* Now, later *)x = . (* Remove value *)g[x_]:= 10 * Sin[3*x] (* Function *)y[x_, A_, b_] := A * x^4 * Sin[b*x] Simplify, FullSimplify, Factor, Collect, Expand, ComplexExpand, Evaluate, Normalz /. x →3, y → 2 (* Replace *)

Solving Equations

In[203]:= Solve[a*x^2 + b*x + c == 0, x] (* Solve 1st arg for x *)Solve[eqn, x] eqn/.x→a (* Replace *) Roots[x^2+1 0, x] FindRoot[x Sin[x] 1, x,1]NSolve[eqn1, x] (* Numerical *)

Simultaneous Equations

In[209]:= Solve[eqn1, eqn2, x, y] (* Solve set of equations *)NSolve[eqn1, eqn2,x,y] (* Numerical solve *)FindRoot[eqn1,eqn2,x,1,y,1 ]eqn1 /. x→3.19739, y→1.21117

231 Landau, First Course in Scientific Computing

Copyright 2005: Princeton Univ Press, RH Landau

Page 211: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

Plotting Along

In[213]:= Plot[V[r], r,0,1] (* Minimal *)Plot[V[r], r,0,1, PlotRange→0,1,0,10] (* Limit y range *)<<Graphics`Graphics`(* Load package*)LogPlot[x^2, x,0,10];LogLogPlot[x^2, x,0,10];Plot[1/r, r, 1/10, 5, AxesLabel→"radius r","V(r)", PlotLabel→"Potentials"];Plot3D[ V[x,y], x,-4,4, y,-4,4, PlotPoints→40, PlotRange→0,2.5, AxesLabel→"x","y","V(x,y)" ];ContourPlot[ V[x,y], x, -4,4, y,-4,4 ];Animate[ Plot[Sin[x]*Exp[-0.3*t]-(Sin[3x]*Exp[-9*0.3t])/9, x,0,π, PlotRange→0,π, AxesLabel→"x","t", Ticks→False],t,0,20 ]MoviePlot[(Sin[3x]*Exp[-9*0.3t])/9, x,0,π,t,0,20, PlotRange→0,π]MoviePlot3D[ T[x,y, t], x,0,π, y,0,π, t,0,20, PlotRange→0,1, AxesLabel→"x","y","T[x,y]" ] ParametricPlot[Sin[ωt], -2*Cos[ωt], ωt,0,8*π, AxesLabel→"x(t)", "v(t)"] PlotVectorField[Ex[x,y],Ey[x,y],x,-3.5,3.5,y,-3.5,3.5] PolarPlot[Cos[t],Sin[t],t,0,4π]; (* Several polar plots together *)

à Plotting Data (see too Chapter 4)

In[215]:= ListPlot[mylist, PlotJoined→True];ListPlot[0,1,Sqrt[3]/2, 1/2, -Sqrt[3]/2, 1/2, PlotJoined→True]; ListPlot3D[data,ColorFunctionScaling→True, ColorFunction→Hue , ViewPoint->-2.343, 2.209, 1.040];

Landau, First Course in Scientific Computing 232

Copyright 2005: Princeton Univ Press, RH Landau

Page 212: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

Calculus

à Differentiation

In[218]:= v[t_] := Limit[(x[t+∆]-x[t])/∆, ∆→0]; (* Limit *)D[Sin[x],x] (* D for derivative *)D[f[x],x,2] (* Second derivative *)D[(Sin[x])^y, x,y] (* Second partial derivative *)Derivative[1][x] (* Derivative as function *)v@t_D := Derivative@1D@xD@tD ;

In[224]:= Derivative[2][f][x] (* Second deriv of f *)Derivative[2][Sin] (* 2nd deriva of function *)Derivative[0,1][g][x,y] (* 1st deriv of g wrt y *)Derivative[1,1][g][π/4, π/4] (* 2nd deriv at values *)

à Integration

In[228]:= Integrate[y/Sqrt[1+x], x] (* Indefinite integral *)Integrate[x/Sqrt[1+x], x,a,b] (* Definite Integral *)NIntegrate[Exp[-x]*Sin[x]/Sqrt[1+x], x,0,1] (* Numerical *)myInt[x_] := Integrate[y/Sqrt[1+x], x] (* As function *)

à Differential Equations

In[232]:= diffeq = D[Vy,t] -g (* DE for vertical velocity *)diffeq = D[y[t],t,2]==-g (* Simpler form *)DSolve[diffeq, y,t] (* Solve diff E *)diffeq2 = Derivative[2][y] -g (* ODE with functional op *)DSolve[diffeq2, y[t], t] (* Solution *)initcon = y[0] == 0, Derivative[1][y][0] V\_y0 (* IC *)DSolve[diffeq, initcon,y[t] (* Include IC *)Plot[Evaluate[y[t]/.soltn], t,0,4.2, PlotLabel->"y(t) vs t"]; (* Plot y(t) *)

233 Landau, First Course in Scientific Computing

Copyright 2005: Princeton Univ Press, RH Landau

Page 213: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

Linear Algebra

à Defining Matrices &Vectors

In[237]:= <<LinearAlgebra`MatrixManipulation` (* Load package *)cubes = Table[i\^3, i, 4] (* Build vector *)M = Table[f[i,j], i,2,j,2]; (* 2x2 matrix of f vals *)Print["M = ", MatrixForm[M]] (* Traditional form *)Array[f, m, n] (* m x n matrix *)m = DiagonalMatrix[a,b,c,d,e,f]; (* Diagonal matrix *)B[[3,2]] (* Assign single element *)ListPlot3D[ID, PlotLabel→"Identity Matrix", AxesLabel→"column","row", " "];A1D = Array[x,4] (* 1D array with x value *)A2D = Array[x+y,2,2] (* 2D array, ie matrix *)

Landau, First Course in Scientific Computing 234

Copyright 2005: Princeton Univ Press, RH Landau

Page 214: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

Matrix Operations

In[238]:= AppendColumns, AppendRows, BlockMatrix, HankelMatrix, HilbertMatrix, InverseMatrixNorm , LinearEquationsToMatrices, LowerDiagonalMatrix, LUMatrices, MatrixConditionNumber, MatrixNorm, PolarDecomposition, SquareMatrixQ, SubMatrix, TakeColumns, TakeMatrix, TakeRows, TridiagonalMatrix, UpperDiagonalMatrix, VectorNorm, ZeroMatrix

3* A//MatrixForm (* Mult bynumber & display *)Print["A . B = ", MatrixFor m[A.B]] (* Mult matrices *)A + B//MatrixForm (* Matrix addition *)Det[A] (* Determinant of matrix *)Binv = Inverse[B];MatrixPower@A, −1D êê MatrixForm (* Inverse too *)Transpose[A]//MatrixForm (* Interchange rows & columns *)Tr[A] (* Trace = sum of diagonal elements *)Map[FullSimplify, %]//MatrixForm (* Simplify all elements *)dt = vec . vec2 (* Dot product *)vcross = vec2 vec3; (* Cross product *)Outer[Times,vec,vec]//MatrixForm (* Outer product *)SetCoordinates[Cartesian[x,x,x]] (* Deriv wrt set *)Curl[vec]SetCoordinates[Cartesian[x,y,z]]Div[f] Grad[x^3] (* Divergence of vector f *)

Eigenvalues, Eigenvectors, Linear Equations

In[238]:= Eigensystem[A] (* Eigenvalues, vectors *)VecMatrix = Eigenvectors[A]; (* Eigenvectors in matrix *)lambda[[1]] lambda[[2]] lambda[[3]] (* Eigenvalues *)vec1 = VecMatrix[[1]]; (* 1st eigenvector *)Print["vec1 = ", MatrixForm[vec1]]<<LinearAlgebra`Orthogonalization`NewVecs = GramSchmidt[vec1,vec2,vec3, Normalized→False]X = LinearSolve[A,b]; (* Solve A X = b for X *)

235 Landau, First Course in Scientific Computing

Copyright 2005: Princeton Univ Press, RH Landau

Page 215: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

Modules; Generating Fortran & C Code

In[246]:= Clear@mySum, MySumDmySum = 0;MySum@iStart_, iEnd_D := Module@8istop<, istop = 77; mySum = 0;For@i = iStart, i <= iEnd, i++, mySum = mySum + i; If@i istop, Break@DDD;Print@"In MySum, at the end of loop, i = ", i, ", mySum = ", mySumDD

CForm[expr]FortranForm[expr]

Landau, First Course in Scientific Computing 236

Copyright 2005: Princeton Univ Press, RH Landau

Page 216: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

Mathematica standard Library Functions

In[251]:=

Abs Erfc MathieuCharacterAiryAi Erfi MathieuCharacterAiryAiPrime EulerE MathieuCharacterAiryBi EulerGamma MathieuCPrimeAiryBiPrime EulerPhi MathieuSAppellF1 Exp MathieuSPrimeArcCos ExpIntegralE MaxArcCosh ExpIntegralEi MeijerGArcCot ExtendedGCD MinArcCoth Factorial MinusArcCsc Factorial2 ModArcCsch FactorInteger ModularLambdaArcSec Fibonacci MoebiusMuArcSech Floor MultinomialArcSin FractionalPart MultiplicativeOrArcSinh FresnelC NonCommutativeMuArcTan FresnelS PartitionsPArcTanh Gamma PartitionsQArg GammaRegularized PiArithmeticGeometricMean GCD PlusBernoulliB GegenbauerC PochhammerBesselI Glaisher PolyGammaBesselJ GoldenRatio PolyLogBesselK HarmonicNumber PowerBesselY HermiteH PowerModBeta Hypergeometric0F1 PrimeBetaRegularized Hypergeometric0F1Regularized PrimePiBinomial Hypergeometric1F1 PrimeQCarmichaelLambda Hypergeometric1F1Regularized ProductLogCatalan Hypergeometric2F1 QuotientCeiling Hypergeometric2F1Regularized RandomChebyshevT HypergeometricPFQ ReChebyshevU HypergeometricPFQRegularized RiemannSiegelTheChop HypergeometricU RiemannSiegelZClebschGordan I RoundConjugate Im SecContinuedFraction Indeterminate SechCos Infinity SeedRandomCosh IntegerDigits SignCoshIntegral IntegerExponent SignatureCosIntegral IntegerPart SinCot InverseBetaRegularized Sinh

237 Landau, First Course in Scientific Computing

Copyright 2005: Princeton Univ Press, RH Landau

Page 217: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

Coth InverseEllipticNomeQ SinhIntegralCsc InverseErf SinIntegralCsch InverseErfc SixJSymbolDedekindEta InverseGammaRegularized SphericalHarmoniDegree InverseJacobiSN SqrtDigitCount InverseWeierstrassP StieltjesGammaDiracDelta JacobiAmplitude StirlingS1DiscreteDelta JacobiP StirlingS2Divide JacobiSN StruveHDivisors JacobiSymbol StruveLDivisorSigma JacobiZeta SubtractE Khinchin TanEllipticE KleinInvariantJ TanhEllipticExp KroneckerDelta ThreeJSymbolEllipticF LaguerreL TimesEllipticK LatticeReduce UnitStepEllipticLog LCM WeierstrassHalfPEllipticNomeQ LegendreP WeierstrassInvarEllipticPi LegendreQ WeierstrassPEllipticTheta LerchPhi WeierstrassPPrimEllipticThetaPrime Log WeierstrassSigmaErf LogGamma WeierstrassZeta

Mathematica Packages

In[251]:= Algebra Calculus DiscreteMath Geometry GraphicsLinearAlgebra Miscellaneous NumberTheory NumericalMath Statistics

Utilities

Landau, First Course in Scientific Computing 238

Copyright 2005: Princeton Univ Press, RH Landau

Page 218: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

Chapter 8: Searching, Programming; Dipsticks

8.4 Mathematica Tools: Programming

We have already done some Mathematica programming when we defined functions so that we could enter f[x] rather than write out some complicated expression all the time. This is fine as long as what we want to calculate fits on one line. However, sometimes we need to include a number of steps in a calculation, and we can't do that with a function. In these latter cases we need to write a program containing the logic that Mathematica needs to follow. In this chapter we explore some of the features of Mathematica that are useful for programming. While programming with Mathematica is a useful extension of our programming skills, we recommend that you should also experience the more powerful programming possible with compiled languages like Java. We do that in Part II of this book. The Mathematica programming here is an excellent introduction to compiled-language programming.

à 8.4.1 Logic

The first step in having the computer make intelligent decisions is having it be able to tell if a statement is true or false. This is accomplished with Boolean variables, that is, variables that are either true or false. Objects that have true and false values may also be constructed from expressions. To construct a Boolean expression, you use relational and logical operators to combine ordinary variables. The relational operators in Mathematica are

< less than <= less than or equal > greater than

>= greater than or equal == equal != not equal

To prove the point, 1 < 2 is true, as is 1 <= 1, while 2 != 2 is false, as is 2 > 3. To determine what Mathematica believes to be true, we evaluate an expression as a Boolean by typing it in with the relational operators:

In[716]:= 1 > 2 H∗ Returns True, False, or echo of input ∗LOut[716]= False

In[717]:= Temp = 1 H∗ Initialize some regular variables ∗LHeat = 3

Out[717]= 1

Out[718]= 3

In[719]:= Temp <= HHeat − 2L H∗ Construct Boolean expression ∗LOut[719]= True

Landau, First Course in Scientific Computing 201

Copyright: Princeton Univ Press, RH Landau, 2005

Page 219: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[720]:= Temp ≤ Heat − 2 H∗ No parentheses, same answer ∗LOut[720]= True

In[721]:= Temp Heat H∗ Another Boolean expression ∗LOut[721]= False

More complicated logical expressions are created by combining simple Boolean expressions by use of the logical, or conditional operators:

and or not

The basic logic behind logical operators is that compound statements constructed from two simpler statements obey the truth table

True False True False

true and true true and false true or false false or false

true or true false and false not false not true

In Mathematica the logical operators are the functions, And, Or, and Not with multiple arguments separated by commas:

In[722]:= And@4 < 5, −99 < 1D H∗ True and True ∗LOut[722]= True

In[723]:= Or@1 < −99 , −99 < 1D H∗ False or True ∗LOut[723]= True

In[724]:= Not@1 1D H∗ Not True ∗LOut[724]= False

You can also use symbols for the logical operators and type them like a compound statement. Logical and is the wedge fl, logical or is the vee fi, and logical not is the exclamation mark !. You find these symbols on the palette or by typing ``esc and esc'' for and, and ``esc or esc'' for or.

In[725]:= 3 < 4 fl −10 < −8 H∗ True and True ∗LOut[725]= True

202 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 220: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[726]:= 1 > −99 fi −99 > 1 H∗ True or False ∗LOut[726]= True

à 8.4.2 Flow Control

The basic logic command used to control program flow is the if statement:

if a statement is true, then do something, else do something else.

Mathematica uses a particular notation for this:

If[test, then, else]

Here test represents an expression that will be evaluated as Boolean, then represents any sequence of Mathematica statements that will be evaluated if test is true, and else represents a set of statements that will be evaluated if test is false. Hence, the If statement provides a way to choose between two alternatives. If more alternatives are needed, you can use a nested set of If functions, but it is clearer to use functions like Which or Switch, which we will discuss later. Also, as we shall see below, you can use just part of the If construct and leave off the else statement if you don't need it.

We start with a simple test that may be useful for programming a thermostat. If the temperature Temp is negative, then we need more Heat:

In[727]:= Heat = 2 ; H∗ Set initial value of Heat ∗LPrint@"Heat = ", HeatDHeat = 2

In[728]:= Temp = −3; H∗ Some like it cold! ∗LPrint@"Temp = ", TempDTemp = −3

In[729]:= If@Temp < 0, Heat = Heat + 1D H∗ Increase heat if cold, output is Heat ∗LOut[729]= 3

In[730]:= Temp = 0;If@Temp ≤ 0, Heat = Heat + 1D H∗ More heat for 0 Temp ∗L

Out[731]= 4

We see that Mathematica can tell whether Temp is positive or negative, act accordingly, and print out the value of Heat. Try out these same conditions using an If command that tests if the Temp is positive, not negative:

In[732]:= H∗ Here ∗LUp until this point, we have a thermostat that can turn up the heat when it is cold, but not turn it down when it gets hot. We fix that by adding an else statement into our If:

In[733]:= Temp = 1; Heat = 3; Print@"Heat = ", HeatDHeat = 3

Landau, First Course in Scientific Computing 203

Copyright: Princeton Univ Press, RH Landau, 2005

Page 221: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[734]:= If@Temp ≤ 0, Heat = Heat + 1, Heat = Heat − 1DOut[734]= 2

We can accomplish the same goal as the line above with a nested If function, which is more confusing in this case, but useful for more complicated situations:

In[735]:= Temp = 1; Heat = 3;If@Temp ≤ 0, Heat = Heat + 1,If@Temp > 0, Heat = Heat − 1; Print@"Heat = ", HeatDDDHeat = 2

In conclusion, it is possible to construct all logical conditions by combining the simple Boolean operators and expressions. In particular, you can keep nesting If functions to be as specific as you like, but if you only have two alternatives, one If will do just fine.

8.4.3 Looping

An essential component of scientific computing involves having the computer repeat a set of commands until some pre-defined condition is met. Sometimes this may be until a desired level of precision is achieved, sometimes until a matrix or vector has been spanned, and sometimes this may be to step through space or time in discrete steps. We discuss the way to do this in Java in Chapter 12 and 13, where we loop over time steps for projectiles, and over space steps for integration. Here we discuss how to do this in Mathematica.

We have already seen Mathematica do looping in Chap. 5, where we summed up the height of blocks to obtain the height of a tower:

In[737]:= H = n*t -a*Sum[i, i,1,n-1]

Out[737]= 15 n −12H−1 + nL n

Here Mathematica has an internal program that loops over the sum. We can do the same thing ourselves using Mathemati-ca's For loop construct:

For[start, test, incr, body]

where Mathematica evaluates start, then repetitively evaluates body and incr, until test, a Boolean condition, fails. So we write our own Sum as

In[738]:= mySum = 0 ; H∗ Initialize ∗LFor@i = 1, i <= 100, i++, mySum = mySum + iDPrint@"mySum = ", mySumD H∗ Output final mySum ∗LmySum = 5050

Here incr increases i by 1 each loop from 1 to 100, and body increases mySum by i each time i is incremented. The loop test is always evaluated before the body of the loop is evaluated. As soon as the test fails to be true, the For terminates. As is often the case with loops, some variables must be initialized before the loop begins, as we do here with mySum=0;, where the ; suppresses the output. Take note, you can print out the 100 lines of intermediate output by placing a ; Print[mySum] in the body section of the For construct:

204 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 222: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[740]:= mySum = 0; H∗ Initialize ∗LFor@i = 1, i ≤ 100, i++, mySum = mySum + i; Print@mySumDD1

3 ...

5050

To obtain loops that do not increment by 1 you can write an explicit statement for incr. For example, here we sum all the even numbers from 1 to 100:

In[741]:= mySum = 0; H∗ Initialize ∗LFor@i = 1, i ≤ 100, i = i + 2, mySum = mySum + iDPrint@"mySum =", mySumD H∗ Final mySum ∗LmySum =2500

Another simple loop structure that can do the same thing is the Do loop construct. It has three forms:

Do[expr, i,imax]

Do[expr, i, imin, imax, di]

Do[expr, n]

In each case, expr is evaluated repetitively, just like in the For loop construct. In the first form expr is evaluated with i varying from 1 to imax in steps of 1, in the second form i varies from imin to imax in steps of di, and in the third form expr is evaluated n times.

8.4.3.1 while loop

You may not always know ahead of time just how often a loop must repeat in order for some condition to be met. In that case you can have Mathematica repeat the loop while some condition is true.

While[test, body]

To give an instance, let us say we want to keep summing until some sum is greater than 10,000, then find out what the i value is:

In[743]:= mySum = 0; i = 0; H∗ Initialize and hold output ∗LWhile@mySum < 10000, mySum = mySum + i; i = i + 1DPrint@"mySum = ", mySumD H∗ Output final values ∗LPrint@"i = ", iDmySum = 10011

i = 142

The problem with the While loop is that it repeats as long as the Boolean condition, test, is true: so if test is always true, then the loop is ``infinite'', that is, it will never end. For example, if you change mySum < 10000 to mySum > 0, then you better be prepared to abort the evaluation!

An addition to the While loop construct that can keep it from becoming infinite, is to break the loop, that is, to stop it if some test within the loop is satisfied. Break is a function to control the flow of execution in your program. It is used when the flow of control is affected by values generated in the body of the loop. For example, here we use the Break command to exit the enclosing While loop when i = 77:

In[746]:= mySum = 0; i = 0; H∗ Initialize and hold output ∗L

Landau, First Course in Scientific Computing 205

Copyright: Princeton Univ Press, RH Landau, 2005

Page 223: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[747]:= While@mySum < 10000, mySum = mySum + i; i = i + 1; If@i == 77, Break@DDDPrint@"mySum = ", mySumD H∗ Output final values ∗LPrint@"i =", iDmySum = 2926

i =77

à 8.4.4 Modules (Methods, Multi-line Functions)

Though it is satisfying to write notebooks that have intelligence, the use of logic and looping tends to require many lines in order to handle all the possible situations that may occur. If all the logic and possible cases are placed together, we may end up with a program that is so long and complicated that it is hard to follow. Accordingly, it is useful to do some house-keeping and remove some of the utility commands out from the mainstream of our notebooks. Mathematica permits this by letting us define our own multi-line modules that can be called from within a notebook. Essentially, this is equivalent to defining a multi-line function, or what is called a method in Java.

Here we define a module MySum that sums the values of i from iStart to iEnd, and then prints out the results. The defini-tion of a module uses opening and closing brackets, the first entry is a list of the variables local to just the module, and the second entry is the body of the module:

In[750]:= Clear@mySum, MySumDmySum = 0;MySum@iStart_, iEnd_D := Module@8istop<, istop = 77; mySum = 0;For@i = iStart, i <= iEnd, i++, mySum = mySum + i; If@i istop, Break@DDD;Print@"In MySum, at the end of loop, i = ", i, ", mySum = ", mySumDD

Once again ignoring the spelling warninsg, we test our module by calling MySum, as you would any Mathematica func-tion, with numerical values for the arguments iStart and iEnd. If this works as intended, Mathematica should evaluate all the statements within the body of the module and then return to the worksheet with values for the global variables:

In[753]:= MySum@0, 10000DIn MySum, at the end of loop, i = 77, mySum = 3003

Note that we called our function by name, and gave it two arguments, the number required when we declared the function and assigned it to be a module. The values for the internal, or local variables within a module are not visible from the outside. For example,

In[754]:= istop H∗ Local to procedure ∗LOut[754]= istop

In[755]:= mySum H∗ Global, visible ∗Li

Out[755]= 3003

Out[756]= 77

We see that the internal test causes the loop to break at i = 77, and that the value of the variable, mySum does get returned to the calling program (it should, since we made it global by initializing it before the module). So now let us tell the function to end at iEnd = 70, and not give it a chance to break:

206 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 224: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[757]:= MySum@0, 70DIn MySum, at the end of loop, i = 71, mySum = 2485

In summary, the general form of a module is:

Module[x,y,..., body]

where the opening and closing brackets must always be present, x, y, ... are the local variables, and body includes the Mathematica statements separated by semicolons. In general, the value returned by the module will be the value of the last expression evaluated in the body of the module (without a semicolon). Since in our example the procedure executed a Print function before ending, there was no last expression that was evaluated. However, if we add a semicolon and mySum (which just recalls the value of mySum) before the closing bracket, we obtain

In[758]:= MySum@0, 10000DIn MySum, at the end of loop, i = 77, mySum = 3003

The 3003 on a line by itself is the value returned by the module, in this case the last value of mySum.

Exercise: after the Print, add ; mySum before the closing bracket and verify that now the value of mySum is returned when you call the MySum function.

8.4.5 Conversion of Modules to Compiled Code

The code generation commands CForm@exprD and FortranForm@exprD are used to convert Mathematica modules and expressions into C and Fortran code. Although we give no examples, we tell you this for reference purposes.

8.5 Solution: Volume from Dipstick Height

The solution to our problem of determining the volume of liquid in a spherical tank of radius 3 as a function of height h in the tank, requires us to solve for the height h at which the function

f @hD = h3 - 9 h2 + 12 = 0.

We start by defining this function in Mathematica and then plotting it as a check that there are solutions in the region of interest:

In[759]:= Clear@h, fDf@h_D := h^3 − 9.∗h^2 + 12.?f

Global`f

f@h_D := h3 − 9. h2 + 12.

Landau, First Course in Scientific Computing 207

Copyright: Princeton Univ Press, RH Landau, 2005

Page 225: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[762]:= Plot@f@xD, 8x, 0, 10<, PlotLabel → "Height of Liquid in Sphere"D;

2 4 6 8 10

-100

-50

50

100

Height of Liquid in Sphere

We observe two solutions, that is, two places where f[h] = 0. Yet, as we discussed when we first set up this problem, the physical solution must lie in the range 0 < h < 2R = 6. So only the root near h = 1.5 is physical.

As we have said, while we could use Mathematica's Roots to find the root, we will find it from scratch by programming up the bisection algorithm. We set the level of desired precision to eps = 0.00001, and the range to hlo = 0, and hhi = 7:

In[763]:= eps = 0.00001; Print@"eps = ", epsDhlo = 0; Print@"hlo = ", hloDhhi = 7.; Print@"hhi = ", hhiDeps = 0.00001

hlo = 0

hhi = 7.

We use a While loop construct to continue narrowing down the h range until » hhi-hloÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅÅhhi+hlo » ¥ eps is no longer true:

In[766]:= While@Abs@Hhhi − hloLêHhhi + hloLD ≥ eps,h = 0.5∗Hhlo + hhiL; H∗ Bisect the interval ∗LPrint@"In loop h = ", hD; H∗ Print out ∗LIf@f@hhiD∗f@hD ≤ 0, hlo = h, hhi = hDDH∗ Zero on rt or left? ∗LIn loop h = 3.5

In loop h = 1.75 ...

In loop h = 1.24386

This tells us that for a dipstick height h = 1.244 m we have a volume V= 4 pÅÅÅÅÅÅÅÅ3 = 4.19 m3 of fluid in the tank of radius R = 3 m. As a check, we can try Mathematica's Solve function,

208 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005

Page 226: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

In[767]:= Solve@f@h1D 0, h1DOut[767]= 88h1 → −1.09052<, 8h1 → 1.24385<, 8h1 → 8.84667<<

Sure enough, we see that in the range we are interested in, 0 < h1 < 2, the answer agrees to 1 decimal place in the 5th decimal place with the answer our algorithm found above. Just the precision we asked our algorithm to produce!

8.6 Key Words and Concepts

Boolean expressions Boolean variables Break flow control local vs global variables logical operators looping Module trial & error volume integration

1. Why would you ever want to use a trial and error approach to problem solving?

2. Can you do arithmetic on Boolean variables?

3. What is meant by symbolic logic?

4. How can Boolean variables be related to artificial intelligence (the computer appearing to think)?

5. Can all decision making be reduced to sets of Boolean expressions?

6. Must there always be a relation between the height of a liquid in some vessel and the liquid's volume?

7. If the height of a liquid in some vessel doubles, does that imply that the volume of the liquid must have increased eightfold?

8. Describe what is meant by an iterative solution to a problem.

9. Can a program containing correctly-programmed Boolean expressions ever give the wrong answer?

10. Can logical conclusions ever be wrong?

11. Is a solution found in 10 steps better than one found in 100 steps?

12. Can a function use another function as part of its definition?

8.7 Supplementary Exercises

1. Use the bisection algorithm to calibrate the dipstick. Explicitly, determine the values of h that correspond to the tank being 1/4 full, 1/2 full, 3/4 full, and 99/100 full.

2. Use the If construct to make a plot of the tan function from -2p .. 2p. Limit the ordinate to »tan» § .75.

Landau, First Course in Scientific Computing 209

Copyright: Princeton Univ Press, RH Landau, 2005

Page 227: First Course in Scientific Computing Table of Contentsassets.press.princeton.edu/landau_firstCourse/MathematicaCD/Math… · Problem Solving Using Maple, Java, Mathematica, and Fortran

3. Write a loop that evaluates the power series for the exponential function ‰H-xL = ‚n=0

N H-xLnÅÅÅÅÅÅÅÅÅÅÅÅÅn! for x = 1, 10, 100. Continue

the loop until the next term added to the sum is less than 1e-6 of the value for the sum.

4. Create a loop that uses the bisection algorithm to find a solution, good to 6 places, of the equationx = H−xL

5. Consider the nonlinear equation for the function y[x]:

y =x H−y2L1 + y2

a) Write a procedure that solves this equation for y(x) and then returns the values of y(x).

b) Plot y(x) for 0 < x < 12.

c) Write a procedure that computes and returns the derivative ∑x y .

d) Make a plot of ∑x y for 0 < x < 12, and check that the derivative does correspond to the slope in the previous graph.

6. (adopted from [Zach 96]) If a is your age in years, w is your weight in pounds, and h is your height in inches, construct Boolean expression that will be True only when the following statements are true:

a) you are old enough to obtain a driver's license and you do not weigh 1000 pounds

b) you are not a teenager

c) you are either younger than 20 and less than 150 pounds, or older than 40 and greater than 6 feet

d) you are neither old enough to vote, tall enough to hit your head on a five-foot door frame, nor the right weight to box in the 132-140 pound division.

7. Let A be your age, Y the number of years you have been in college, and D the number of dollars you have in the bank. Construct Boolean expressions in Java that will be True when the following conditions are met:

a) you are a millionaire but you are not a senior

b) you are either too young to vote or you are not a freshman

c) you are either younger than 20 and broke, or older than 90 and have more than $100,000

d) you are 16 years old and your number of years in college is greater than the number of dollars you have in the bank

210 Landau, First Course in Scientific Computing

Copyright: Princeton Univ Press, RH Landau, 2005


Recommended