251 36 9MB
English Pages [156] Year 2015
SMath for Physics A primer Bernard V Liengme St Francis Xavier University, Nova Scotia, Canada
Morgan & Claypool Publishers
Copyright © 2015 Morgan & Claypool Publishers All rights reserved. No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without the prior permission of the publisher, or as expressly permitted by law or under terms agreed with the appropriate rights organization. Multiple copying is permitted in accordance with the terms of licences issued by the Copyright Licensing Agency, the Copyright Clearance Centre and other reproduction rights organisations. Rights & Permissions To obtain permission to re-use copyrighted material from Morgan & Claypool Publishers, please contact [email protected]. ISBN 978-1-6270-5925-1 (ebook) ISBN 978-1-6270-5924-4 (print) ISBN 978-1-6270-5927-5 (mobi) DOI 10.1088/978-1-6270-5925-1 Version: 20150301 IOP Concise Physics ISSN 2053-2571 (online) ISSN 2054-7307 (print) A Morgan & Claypool publication as part of IOP Concise Physics Published by Morgan & Claypool Publishers, 40 Oak Drive, San Rafael, CA, 94903, USA IOP Publishing, Temple Circus, Temple Way, Bristol BS1 6HG, UK
Contents Preface Acknowledgements Author biography 1 An overview of SMath Suite 1.1 What is SMath Suite? 1.2 How do I get SMath Suite? 1.3 How can I get help with SMath? 1.4 The SMath interface 1.5 Constructing regions 1.6 Greek characters 1.7 Option settings 1.8 Scratchpad calculations 1.9 Simple algebraic calculations 1.10 Subscripted variables 1.11 Working with units 1.12 Physical and mathematical constants 1.13 SMath functions 1.14 Matrices and vectors 1.15 Drawing graphs 1.16 Solving equations and finding roots 1.17 Symbolic differentiation 1.18 Programming 1.18.1 The If…Else structure 1.18.2 The For structure 1.18.3 The While structure 1.19 Snippets Appendix A. SMath functions 2 Introductory physics: some simple problems
2.1 Mass on a string 2.2 Kinetic energy of a merry-go-round 2.3 Telescope resolution 2.4 Dimensional analysis 2.5 Solving a cubic equation with polyroots 2.6 Conservation of energy 2.7 Stone dropped down a well (solve function) 2.8 Roller-coaster problem (function solve) 2.9 Bullet velocity 2.10 Water depth 2.11 Balmer series 2.12 Uncertainty calculation 2.13 Calculate the age of a rock 2.14 The ladder problem: search method 2.15 The ladder problem: solved with differentiation 2.16 Circuit analysis: matrix math 2.17 Thermistor quality control 2.18 Fourier series 2.19 Self-test projects 2.19.1 Centroid 2.19.2 Sound beats 2.19.3 Rigid structure analysis 2.19.4 Inflection points 2.19.5 Chart task References 3 Trajectory of a projectile 3.1 A simple calculation 3.2 An improved plot 3.3 Trajectory when drag is considered 3.4 Did we use a small enough Δt increment? 3.5 What is the purpose of the Eval function?
References 4 Linear regression 4.1 Simple linear regression 4.2 Zero intercept 4.3 Multiple linear regression 4.4 Multiple linear regression using a vector function 4.5 Multiple regression: some exercises Reference 5 Root finding 5.1 Fixed point iteration 5.2 Bisection method 5.3 The secant method 5.4 Newton–Raphson method 5.5 Self-test 5.5.1 Find a root 5.5.2 False position method Reference 6 Numerical integration 6.1 Simpson’s ⅓ rule 6.2 Simpson’s ⅓ rule with tabular data 6.3 Numerical integration using a Monte Carlo method Reference 7 Solving differential equations 7.1 The Euler approximation 7.2 Runge–Kutta method 7.3 Cooling by radiation 7.4 Runge–Kutta for systems of equations 7.4.1 Using vector functions 7.5 Second-order differential equations References 8 The SMath Viewer
8.1 The basic steps 8.2 A better GUI 8.3 Working with units 8.4 Adding tabs Reference 9 Data exchange with external files 9.1 Wfile and rfile functions 9.1.1 Write and read a single variable 9.1.2 Write and read a vector 9.2 The importData(9) function 10 SMath with Maxima 10.1 Saving options 10.2 The XY plot feature 10.3 Maxima’s equation solving functions 10.3.1 Solve function 10.3.2 Bisection function 10.3.3 FindRoot function 10.4 Golden section search 10.5 Linear regression 10.6 Symbolic integration 10.7 Data exchange (wfile and rfile) 10.8 Data exchange with Microsoft Excel® 10.9 Differential equations 10.9.1 The rkfixed function; example 1 10.9.2 The rkfixed function; example 2 10.9.3 The Rkadapt function 10.9.4 The Rkadapt function with a system of equations 10.9.5 The ODE.2 function 10.10 Statistics Reference
To our 10 wonderful grandchildren; may your futures be bright.
Preface The target audience for this book is mainly physics students and their instructors. While not quite as powerful as Mathcad, upon which it is modeled, SMath can be of great use to the physics student at any level. And the price is right—it is free. Furthermore, there is a mobile version than can be run from a thumb drive. This is a boon to students wishing to use school computers on which they lack the permission needed to install software. More information is given in the Overview chapter. The professional physicist can often justify the expense of the excellent symbolic mathematics applications like Mathematica, Maple, MathLab and Mathcad. But funds may not be available to let every technician have a copy. Again SMath can fill the gap. The author has kept the physics in the book at a fairly low level so that readers can concentrate on understanding the SMath features. The reader is encouraged to work through the Overview and Simple Physics chapters to master the fundamentals. As with all software, you learn by doing. So please experiment. After that, one can jump about as interest dictates. The SMath website can be a source of great help and questions can be posted on its forum—registration is required but you will not be inundated with spam. The author is happy to answer by email questions than may arise as you work through the book. Bernard Liengme St Francis Xavier University, Nova Scotia, Canada [email protected] http://people.stfx.ca/bliengme Note on typography: to avoid the confusion that often arises with the use of quotation marks, these have been kept to a minimum. The names of functions and variables (and occasionally, new terminology) are shown in italic. To indicate what a user should type, or to draw attention to statements in figures showing SMath pages, you will see, for example: The statement converts the data in the Temp vector from °C to Kelvin.
Acknowledgements The author thanks Andrey Ivashov (Андрей Ивашов) for his brilliant work in creating SMath Studio, and for the help he has given the author. Thanks also to Professors Martin Kraska (Brandenburg University of Applied Science) and Gilberto E Urroz (Utah State University) for their help with SMath. And great thanks to Pauline, my wife, for her encouragement and word skills.
Author biography Bernard V Liengme
Bernard V Liengme attended Imperial College London for his undergraduate and postgraduate degrees; he held post-doctoral fellowships at Carnegie-Mellon University and the University of British Columbia. He has conducted research in surface chemistry and the Mossbauer effect. He has been at St Francis Xavier University in Canada since 1968 as a Professor, Associate Dean and Registrar, as well as teaching chemistry and computer science. He currently lectures part-time on business information systems. Bernard is also the author of other successful books: COBOL by Command (1996), A Guide to Microsoft Excel for Scientists and Engineers (now in its 4th edition), A Guide to Microsoft Excel for Business and Management (now in its 2nd edition) and Modelling Physics with Microsoft Excel®.
IOP Concise Physics
SMath for Physics A primer Bernard V Liengme
Chapter 1 An overview of SMath Suite Throughout the book reference is made to SMath files in the form [LinearRegress1.sm], generally at the start of a paragraph. All these files are available here. Files with names ending with M, M1, etc. are functional only when opened with SMath with Maxima.
1.1 What is SMath Suite? [Overview1.sm.] The developers of SMath Suite call it a mathematical program with paper-like interface and numerous computing features. SMath has many of the features found in the expensive application Mathcad but differs in that SMath is free. Some of its features are shown in figure 1.1. The SMath user interface resembles that of Mathcad.
Figure 1.1. The SMath interface. Although the application is correctly called SMath Suite, it is normal to use just the word SMath. However, when doing an internet search always use the full name to avoid hitting sites dealing with an unrelated item.
1.2 How do I get SMath Suite? The website http://en.smath.info/ has downloadable files for a Windows and a Linus (Mono) installation. They are quite small: about 2 and 1 MB, respectively. The author has used SMath under Windows XP, 7 and 8.1. At the site http://smath.info/wiki/SMath%20with%20Plugins.ashx one can obtain a Windows portable version. Just download the 78 MB Zip file and expand it to a USB thumb drive. Now you can run SMath on any computer without having to do an installation. This will appeal to students who wish to run it on a university computer for which they do not have installation privileges. This unofficial version has been greatly enhanced by Professor Martin Kraska (University of Applied Sciences, Germany) who has added the Maxima plug-in. These enhancements can be ignored when using examples from this book, but see chapter 10. You can also run the ‘cloud’ version of SMath in your browser at http://smath.info/cloud/ but it is rather limited at the moment.
1.3 How can I get help with SMath? The official SMath site is http://en.smath.info/. At the top of the page you will find links to a forum where questions can be asked and answered, and to a Wiki which gives access to tutorials, example, and helpful documents. Here is a good way to do a Google search: polyroots site: http://en.smath.info.
1.4 The SMath interface As can be seen in figure 1.1, the SMath interface has a menu bar and a tool bar. Later we will see the SMath palettes. The work area on the interface is technically called a page, but you will also find it referred to as a worksheet. An SMath file holds one page. The File and Edit menu items contain the controls one expects in such menu items in a Windows environment. File has Save, SaveAs, Print, etc while Edit has Cut, Copy and Paste, etc. All the normal keyboard shortcuts (e.g. Ctrl+S for Save, Ctrl+C for Copy) work in SMath. The other items on the menu bar are discussed as we proceed. The asterisk in on the title bar indicates the file has not been saved since it was last edited. It should be noted that a file may be saved in its native format (note the extension sm) or as an image file (the default is png but the user can change the extension to jpg, bmp, or gif). There are other SaveAs options but we will look only at the executable file (exe)— see chapter 8. While one can easily print an SMath file, a student using SMath for an assignment might save several SMath files as images and then insert them into a Word file. This will give more control over pagination, headers and footers etc. The SMath Studio toolbar contains 21 icons (figure 1.2) which are briefly described below.
Figure 1.2. The SMath toolbar. 1. New page
11. Text color (of items to be entered)
2. Open (existing worksheet)
12. Background color (of items to be entered)
3. Save (current worksheet)
13. Control border (frames selected items)
4. Print (current worksheet)
14. Align horizontally selected items
5. Cut
15. Align vertically selected items
6. Copy
16. Function (insert a function)
7. Paste
17. Unit (insert unit)
8. Undo (recent action)
18. Reference book (see Help)
9. Redo (recent action)
19. Recalculate page
10. Font size (of selected items on page)
20. Interrupt process 21. Show/hide side panel
Items (1) through (4) manipulate new or existing worksheets. Items (5) through (7) are well-known editing functions. Items (8) and (9) will undo and redo the most recent action. Items (10) through (12) adjust font or background properties—see Construction Regions below. Item (13) allows you to put a frame over an entry; for example, to show a solution to a problem. Items (14) and (15) re-align selected cells. Items (16) and (17) open the Function and Unit menus, which are also available in the Insert menu. Item (18) is also available under the Help menu. Items (19) and (20) are also available in the Calculation menu. Item (21) shows or hides all the palettes on the right-hand side of the page. The palettes (figure 1.3) contain mathematical, graphical, and programming functions that can be placed in the main window. Each palette may be condensed or expanded on the tool on its header ⊡. The panel containing the palettes may be toggled on/off with the last item on the toolbar.
Figure 1.3. The palettes. We will briefly explore some of these palettes and what they contain. Note that allowing the mouse pointer to hover over an item causes its name to be displayed. As expected, the π tool inserts that symbol; this is one of SMath’s numerical constants with the value 3.12…. The square roots tool is readily identified; the keyboard short cut is . Similarly, one can see the multiplication operator × but most users will type *. In either case, SMath converts the operator to a middle dot, as in To assign a value to a variable or to define it in terms of other variables the definition/assignment operator := is used. This is the penultimate icon on the Arithmetic palette but normally the user types just a colon (:) and SMath converts it to the operator. The Functions palette contains only a few of the functions available from Insert |
Functions. The iconic tools for summation, product, differentiation, and integration are very useful. Items in the Matrix and Programming palettes are discussed later. The two Symbols palettes enable the user to insert Greek letters into a page. The alternative method is to type the Roman letter followed by Ctrl+G to convert it to Greek.
1.5 Constructing regions There are two types of regions: text and math. In figure 1.1, the phrases Simple math, Root finding, etc are text regions while the assignment of a value for x (as in ) is a math region. As you move the mouse around, you will see a red cross on the page; this is the insertion point and anything you type (or insert using a palette) will begin at that point. There are some exceptions for operators inserted from a palette. In addition to the two types of regions, it is possible to construct plots and to paste images onto an SMath page —figure 1.1 shows a plot and an inserted image. Note that SMath is ‘top down’ (you cannot refer to a variable before it is defined) so the plot of g(x) is about as high up the page as it can be. The screen captures below may help you understand the comments in the next three paragraphs.
To make a text region either use the command Insert | Text Region or begin the text with a double quote which will not be recorded. If you just start typing some text, SMath will recognize it as a text region when you enter a space. As soon as this happens a small yellow box appears to indicate your language. To start a new line in a text region use Shift+Enter rather than just Enter. Looking at the top line in figure 1.1 we see definitions for three variables (x, y and ans). Recall that we can begin the last one either by typing ans: or by typing ans and then clicking the definition operator (:=) in the Arithmetic palette; in each case we have a partial definition with a place holder. Again we have two options: (a) we could enter the numerator (x − y)2, then the division operator and type the denominator x, or (b) use the division operator to give the template shown here and then add the numerator and denominator. The trick in constructing and editing formulas is to watch the poistion of the insertion symbols ⌊ and ⌋. Once a variable has been defined it will appear in the dynamic assistant. So if we begin to type an we will see the definition for ans. To copy, move or align one or more regions begin by clicking to one side of a region and then drag the mouse to select all the required regions. Use the Ctrl key to select non-
adjacent regions. When the mouse button is released just the regions are shown as selected. Now you can drag to a new position, use one of the alignment tools or issue the Copy command (Ctlr+C is the easiest way). The same selection method can be used to give one or more regions a border, a background colour or a different font size. A region selected in this manner can be copied by holding down the Ctrl key as you drag the region. Text regions can be made bold, underlined and/or italicizied—these effects will apply to the entire text; one cannot enhance just part of a text region. Do not confuse the selection method here with clicking and dragging inside a region to make it dark blue.
1.6 Greek characters Greek characters (for use in text or math entries) may be entered either: (a) by clicking on the appropriate symbol in the palette, or (b) by typing the Roman letter (see table 1.1) followed by Ctrl+G. Thus D followed by Ctrl+G gives Δ. The symbol π (pi) may be inserted as p followed by Ctrl+G; from the symbol or arithmetic palette, or with Ctrl+Shift+p. When inserted into a math area π (pi) will have the value 3.14 159 265…. Table 1.1. The Greek alphabet. Lower case
Upper case
Name
Roman letter
Lower case
Upper case
Name
Roman letter
α
Α
alpha
a
ν
Ν
nu
n
β
Β
beta
b
ξ
Ξ
xi
x
γ
Γ
gamma g
ο
Ο
omicron o
δ
Δ
delta
d
π
Π
pi
p
ε
Ε
epsilon
e
ρ
Ρ
rho
r
ζ
Ζ
zeta
z
σ
Σ
sigma
s
η
Η
eta
h
τ
Τ
tau
t
θ
Θ
theta
q
υ
Υ
upsilon
u
ι
Ι
iota
i
ϕ
Φ
phi
f
κ
Κ
kappa
k
ψ
Π
psi
y
λ
Λ
lambda l
χ
Χ
chi
c
μ
Μ
mu
ω
Ω
omega
w
m
The reader may wish to skim through the rest of this chapter and return to it when using a particular SMath feature.
1.7 Option settings The Tool menu item has an Options item which leads to the dialog shown in figure 1.4. Most of these are self-explanatory. All these settings apply to the entire page and will be used next time the user starts SMath. We have seen that a text region can be individually formatted. The decimal and exponential threshold setting for a math region displaying a number can also be altered on an individual basis. Suppose, with the decimal places set to 8 and exponential threshold at 5, we see on a page . We can select the region by left clicking, then by right clicking bring up a menu from which Decimal places may be chosen; this leads to the dialog in figure 1.5. The process can be repeated to change the exponential threshold to 1. Now we have .
Figure 1.4. The Options dialogs.
Figure 1.5. Change the decimal setting for one region.
1.8 Scratchpad calculations The reader is encouraged to treat this section as an exercise by typing what is shown in the left hand column on a new SMath page, observing the movement of the insertions symbol ⌋ and to see why the results in the right hand column are obtained. The symbol → is used to denote the right arrow key or the spacebar. 1 + 5/6 + 7/8
,
1 + 5/6→ + 7/8 On the SMath page, left click the result above, then right click and select Fractions followed by Fractions. See if you can get the first result rather than the second.
1.9 Simple algebraic calculations It must be emphasised that SMath is case sensitive. So a variable defined as v and another as V are totally different items. The reader is advised not to use π or e as variable names as these are defined in SMath as mathematical constants—see below. Also it is recommended not use the single letter i for a variable name but to reserve its use for the imaginary number √−1. The use of the single letter l is discouraged as it is easily confused for the digit 1.
[Overview2.sm.] Figure 1.6 shows an SMath page with some simple definition and display math regions. As a warm up to delving deeper into SMath, the reader is invited to recreate such a page, perhaps with the explanatory text omitted. Note how typing a: results in a:=. When you type c:a*b, the conversion to c := a·b is instantaneous.
Figure 1.6. Some simple math operations. Experimentation is encouraged: 1. Change the global decimal place setting and the decimal setting for an individual region. 2. Can d be displayed as a fraction? 3. Find other ways to obtain the √ operator. 4. Have you mastered the two alignment tools? 5. When you drag the d = 0.8 region up the page it becomes d = ▪ with a red border; why? 6. Is there another way to compose the x assignment? 7. Can you change the value of b without retyping the entire assignment? 8. Click on z = 4.79 then right click and from the popup menu use Optimization | Symbolic. 9. Experiment with unchecking the AutoCalculation in the Calculations menu item. Then change the value of a. Does anything happen to the other displayed values? What does F9 do? Remember to put AutoCalculation back on. 10. Type z→ using the arrow in the Arithmetic palette. This tells SMath to use symbolic representation. Note that the arrow becomes =. Some documents on the SMath website show the arrow being displayed but this has been changed in the newer version of SMath. 11. The √ symbol in the text region was pasted from a Word document. Try copying some math regions from the SMath page to a Word document; here is an example .
1.10 Subscripted variables It is convenient in many problems to use variable names such as x1 and x2 to emphasize their similarities. To achieve the user types where [dot] indicates the period (full stop) key. Later in this chapter we will discuss indexed variables— elements of vectors and matrices. These are constructed in a different manner and (if one looks close enough) have a slightly different appearance.
1.11 Working with units [Overview3.sm.] This topic will be demonstrated with a simple hydrostatics problem. Water is pumped at a constant rate r = 6 m3 min−1 through a pipe. The pipe diameter near the pump is 20 cm but this widens to 40 cm at the end. Find the velocity of the water at the discharge point. We reason that, since water is incompressible, the rate of flow at any point in the pipework is constant. So r = v1·A1 = v2·A2 where v is the velocity and A the cross-sectional area. Figure 1.7 shows the page for this calculation.
Figure 1.7. Example of a calculation with units. There are several way of entering units. Method (a): suppose we have typed and the region is still active. From the menu bar use Insert | Units to bring up the dialog shown in figure 1.8. Note how the left panel shows various categories but we have selected All. In the Quick box we entered meter (note the US spelling). Now in the right hand panel we can select centimeter (cm) and click the Insert button, or we can double click the cm entry in the dialog. In either case the dynamic assistant pops up so we tap the Tab key to confirm we want this unit. Method (b): now we have typed and wish to add the cm unit. We type a single quote (‘) and this causes the units menu to pop up; we type cm and this locates the desired unit and we confirm with the Tab key. Note that when the user types the single quote, SMath adds a place holder but it is more oval than the normal rectangular place holder.
Figure 1.8. The Units dialog.
The progression to get is: after typing , insert the m unit and then use . Now insert the min unit and use . While units are shown in blue, any exponent for a unit is not. Note how SMath looks after unit conversion. We have centimetres and minutes in the data but the result show metres and seconds. SMath always shows standard SI units in numerical evaluation regions. However, as seen in figure 1.7, we can override this. Click on a region displaying , use the right arrow key to get to the far right of the region, and then use the single quote to indicate that you wish to add units, and add the required units. If you enter inappropriate units, the regions will show no numeric value and will have a red border.
1.12 Physical and mathematical constants [PhyConst.sm.] SMath has a number of built-in physical constants and two mathematical constants (π and e). These are shown in figure 1.9. All of the physical constants are to be found using the same techniques as adding a unit. In the left panel of the units dialog (figure 1.8) there is a group called Physical Constants within which the first six physical constants may be found. The others are in groups as shown in the figure. Of course, the All group contains every one.
Figure 1.9. SMath’s physical and mathematical constants. Clearly, the current version of SMath has trouble displaying the correct units for Boltzmann’s k, the gas constant Rm, and the Newtonian gravitation constant GN. However, SMath ‘knows’ the correct units and displays them in the dynamic assistant and uses them in calculations. To insert a physical constant symbol into a math region use the same techniques as for unit. So to get the region shown to the right, after typing the , the user typed ‘ (single quote to indicate a unit is needed), to locate the items beginning with g, a period to indicate a subscript in preparation for typing an . As it turns out, there was no need to add the since the dynamic assistant located . All that remained was to tap the Tab key to confirm the choice.
If you use π or e in a formula without assigning a value then the values shown in figure 1.9 are used. If values are assigned, they will override the built-in values. It is recommended that values not be assigned to either π or e.
1.13 SMath functions SMath contains a large number of predefined, or intrinsic, functions for both real and imaginary numbers. We will not discuss the last group. The complete list of functions can be found in Appendix A. The entire collection of functions is accessible from the Insert Function dialog (figure 1.10) which is accessed by the menu command Insert | Function or by clicking the f(x) tool. It is worth noting that the dialog provides a brief description and
syntax for a selected function. An alternative way of inserting a function is to type the function name (or part thereof) and let dynamic assistant help you to get it right.
Figure 1.10. The Insert Function dialog.
A user wishes to define x with . Method (a): after typing , he clicks the f(x) tool, locates the ln function in the Insert Function dialog, which he double clicks, or he clicks the Insert button. Unfortunately, the Insert Function dialog has no Quick Search facility, so you must scroll all the way through. The task is shorter if you correctly guess what group to use from the left panel. Now he has the template shown above. Alternatively, since he knows the name of the function, after typing the he types and up pops the dynamic assistant. He commits his choice with the Tab key. Note that in the dynamic assistant functions are shown in purple while units are blue.
1.14 Matrices and vectors [MatrixMath.sm.] A matrix is constructed by clicking the first icon in the Matrix palette or by using the shortcut Ctrl+M. This bring up a dialog where one specifies the number of rows and columns; following this the matrix elements are entered into the place holders. The sequence is shown in figure 1.11. A vector is constructed in the same way, i.e. as a one column matrix.
Figure 1.11. Constructing a matrix. An alternative way of constructing a matrix is to type , which generates a 2 by 2 matrix template. By clicking on either of the matrix brackets one can have SMath present a fill handle in the lower right corner; dragging this can expand the rows and/or columns to the required number. At the bottom of figure 1.11 we see how to reference a matrix element: type to make this math region. Note the use of [ to get an index compared to [period] to get a subscript. There is more white space between the matrix name (A) and the first index (3) than there would be if we had a variable A with a subscripted 3. Some simple matrix math is demonstrated in figure 1.12. In a later chapter we see how to use matrix math to solve a system of equations.
Figure 1.12. Examples of matrix math.
[Vector.sm.] The range functions may be used to generate vectors with numerical elements as seen in figure 1.13. Coupling this with the augment function we can define a matrix—see figure 1.14. range(start, end): shows up in the worksheet as start..end, and produces a vector whose elements are start, start+1, start+2, … end. range(start, end, start + increment): shows up in the worksheet as start, start + increment … end, and produces a vectors whose elements are start, start + increment, start + 2 increment, etc. The last element is the lowest value smaller than end by less than increment.
Figure 1.13. Using the range functions to define a vector.
Figure 1.14. Using augment to make a matrix. The cross product of two three-element vectors (X and Y) is found with where the × operator is the last item on the Matrix palette.
,
[VectorMath.sm.] SMath has problems with symbolic evaluation of vector math and incorrectly applies the scalar rules for commutation and distribution. If in doubt, use numerical optimization with vectors and matrices.
1.15 Drawing graphs SMath has limited graphing facilities; they are useful only for personal work or, at a pinch, for internal reports, but not for publication work. SMath can generate two- and threedimensional graphs. We will explore only the 2D graphs. For more information on graphing see http://smath.info/wiki/Graphs.ashx. In section 10.2 there are notes on the XY Plot function in SMath with Maxima. [Graph1.sm.] We begin with a very simple example: a plot of a cubic function—see figure 1.15. 1. Click on the point in your worksheet where the upper left corner of graph will go. 2. Use the Insert | Plot | 2D menu option. Alternatively, use the keyboard shortcut of typing @. 3. Type the function in the place holder in the lower left corner of the graph. 4. Use the mouse wheel to rescale both axes. Drag the centre of the plot to keep the zone of interest (where we see the three roots) visible. 5. Resize the plot by dragging one of its fill handles.
Figure 1.15. Plotting a function of x. When using this method, we must use a function of x; no other variable name will work. Furthermore, we have no control over the range of x-values; we address this in later chapters. The methods for modifying a graph are listed below; you must first ‘activate the graph’ by clicking on the graph so that the handles are displayed: 1. Drag one of the handles (small solid squares) to resize the graph. 2. Drag the mouse pointer to reposition the origin. 3. Scroll the mouse wheel to rescale both axes. 4. Scroll the mouse wheel while holding down CTRL to rescale the y-axis. 5. Scroll the mouse wheel while holding down SHIFT to rescale the x-axis.
Sometimes when you plot a function the graph appears empty. In such cases it is necessary to rescale the graph to find the plotted data. Try plotting x2 + 75x − 2500; you will see nothing until the x scale is about ±64 and the y scale ±1024. At the time of writing, SMath (version 0.97.5346) has a problem with certain high resolution Microsoft wireless mice (model 4000, for example). The plot scales increase regardless of the direction of rotation of the wheel. A fix for this problem is planned. To relocate the graph on the page: click outside the graph and drag the mouse until the graph is selected (blue background with default setting); now drag it to new position. To copy or delete a graph you need to select it in the same way. Alternatively, a graph (or any region) can be moved by dragging it by the outside frame when the mouse pointer is a four-pointed arrow. [Graph2.sm.] Two or more functions can be plotted on one graph (figure 1.16) by using the multiple values tool—it is the last one in the Functions palette. What is produced is sometimes called a list. The list may be external to the graph or used in the graph place holder. When you click on the tool a template with two place holders is displayed. To add more items to the list, click on the brace { and drag the resulting fill handle (lower right corner) down. Items can be deleted by dragging it up.
Figure 1.16. Plot of two functions. [Graph3.sm.] Figure 1.17 has five functions plotted and gives some idea of the colours
used by SMath with blue being used for the first function.
Figure 1.17. Plot to show colours used by SMath. [Graph4.sm.] Figure 1.18 demonstrates how to add text and points to a graph. The variable plottext is a 2×5 matrix: the first two elements in a row specify the starting position (x, y), then the text to be displayed, followed by the font size and colour. Similarly, in each row of the 7×5 matrix Points we have: x-position, y-position, symbol, font size, and colour. See the note below regarding the symbol.
Figure 1.18. Adding texts and points to a graph. SMath offers over 140 colour choices from aliceblue to black—see http://en.smath.info/forum/default.aspx?g=posts&m=3663. A misspelled colour name will result in black being used. It is not possible to type the = symbol within a text element in a vector; the = symbol in y = mx + b was produced with Alt+205.
[Graph5.sm.] The plotG function, which was made available by Professor Radovan Omorjan in the SMath Studio forum, is illustrated in figure 1.19. The program takes vectors of values (x, y) and creates a plot matrix for the data using a specified character (char), size, and colour. The plotG function saves us the work of making a matrix similar to Points used in the previous example. The vectors x and y could represent experimental data and yline is the equation of linear best fit. The syntax for using this is Variable := plotG(xdata, ydata, char, size, colour); then Variable is used in one of the plot place holders. The reader may wish to experiment with different characters, sizes and colours. For the value of char, use only one of: the period character which displays as a solid circle; the lower case character o which displays as a circle; x which displays as a cross; the asterisk (*) which displays as a star. Other characters are plotted incorrectly —too low and too far to the right.
Figure 1.19. The plotG function. It is suggested that you copy and paste the plotG function from the file Graph_PlotG.sm rather than try to code it. Also refer to section 1.19 to see how to make a snippet to allow the plotG function more readily accessable.
[Graph.sm.] If we have a function such as defined on an SMath page and enter f(x) in the plot’s place holder, then we have no control over the domain used by the plot. This can be rectified using the augment function. This method is explained in figure 1.20.
Figure 1.20. Using the augment function to plot.
1.16 Solving equations and finding roots When we speak of solving an equation we mean finding the value(s) of x that satisfy the equation f(x) = g(x). For example we might wish to know what value of x gives the function exp(x2 + x) the value of 10. When we speak of finding the roots of f(x), or finding the zeros, we mean finding what values of x makes f(x) = 0. [Quadratic.sm.] We will start this topic by finding the roots of a simple quadratic equation. In figure 1.21 the bordered text box shows the equation whose roots we seek, but the expression is not used in the calculation; rather we use the values of the coefficients a, b and c as entered in the first row. The familiar quadratic equation is entered; observe the ± which is obtained from the Arithmetic palette. Since, in general, a quadratic has two roots, when is used to display the roots then multiple values (a list) result. The figure shows that plugging each value into the second order equation gives the result zero, proving we have the roots; note that an element in a list is referenced in the same way as in a vector—using an index not a subscript. So to display the value of x1 we type note how on the SMath page there is white space between the x and the 1, denoting an index.
Figure 1.21. Finding roots of a quadratic equation. By changing just the values of a, b and c, the reader might wish to find the roots of 9x2 + 12x + 4 and x2 − 9 to see what happens when there is one root, and 3x2 + 4x + 4 which has a negative discriminate and hence has imaginary roots. [Polyroots.sm.] The polyroots function is demonstrated in figure 1.22 where the roots of a quadratic (x2 + 3x − 18) and of a quartic function (x4 − 15x2 + 10x + 24) are found. In the first example the user typed to make the template (▪). Then the place holder was converted to a vector (Ctrl+M brings up the required dialog and a 3×1 matrix—a vector—was specified) and the coefficients of the equation were entered starting with the coefficient for x° (i.e. the constant). The results are presented in vector form. Of course, we get the same roots as before for this quadratic. In the second example, a vector was made first and this was referenced in the polyroots template. The fourth element in coeff is zero since the quartic of interest has no x3 term. It was simpler to define a function to show the correct roots had been obtained.
Figure 1.22. Demonstrating the use of the polyroots function. The polyroots function uses an analytical method to generate results that are accurate to within the precision of SMath (15 decimal places). The next two functions we will look at, roots and solve, use numerical approximation methods. The reader may be familiar
with methods such as Newton–Raphson, secant, bisection, etc; a concise review of numerical methods can be found at http://www.maths.dit.ie/~dmackey/lectures/Roots.pdf. [Roots.sm.] Normally we would use polyroots to find the roots of any polynomial but for the sake of comparison in figure 1.23 we use polyroots, roots and solve to get the roots of the cubic equation x3 − 2x2 − 3. The polyroots function finds three roots, only one of which is real. The functions roots and solve give only real roots.
Figure 1.23. Comparing polyroots, roots and solve. The syntax of roots is either
or , where each argument is either a variable or each is a vector. Our example uses variables with as the function whose roots are sought, the variable to find, and, in the second and third cases, we have a number (3) to give roots a guess at the root. Our f(x) has only one real root but had there been three, the results would have been displayed in vector form, as we see below. Looking at the first and second examples of roots it is clear why one is always encouraged to provide a guess—i.e. to use the three-argument form. The third example, with rather than a simple , is there to demonstrate a very important point. Figure 1.24 shows what happens when the second argument has been given a numerical value prior to being used within root. The calculation in the second example fails but the third example still works. The reader is encouraged to experiment. If you delete , you may need to press F9 to recalculate the SMath page. So why Many SMath users employ a variable like rather than in a roots evaluation since it is unlikely that such a variable will have been used before in the page. Others employ a variable similar to . You will see both in examples on the SMath website.
Figure 1.24. The roots function fails when argument-2 already has a numerical value. The second argument in a roots evaluation cannot have been given a numerical value in any statement prior to the roots calculation. [Roots2.sm.] Figure 1.25 demonstrates another example of the use of roots: to find the roots of a transcendental equation.
Figure 1.25. Finding the roots of a transcendental equation. [Roots3.sm.] Figure 1.26 demonstrates the use of roots to solve a system of linear equations. In the upper part, the vectors are used for the three arguments; in the lower part the vectors are defined beforehand and are referenced by the arguments. In a later chapter we see how matrix math can be used to solve a system of equations.
Figure 1.26. Solving a system of linear equations. [Roots4.sm.] Unlike the matrix method, the roots function method allows us to tackle systems of nonlinear equations, as shown in figure 1.27.
Figure 1.27. Solving a system of nonlinear equations. [Solve1.sm.] In figure 1.28 the solve function is used to find the roots of the same function that was solved with the roots function in figure 1.25. Solve has the advantage of locating all the real roots in one operation and returning them in a vector. In the top part of figure 1.26 solve is used in the two-argument form solve(function-to-solve, variable). In the lower part we have the four-argument form solve(function-to-solve, variable, lower-
limit, upper-limit).
Figure 1.28. Finding roots with the solve function. [Solve2.sm.] The two-argument form of the solve function is sensitive to the last setting in Tool | Options | Calculate (see figure 1.4). This is demonstrated in figure 1.29. Normally a polynomial is best solved with polyroots but the quadratic here serves as a convenient example to make the point being made.
Figure 1.29. Solve response to the roots range setting. [Solve3.sm.] So far we have been finding roots, i.e. we have found x such that f(x) = 0. In the next example (figure 1.30) we see how to find x such that f(x) = Q where Q is some numerical value. A Boolean = must be used in the expression within solve.
Figure 1.30. Solving for a non-zero value of f(x). Things to remember when using the solve function: 1. The solve function cannot be used with units of measurement. 2. If the statement is enclosed in a red border and the message ‘No real roots’ appears when the mouse point hovers over the statement, then the user should experiment with various values for the third and fourth arguments—the lower and upper values of the range in which a root is sort. 3. When the first argument is an equation (e.g ) it is imperative that the equal sign be inserted from the Boolean palette.
1.17 Symbolic differentiation [SymbolicDiff.sm.] The more advanced applications like Mathematica, Maple, MathLab, etc can perform various symbolic manipulations. SMath is limited to being able to do symbolic differentiation. Some examples are shown in figure 1.31.
Figure 1.31. Examples of symbolic differentiation. The first-order differential template is found on the Function palette or can be generated by typing and accepting from the dynamic assistant. The second-order template is generated by typing and accepting from the dynamic assistant. The → tool on the Arithmetic palette is used rather than the = from the keyboard to specify symbolic evaluation; the shortcut is Ctr+period. An earlier version of SMath displayed the → symbol rather than the = symbol but the current version converts it. Recall that if a math region is right clicked and the Optimization item is selected, the user can specify the type of evaluation. It is to be hoped that every physics student is familiar with www.wolframalpha.com and its free mathematics services—see figure 1.32.
Figure 1.32. A sample from Wolframalpha.com.
1.18 Programming Computer scientists speak of programs being constructed from three structures: sequential, branching (aka decision or conditional), and looping. In a sequential structure each statement is executed one after the other; in SMath this means from left to right and from top to bottom. SMath has one way to make a branching construct and that is the If… Else. SMath does not have the case construct found in many computer languages. There are two looping constructs: for and while. The for construct is used when one knows how many times some code is to be repeated; the while construct is used to loop until some condition is met.
1.18.1 The If…Else structure [IfElse.sm.] Figure 1.33 illustrates an If…Else construct. The template is generated either by clicking if in the Programming or by typing and accepting the construct from the dynamic assistant. There may be occasions when nothing is to be done in the else area. One option is to enter a ‘O’ but the word “continue” in quotes is more meaningful. Do not use the continue item from the programming palette.
Figure 1.33. An example of the If…Else structure.
Very often we need more than one statement to be executed after the or the condition. We can get this using the line command from the Programming palette. The sequence is shown below.
1. Start with the basic template; fill in the first place holder. 2. Click on the inner place holder—the second or the third. 3. Click on line in the Programming palette. 4. Click on the line to reveal a fill handle in the lower right area. 5. Drag this down as far as needed; drag up if you go too far.
1.18.2 The For structure [CubeAddition.sm.] Figure 1.34 shows an SMath page which (a) sums the cubes of the first 12 integers, and (b) sums the cubes of the even numbers up to 12. The second part is done with two forms of the ranges in the for construct. We also see that SMath has a summation tool that makes all the work in (a) unnecessary!
Figure 1.34. Examples of for loops.
∈ ∈
Means vary j from 1 to 12 in increments of 1. Means start with j = 2, increment by 2 (since the difference in the first and second arguments is 2, i.e. 4 − 2 = 2) while j is less than or equal to 12.
⩽
Means start with j = 2, and while j is less than 12, increment j by 2. NOTE: you must use the Boolean = in .
The second and third constructs are equivalent, but the author finds the meaning of the third one to be clearer. In these constructs, j is referred to as the loop variable. Programmers take great care never to explicitly change the value of a loop variable other than in the opening code of the for loop. [CubeAddition.sm.] There is another variation of the for structure that uses no loop counter. It is used only in conjunction with vectors and matrices. Figure 1.35 shows an example: again we are summing the cubes of the even numbers from 2 to 12. The code for ∈ may be thought of as ‘for every element in vector V’. The name elem is unimportant, any valid name may be used.
Figure 1.35. Example of the for-every-element.
1.18.3 The While structure [CubeAddition.sm.] Figure 1.36 shows an SMath page using while loops to sum the cubes of the natural numbers but not to exceed 1000. Clearly in the left hand side, the sum was exceeded. Indeed it could not have been otherwise since the test (sume ⩽ 1000) only fails when the sum exceeds the limit. So the programmer had to subtract the last j3. This is avoided in the code to the right where we have an if constructed nested within the while. Note the use of to exit the loop.
Figure 1.36. Examples of while loops. When coding a while loop is it easy to make a mistake that causes the loop to run for ever—the exit condition is never satisfied. You will see a green border around the code that is being executed and the timer in the status bar keeps increasing. Press the Esc button and accept the invitation to cancel the calculation! While you are working in a program structure, be careful to avoid typing the evaluation operator (=) when a definition operator (:=) is required. This mistake will result in egregious place holders in the top right corner of the structure and only after patient work with the delete, backspace and arrows keys will you have workable code.
1.19 Snippets It may be helpful when a user finds he is repeating a particular piece of code in many worksheets, to place this code in a snippet. When SMath Studio is installed there are already two snippets available. These allow the user to readily work in degrees or in grads rather than in radians. In figure 1.37 the top part shows the calculation of some
trigonometry functions; the last item in each row was given the symbolic optimization— either type = and then by right clicking the region, set the optimization to symbolic, or use the shortcut Ctrl+period in place of the =.
Figure 1.37. Using the Degrees snippet. In the centre of the page there is a line with the notation Evaluation in Degrees, and under that some more calculations but this time with arguments in degrees not radians. Clicking the ⊞ at the left of the line will reveal the code that allows for this. To add the hidden code to the worksheet, click the place where the code is to added (look for the red cross), open the dialog shown in figure 1.38 using the command Tools | Snippet Manger, then double click the required snippet.
Figure 1.38. The Snippet Manager dialog. The reader may be wondering how code gets added to the Snippet Manager. The process is relatively easy; here is a concrete example for a user wishing to add the plotG
function as a snippet (figure 1.39). a) Open a file with the function; Graph_PlotG.sm for example. b) Copy and paste just the plotG function to a new page. c) Save the new file as plotG.sm on the desktop, and close SMath Studio. d) Using Windows Explorer (aka File Manager) move the new file from the desktop to the folder C:\Progam Files (X86)\SMath Studio\snippets. Windows will prevent the user who attempts in step (c) to save directly to the snippet folder, hence the workaround of first saving it elsewhere. For those with the portable version of SMath Studio a direct save is recommended. [SnippetExample2.sm.] The steps to use the new snippet are the same as before. The advantage of having the plotG snippet is being able to find the code quickly and make tidy worksheets where the plotG function is hidden and therefore is not obtrusive.
Figure 1.39. plotG used with a snippet.
Appendix A. SMath functions
IOP Concise Physics
SMath for Physics A primer Bernard V Liengme
Chapter 2 Introductory physics: some simple problems This chapter will look at SMath solutions to some Physics 101 level problems. The purpose is to familiarise the reader with SMath by solving problems that could readily be done with pen, paper and calculator. Hopefully, the physics student and his instructor will see the merits of SMath as a tool for completing and submitting assignments. The professional physicist may wish to use this chapter to gain familiarity with SMath features. Some of these problems are adaptations from [1].
2.1 Mass on a string [Rotation.sm.] Figure 2.1 shows a rather simple problem solved with appropriate units. The text was added with the command Insert | Text. The diagram was taken from a website using the Windows Snipping tool and pasted into the SMath page. Assignment code such as was started with , then typing the letter brought up the dynamic assistant from which the s (second) unit was selected and inserted into the code using either a double click or by tapping the Tab key. The exponent was added as . On pressing Enter, or clicking a blank area, SMath converted the entry to that shown in figure 2.1. The last result (r = 18.29 cm) was obtained by first typing . SMath immediately displayed the result shown below.
Figure 2.1. A simple physics problem solved.
Figure 2.2. Rotational kinetic energy.
Figure 2.3. Telescope resolution. The user clicked in the place holder, typed cm and selected the cm unit from the dynamic assistant. SMath displayed r = 18.2859 cm since, when the page was developed, the number of decimals had been set to 4. The user selected the math region, right clicked it, selected Decimal Settings from the popup menu and used the value 2.
2.2 Kinetic energy of a merry-go-round [RotationKE.sm.] The second problem (figure 2.2) requires the computation of the kinetic energy of a rotating body given its mass, radius, and rotational speed. Note how SMath looks after the unit conversions. The value of KE is displayed twice. After typing the second time, the math region was selected, right clicked, Exponential Threshold was selected from the popup menu and set to 3. In a similar way the Decimal Places value was set to 2. Note how there was no need to compute either ω or I to get KE; their values are displayed at the end for completeness. As an exercise, see if you can make SMath display KE = 1.68 kJ.
2.3 Telescope resolution A telescope is used to observe, at a distance of 10 km, two objects which are 0.12 m apart and illuminated by light of wavelength 600 nm. Estimate the diameter of the objective lens of the telescope if it can just resolve the two objects. The pen-and-paper approach to this starts with: (a) Rayleigh’s criterion for the angular resolution Δθ of a circular aperture of diameter D when D ≫ λ is: Δθ = 1.22 λ/D and (b) the simple geometric approximation Δθ = s/z that is acceptable when s ≪ z. From these a substitution and a rearrangement gives D = 1.22 λz/s. Before replacing variables by numbers, care would be needed to convert to consistent units. The approach in figure 2.3 does use a rearranged Rayleigh criteria, but it leaves the substitution and consistency of units to SMath.
Figure 2.4. Dimension analysis.
2.4 Dimensional analysis A student is of the opinion that, in a particular problem, the pressure P can be computed using the formula where ρ is a density measurement, h a height measurement and
g the gravitational acceleration. He makes the simple SMath page shown in figure 2.4 and finds that the units for P are unacceptable thus invalidating his formula. When the user typed and tapped the Enter key, he was rewarded with the value and units shown under Compute P… . When he typed P the second time, the page displayed what is seen at the bottom of figure 2.4. The user moved to the place holder, typed Pa (for Pascal) and accepted this from the dynamic assistant by tapping the Tab key. Clearly, his units do not convert to Pascal so his formula is invalid.
2.5 Solving a cubic equation with polyroots [Polyroots.sm.] You have been asked to find the roots of From the Overview chapter you recall that polynomials are best solved with the polyroots function; and that the argument of this is a vector listing the polynomial’s coefficients starting with the coefficient of x°—i.e. with the constant. The SMath page is shown in figure 2.5. Be sure you check that for each root r, f(r) = 0; you are satisfied with the results that are in the 10−14 region as being zero. Finally you look at the values 1.4142 and 1.7321 and recognize that these could be √2 and √3; you check this. You can now report that the roots are ±√2 and −√3.
Figure 2.5. Using polyroots to solve a cubic equation.
2.6 Conservation of energy [PumpWater.sm.] An electric pump, with an efficiency of 80%, pumps water from a 50 m deep well, discharging the water at 2 m3 s−1 with a velocity of 10 m s−1. What power does the pump draw? The law of conservation of energy tells us that if W is the energy used by the pump per second, then W = kinetic energy gain by the water (½ m v2) + potential energy gain by the water (mgh). Recalling that the density of water is 10 kg m−3, we can convert the flow to mass of water moved in a second. Note in figure 2.6 how we computed with := and displayed with = in one piece of code. Once we have found W we can make allowances for the 80% efficiency—the units for P were converted from W to kW and the number of decimal places was made zero.
Figure 2.6. Pumping water.
2.7 Stone dropped down a well (solve function) [StoneInWell.sm.] A stone is dropped down a well and takes 2 s to hit the water. At what speed must the stone be thrown to hit the water in 1 s? For this problem we will make movement towards the water positive. To the right in figure 2.7 we see a possible pen-and-paper solution. Note the genuine error the author made and had to correct! First h is found for the 2 s event. This value is used to compute v in the 1 s event. Some simple algebraic rearrangment is needed.
Figure 2.7. Stone dropped in well problem. The SMath approach is to define a function h(v, t) that computes the distance moved in t s with initial velocity v. We get solve to find what value of v makes h(2, 0) equal to h(1, v). The author has been careless and used the two-argument form of solve. He was lucky that the result was within the range set in Options (the default being ±20); we pick up on this in the next problem. The solve function does not work when the variables have units. This means we must define g rather than use the built-in ge constant which has units.
2.8 Roller-coaster problem (function solve)
[Rollercoaster.sm.] A roller-coaster climbs to the height of 50 m and has a velocity of 0.5 m s−1. It plunges to a point with elevation 5 m before climbing to another point of inflection at 20 m. What are the velocities at the two points? Our solution will again be based on the law of conservation of energy. This time we have:
The pen-and-paper approach would be to cancel out all the m symbols, rearrange to get two equations with v on the left and known values on the right, and compute. The SMath approach (figure 2.8) is to use the solve function to make E(v1, h1) and E(v2, h2) the same by changing v2. Then do the same to find v3. Rather than eliminate m from our equations we have given it a reasonable value of 1000 kg—the reader should experiment to show the solution is the same even with an unreasonable value such as 5 × 10−5 kg.
Figure 2.8. Roller-coaster problem answered with function solve. The first time the author set up this problem he was discouraged to find that solve found no real root! How could that be? The answer was because he had foolishly used the two-argument form of solve. When the third and fourth arguments were added (and some experimentation done), all was well. Recall that solve with two arguments looks only in the range set in Options (see section 1.7)
2.9 Bullet velocity [BulletVelocity.sm] A gun is fired point-blank into a block of wood which is initially at rest on a horizontal surface. When the bullet becomes impacted in the wood, the block slides a certain distance (s) before coming to rest. Given the mass of the bullet m, the mass of the block M, and the coefficient of sliding friction μ, find the muzzle velocity of the bullet. The textbook [2] from which this problem is taken gives us three equations (we will use subscript b for the bullet and B for the block):
After some algebraic rearranging, an expression is found for vb allowing the authors to enter some numeric data (m = 10 g, M = 4 kg, s = 15 cm and μ = 0.4) and compute the required velocity. We will let SMath do most of the work—figure 2.9. All that is needed is a very simple rearrangement of the first equation. As can be seen in the symbolic evaluation of s, SMath can perform all the other rearrangements, and its solve function can complete the problem.
Figure 2.9. Find muzzle velocity. The expression on the second line was obtained by typing s followed by Ctrl+period to get a symbolic representation of s. Note how SMath has done all the algebra for us. The yellow coloured note is called a description. It is added by left clicking the region, then right clicking and using Show description from the popup menu. By default the description appears at the top of the region. Click on the region and move the mouse pointer over it until a pointer with four arrows appears, then drag the description to the required location. A description has some advantages over a simple text region: the description moves with the region and it can be switched on and off at will. Observe that the solve function in this example was applied to an expression for s rather than to a function as was done in the previous two examples. Since we cannot use units with solve, the values of some experimental data are entered in a form that clearly shows the conversion to SI units. The final displayed value for vb has been formatted to display zero decimals.
2.10 Water depth [WaterDepth.sm.] A swimming pool is illuminated by an underwater point source of light. Viewed from above the water at a horizontal distance d = 1 m the light is seen at an angle
θ2 = 30°. How deep is the light? Use 1.3 as the refractive index of water. The simplest way to remember Snell’s Law is μ · Sin(θ) = constant. In figure 2.10, we solve the problem by finding the angle within the water and from that the depth is readily found.
Figure 2.10. Snell’s Law example.
2.11 Balmer series [Balmer.sm.] A student is asked to compute the wavelengths of the first six lines in the Balmer series of the hydrogen spectrum using the equation:
At the top of an SMath page, the student entered the value for the Rydberg constant R —see figure 2.11. The code was generated by typing and filling in the two place holders in the resulting template. This gave the vector n having values {3, 4, 5, 6, 7, 8}. A for loop is required to make a vector called λ holding the six wavelengths. Rather than rearrange the equation to compute the wavelength with a single statement, the student used a line with two statements in the block—this is explained in the Overview chapter. Then the λ and n vectors are displayed side by side. Note that originally the λ values had dimensions of metres but he changed this to nanometres.
Figure 2.11. Balmer series. The screen capture shows values reported on a website; the agreement is acceptable. To generate the wavelength for the 2→∞ transition, one could enter under the second line of code.
2.12 Uncertainty calculation [Uncertainty.sm.] Measurements of a cylinder have been recorded as: mass m = 47.36 ± 0.1 g; height h = 15.28 ± 0.05 mm; diameter d = 21.37 ± 0.04 mm. We are asked to compute the density ρ together with its error in units of kg m−3. In figure 2.12 the measurements and their errors are entered separately. The density is computed. Fractional errors in the measurements are defined and the fractional error in density is computed. From this the error in ρ is found. The last line displays the result. In the last math region, the number of decimals and the exponential threshold were each set to 2. Unfortunately it is not possible to have SMath display the result in the form ρ .
Figure 2.12. Uncertainty calculation.
2.13 Calculate the age of a rock [RockAge.sm.] The radioactive decay of 238U leads to the stable isotope 206Pb. A certain rock has a 206Pb/238U ratio of 0.0058. What is its age? Assume all the 206Pb comes from the decay of uranium. Let the number of atoms of 238U at t = 0 be N0. After t years there will be N0 exp(−λt) atoms of 238U and N0 (1−exp(λt)) atoms of 206Pb, where λ = ln(2)/t½ and t½ is the half-life of 206Pb. This tells us that the expected ratio is given by 1−exp(λt)/exp(λt). Given that t½ = 4.51 × 109 years we can solve for t. In figure 2.13 we provide SMath with the relative equations and data, and again use solve to find the answer.
Figure 2.13. Age of a rock.
Note the range 0 … 1010 given to the solve function. How did the user come up with these values? The zero value reflects the fact that t must be positive. If 4.51 × 109 (that is t½ years) had passed, then half of 238U would have decayed and the ratio would have been 1.0. The user might have considered using a range of 0 … 108 but he went for broke with 0 … 1010. The reader may wish to change Rrock to 1.0 and see if the worksheet computes the expected value for t.
2.14 The ladder problem: search method [Ladder1.sm.] Many textbooks on computer programming contain this problem: a ladder is being carried down a corridor which intersects with a second corridor, what is the longest ladder that can be taken around the corner? We will assume that the ladder is being carried with the rungs perpendicular to the floor so we need to be concerned with its width; we would also assume the ladder always remains parallel to the floor. In figure 2.14 we have a ladder of length L passing from a corridor of width w1 into a second corridor of width w2; the two corridor doors meet at an angle a while the ladder makes an angle c with the second corridor1. It can be shown that the relationship between these variables is given by:
Figure 2.14. The ladder problem, the search method. A plot of L against c shows that there is some angle for which L is a minimum; this value is the longest ladder that can pass around the corner. It takes some thinking about to realize that this maximization problem has become a minimization problem. From the plot we can see that the point of inflection lies somewhere between ca = 0.375 and cb = 0.625. We divide this range by n (start with n = 100) to give the step size for the search. We temporarily set Lmin to L(ca). Within the for loop, c is varied and a check is made to see if a new minimum value has been found. If the values are found to be increasing, we break out of the loop since we must have gone around the inflection point —this action is not essential but it does cut down on the calculation time. We complete the worksheet by displaying the values of L and the corresponding c in radians and degrees. It should be clear that our computed L value has the limits of L ± delta.
2.15 The ladder problem: solved with differentiation
[Ladder2.sm.] Traditional programming languages were unable to perform differentiation and in the days before Wolframalpha.com, the student was not expected to be able to find dL/dc. But SMath has no trouble, as figure 2.15 demonstrates.
Figure 2.15. The ladder problem, solved by differentiation.
2.16 Circuit analysis: matrix math The following is a brief explanation of how matrix math may be used to solve a system of equations.
[Kirchhoff.sm.] In figure 2.16 there is a simple electric circuit together with a list of resistance and voltage values. The task is to find the three currents. Applying Kirchhoff’s voltage law, which states the algebraic sum of the voltages around a closed loop in a circuit is zero, gives three equations:
Figure 2.16. Kirchhoff’s voltage law. Substituting the known values and rearranging the equations in preparation for the matrix solution, we write:
On the SMath page we code the M matrix and C vector. The resultant vector I is computed with I = M−1C, and the I values are displayed.
2.17 Thermistor quality control [Thermistor.sm.] A thermistor [3] is a device whose resistance is very sensitive to its temperature. A certain model comes with the calibration formula: The manufacturer checks each unit before shipping and requires that the error be no more than ±1 °C. If we translate this to resistance measurements, what is the acceptable resistance range if the thermistor is in a 19 °C bath? Looking at the left side2 of figure 2.17: the function relating 1/T with R is defined. The t vector holds the three acceptable temperatures in Celsius while T has them in Kelvin. In the for loop, the solve function finds what values of R generated the three T values. The values are stored in the r vector and a check is made that these do indeed correspond to the three temperatures. These are displayed. It seems that the acceptable range is 13066 Ω ⩽ R ⩽ 13078 Ω.
Figure 2.17. Thermistor quality control. We may, incorrectly, believe we have completed the task. What is required is a significant figures analysis or a sensitivity analysis as shown on the right hand side of figure 2.17. The quality control specifications indicate that one is interested in temperature values with a precision of ±0.01 K, so we use the round function to achieve this. The range 13060 Ω ⩽ R ⩽ 13085 Ω is tested to see what temperature values would result from such R measurements. Note that we cannot use it for ∈ as these values exceed the limits permitted by SMath in a for loop, so we use a workaround with the variable fix. The conclusion is that the acceptable range for R is 13064 Ω to 13081 Ω, assuming the resistances are measured with a precision of ±1 Ω,
2.18 Fourier series Many applied mathematics texts state: all functions f(x) of practical interest which are defined on the interval3 −π ⩽ x ⩽ π can be expressed in a converging trigonometric series of the form
The constants a and b are related to f(x) in a special way
[Fourier.sm.]The demonstration shows the construction of the Fourier series of the step function
It can be shown [4] that in this case
The first statement in the SMath script (figure 2.18) defines a value for the variable div which will be used to determine how many data points will be calculated for f(x) on the stated interval −π ⩽ x ⩽ π, and the value of delta which will be the step size. The larger div is made, the smoother the plots will be. By typing , the user generated a vector of x-values from −π to π with Δx equal to delta. So X will have div +1 data points; this can be confirmed with the statement .
Figure 2.18. Demonstration of a Fourier series calculation. The for loop, within which there is an if structure, generates the corresponding values for f(x); these are put into vector F. The matrix P produced by augmenting X and F will be used for plotting. There follows a second for loop to compute the values of the Fourier series for every x-value in vector X. The eval function is used to speed up the calculations. By setting the maximum n to 3, we compute four terms in the series sin(x), sin(3x), sin(5x), and sin(7x); this is called the partial sum S4(x). The reader should change the 3 in n ∈ 1…3 to 10 to observe the effect. Note that there is a picture of a plot in figure 2.18; the actual plot must be below the statement that makes the M matrix.
2.19 Self-test projects 2.19.1 Centroid Figure 2.19 shows the equations needed to find the coordinates of the centroid of a polygon together with a plot of a sample polygon showing its N vertices and side, and the position of the centroid. Make a vector for the x-values of the vertices and another for the y-values; all are integer values. Compute the Cx and Cy values. Make the plot as shown.
2.19.2 Sound beats A sound wave can be represented by the equation shown in figure 2.19. Make two functions (wave1(x) and wave2(x)) and produce the plot as shown for A1 = 1, f1 = 440 Hz, A2 = 1.5 and f2 = 500 Hz. What happens when you increase the value of A2 to 3?
Figure 2.19. Finding centroid coordinates of a polygon.
2.19.3 Rigid structure analysis Figure 2.20 shows a diagram of a rigid structure. Write a system of equations for the equilibrium of forces at each junction. Use matrix math to find the forces; the results are in
the figure.
Figure 2.20. Generation of beats from two sound waves.
2.19.4 Inflection points For the cubic equation below, find the roots with polyroots. Find the equation of the differential using the differentiation function (it follows cot on the middle row of the Functions palette). Solve this for x, and show that the points of inflexion are (−1.3609, 20.7453) and (2.6943, −12.5972).
2.19.5 Chart task Referring to section 2.17, make a chart similar to that in figure 2.21 for the thermistor (figure 2.22).
Figure 2.21. Rigid structure analysis.
Figure 2.22. Chart for thermistor task.
References [1] King A R and Regev O 1997 Physics with Answers: 500 Problems and Solutions (Cambridge: Cambridge University Press) [2] Fowles G R and Cassiday G L 2005 Analytical Mechanics 7th edn (Belmont, CA: Thomson Brooks/Cole) p 305 [3] Kaw A Holistic Numerical Methods: Transforming Numerical Methods Education for STEM Undergraduates http://nm.MathForCollege.com [4] Jeffrey A 1996 Mathematics for Engineers and Scientists. (London: Chapman & Hall) 1Because corridors in buildings generally meet at right angles, and the problem is more interesting if they meet at an
angle, the ladder problem is often called ‘the ladder down the mine’! 2Normally one works down an SMath page. Here the material has been placed on the right side of a bar so that a usable
screen capture was possible. The bar was made in a drawing program and put on the page with copy and paste. 3This interval is not a true restriction; a simple change of variables can change an interval [p, q] to [−π, π].
IOP Concise Physics
SMath for Physics A primer Bernard V Liengme
Chapter 3 Trajectory of a projectile This topic was selected as it can be used to demonstrate several SMath features.
3.1 A simple calculation We begin with an exercise to plot the trajectory of a projectile flying over horizontal ground having started at (0, 0) with a velocity v and angle θ. This, of course, is a rather simple problem but as we develop it we can gain some useful insight into SMath. In ProjectileSimple.sm (figure 3.1) we code the well known equations of motion and make a plot.
Figure 3.1. The simple approach. On the first row on the page we set up the experimental conditions: the initial angle and the velocity. We also enter a value for g, the gravitational acceleration. To make the first math region, type (without spaces) and either tap the ENTER key or click a blank area on the page. This sets the initial angle of the projectile as 60° but we have converted it to radians with π/180 in anticipation of using SMath trigonometry functions. The use of CTRL+g after a letter
converts it to Greek, so q becomes θ, and p becomes π. The colon (:) gets converted to the assignment operator (:=) while the asterisk (*) becomes a middle dot (·) denoting multiplication. A function y(x) is constructed for use in the plot. Formulas are entered to calculate the maximum height (h) and the range (r) of the projectile. The resulting values are displayed. The command Insert | Plot | 2D (or by simply typing @) brings up a blank chart. In the place holder in the lower left type . You may not see anything until the chart is rescaled. This is where the values of h and r come into play. The whole chart is scaled by clicking within it and rolling the mouse wheel; to scale just the vertical axis, hold down the CTRL key while rolling the mouse wheel; holding the SHIFT key scales the horizontal axis. Dragging the mouse moves the origin of the plot. When no mouse wheel is available, it is necessary to use the Scale and Move tools on the Plot palette. Knowing the values of h and r will help the user adjust the scales to suitable values. Do our SMath results agree with independent calculations? Note that many internet trajectory calculators use g = 9.81 while we have used g = 9.80665 so small difference are expected. As has been stated above, the assignment operator is generated by typing a colon. So gets converted to when you press ENTER or click elsewhere on the page. If you open a new SMath page and type, for example , then SMath will obligingly change it to allowing you to make an assignment such as . However, although it saves having to use the SHIFT key, you should avoid relying on this. If you try it within a programming structure such as a for loop, things will go badly wrong.
3.2 An improved plot The plot in figure 3.1 is somewhat unsatisfactory in that time extends into the past and the projectile seems to have a burrowing capacity! To avoid this we compute the value of y at various, pre-chosen values of x. In precomputer days, a student would make a table such as in table 3.1 using the equation of motion. Our SMath page will do just that. We will make a vector with x-values and another with y-values. Table 3.1. Data for manual plotting. x 0 10
20
30
40
50
60
70
80
y 0 16.842
32.725
47.651
61.619
74.629
86.681
97.776
107.912
Figure 3.2 shows the page ProjectilePlot.sm. We begin by assigning values to θ and v. Note also that we have included appropriate units. Rather than defining g we will use the built-in physical constant ge. The value is displayed merely for information.
Figure 3.2. An improved plot. We calculate and display the expected range of the projectile. To make a smooth plot we need fairly small increments of the x-values. The variable step is made equal to the range divided by 100 and this will be used for the increment. If the resulting plot is not smooth, we can use a smaller fraction of the range. To construct the X vector using we begin with then type (or the first three letters of ). Within the dynamic assistant, double click to generate the code X:= ▪.▪ .. ▪. Fill in the place holders to give . This code needs to be explained. If we had , SMath would compute the difference between the first two parameters: 7 − 3 = 4. Then it would construct the vector with values 3, 7, 11, 15, 19. Note the steps of 4. The last value (19) meets the criteria that it must be equal to or less than the third parameter which is 20. So our actual
code gives us values 0, step, 2*step, 3*step … r. The code have 101 data points in the vector X.
tells us we
The Y vector is made with a loop. Either click on in the Programming palette, or type and select from the dynamic assistant: it is not sufficient to just type the word. This generates the template shown to the left below. Enter as the first parameter; the variable will be used as an index to refer to each element in in turn. Select the second place holder, type (or the first three letters of it) and select from the dynamic assistant, giving two place holders to the right of the ∈ symbol.
Fill these in with and , respectively. In the remaining place holder type the formula to compute a Y vector element. In all cases here, the j is an index so type (where → denotes the right arrow key, or the spacebar). The open square bracket ( ) causes the j to be an index. Construct the plot as before. The code to the right of the plot shows that the largest value in the Y vector and the largest in X give results in agreement with the expected values. Such confirmation gives us confidence in the code we have used and that the step size was small enough—suppose we had used a large step size, then the true maximum yvalue could lie between two data points.
3.3 Trajectory when drag is considered [SMath file ProjectileDrag.sm.] When the concept of a projectiles trajectory is covered in an introductory physics class, it is assumed that the only force on the projectile after it leaves the firing point is gravity. Reality tells us air resistance, or drag, also exists. We will compare the trajectory when drag is ignored with that when drag is considered. For this exercise we will use a drag that is proportional to the square of the instantaneous velocity of the object; this is sometimes termed quadratic drag to distinguish it from linear drag. An analytical approach for the drag problem would involve differential equations [1]. Our approach therefore will be to use a numerical approximation. As a check on our method we will use the same numerical method for the non-drag trajectory. If the force of air resistance is written as F = Dv², we may write f(x) = −Dvvx and f(y) = −Dvvy, where D is the drag coefficient, v the velocity and vx and vy the x and y components of v. From there we find that the acceleration in the x direction for an object of mass m is ax = −(D/m)vvx and in the Y direction it is ay = −mg − (D/m)vvy. The D parameter is generally found using D = ρCA/2, where ρ is the density of the medium the object is moving through, A is the object’s cross-sectional area in the direction of motion, and C is the dimensionless drag coefficient and it normally has a value in the range 0.1 to
1.0. The numerical approach computes the coordinates (x, y) of the object at time 0, Δt, 2Δt, 3Δt and so on until y becomes zero again. Once the problem has been defined (in terms of initial position and velocity, initial angle of flight, mass of object, and terms needed to compute D), the procedure may be summarized as follows (details on the method can be found in [2, 3]). (Do while y is not negative.) Record the current coordinates in vectors; Increment the vector index; Compute ax = −(D/m)vvx and ay = −mg − (D/m)vvy; Compute new velocities vx = vx + axΔt and vy = vy + ayΔt; Compute new coordinates x = x + vxΔt + ½axΔt² and y = y + vyΔt + ½ayΔt². The SMath page ProjectileDrag.sm is shown in figure 3.3. The experimental parameters (the object’s mass and radius, air density ρ, together with the initial angle of flight θ and initial velocity v) are chosen to represent a baseball’s flight path. In the figure, the value of Δt is 1/2000 (i.e. 0.0005 s). However, the file on the companion site has a value of 1/200 so the reader is not inconvenienced by a long calculation time. This matter is discussed below.
Figure 3.3. Trajectories with (red) and without (blue) drag.
To avoid confusion between subscripts and indices, no subscripts were use. A variable name containing the letter A refers to the projectile without drag while B is for the other projectile. The letters x and y refer to the horizontal and vertical directions, respectively. The variables k and j are used for indices. A loop is used for each case to compute the coordinates of the object with the iterations continuing as long as the y position is not less than zero. The coordinates are stored in vectors: XA and YA for the A object, and XB and YB for the B object. The loop on the left in figure 3.3 computes the points for the non-drag trajectory. Since in this case there is no horizontal force, we need not compute the horizontal acceleration nor do we need to recalculate the horizontal velocity in each iteration as it remains constant. To construct this block begin by either using the item on the Programming palette or by typing and selecting the appropriate item from the dynamic assistant. This gives the template shown to the left in figure 3.4. The logical negation (not) operator (¬) is taken from the Boolean palette. When the condition has been completed (use the < symbol from the Boolean palette), click on the place holder in the second row of the template and from the Programming palette select . The template now has two place holders (see centre of figure 3.4) but we need six. Click on the line (the vertical bar in the template) and drag the fill handle (the solid square in lower right corner—right area in figure 3.4) down until there are six place holders.
Figure 3.4. Progression of the While loop construction. The remaining statements are then added to the loop. The purpose of is discussed later. Once the second loop has been constructed, the results can be displayed. The ranges of the projectiles are given by the last elements of their X vectors while the maximum heights are found by locating the maximum values of their Y vectors. Finally, the pairs of X and Y vectors are augmented to give a matrix to use in the plot. Are we on the right track? Firstly, we note that, as shown in the table below, the values for the range and height of projectile A (no drag) is in reasonable agreement with the values computed in ProjectilePlot.sm.
ProjectilePlot
ProjectileDrag
% error
Range
163.1546
163.1154
−0.024%
Height
40.7886
40.7745
−0.035%
Furthermore, if we make C equal to zero (i.e. we make projectile B dragless), the two plots, and the range and height values for objects A and B coincide exactly. This gives us confidence in our programming and the accuracy of SMath. Actually, we can ‘cheat’: the authors of the paper cited in footnote 1 have provided results for their calculations which, while using the more accurate Runge–Kutta method, has values in good agreement with ours. The interested reader should look at the bottom of the ProjectileDrag.sm page.
3.4 Did we use a small enough Δt increment? The precision of an iterative numerical method such as that in ProjectileDrag.sm depends on using a small enough step size; here that means a small enough value for Δt. Typically one keeps reducing the step size until successive results converge within the required precision of the problem. The SMath page ProjectileDelta.sm is essentially the same as ProjectileDrag.sm but computes results only for projectile A. This page was run six times with different denominator values and the range and height values were recorded in an Excel worksheet, see figure 3.5. Recalling that Δt = 1/denominator we see the results converge with smaller Δt values.
Figure 3.5. Results converge as Δt gets smaller. A denominator value of 5000 would appear to give a sufficiently small step size; would we ever need to know the range or height in metres to better than a few decimal places? However, there is a price to pay for such a small step size. Figure 3.6 shows the calculation times for various denominator settings when the page was run on a computer with an Intel Core I5-4440 3.1 GHz CPU. Interestingly, the calculation times and the
denominator values have a quadratic relationship, as shown by the second order polynomial trendline.
Figure 3.6. Convergence has a time cost. We may be willing to spend 10 min when the denominator is 5000 but can we spare nearly 45 min when the denominator equals 10,100 for just a small improvement in precision? This points out one of the few weaknesses of SMath: to compute and plot about 58,000 data points took 45 min. An Excel worksheet (see Projectile.xlsx) recalculates its nearly 58,000 rows for a denominator value of 10,000 almost instantaneously. Fortunately, SMath has a number of features that lessen the need to resort to long-running loops. It should be noted that, when starting a new project, the ability to do it with two independent software applications can help find programming errors. Suppose you have ProjectileDrag.sm open and wish to do some minor edits. The application will start to recalculate every time you make an edit and hit ENTER or click on an empty space. The recalculation can be stopped by tapping the ESC key. An area on the page will be outlined in red to indicate it has not completed the computation. Alternatively, one can open the Calculation tab and uncheck AutoCalculation. With this setting, one must press F9 to cause a recalculation. It is advisable to put AutoCalculation back on as soon as possible: if you forget it is off you can get confused when simple code does not give a result! The F9 key can also be used to recalculate a page in the Ready state. One can perform an interesting experiment with ProjectileDrag.sm with the denominator set at, say, 5000. Press F9 and observe that a green box appears around the while block, then around the augment statement and finally around the plot as each
of these area get computed.
3.5 What is the purpose of the Eval function? The function converts its argument from symbolic to numerical format. This can have a dramatic effect on the time required to calculate an SMath page. As noted in the section 3.4, with the page ProjectileDelta.sm the calculations for the single projectile without drag took 117 s when the denominator was set to 2000. The file ProjectileNoEval.sm is the same as ProjectileDelta.sm but the three functions have been removed. This page took 196 s to calculate; so the three functions reduced the running time by 40%. The times to compete just the blocks (without the statement and producing the plot) were 80 and 160 s, respectively; so the functions saved 50% when only the loops were considered.
References [1] http://www.lajpe.org/sep13/04-LAJPE-782_Chudinov.pdf [2] http://wps.aw.com/wps/media/objects/877/898586/topics/topic01.pdf [3] http://www.wlu.ca/documents/53145/NotesCh3.pdf
IOP Concise Physics
SMath for Physics A primer Bernard V Liengme
Chapter 4 Linear regression To define what is meant by linear regression, here is a quote from Wikipedia [1]: “In statistics, linear regression is an approach for modeling the relationship between a scalar dependent variable y and one or more explanatory variables denoted x. The case of one explanatory variable is called simple linear regression. For more than one explanatory variable, the process is called multiple linear regression.” A simple linear regression finds the parameters for y = mx + c. A multiple linear regression might find the parameters for a polynomial equation. Suppose the equation was cubic as in y = ax3 + bx2 + cx + d, then we can think of the explanatory variables as being x3, x2 and x.
4.1 Simple linear regression [LinearRegress1.sm.] An experimenter is calibrating a piece of equipment. She varies the independent variable (generally called x) and measures the dependent variable (generally called y.) She needs to find the least-squares line of best fit which we will denote as y = mx + c where m is the slope and c is the intercept. The formulas to compute the slope and intercept when there are n measurements can be expressed in various ways, for example:
Rather than using one monolithic expression for slope m, we will define some intermediate variable Sxx, Sxy, etc as shown in figure 4.1.
Figure 4.1. Simple linear regression example. Since the x values varied monotonically it was simpler to use (note the use of range(3) for the right-hand side) to fill the vector. The y values were entered into a vector which was initiated with the first tool in the Matrices palette. Towards the bottom of figure 4.1 the variables Stot and Sres are computed to enable us to estimate the value of R2. The reader may wish to consult a statistics textbook or website to understand the equations being used. Using the technique shown in the Overview chapter, a plot of the line of best fit together with the ten data points was constructed—see figure 4.2.
Figure 4.2. A plot of the line of best fit and the data. The reader will see that the SMath file LinearRegress1.sm worksheet can serve as a template for other linear fitting exercises. All that is required would be to either edit or re-enter the xdata and ydata values. Many statisticians recommend that one plots the residual values—the difference between the experimental y values and the predicted y values. If that plot shows the residuals to be randomly scattered above the x-axis then all is well. If a pattern is evident, then one must consider the possibility of a so-called lurking variable. To the left in figure 4.3 the residual plot of LinearRegress1.sm is displayed, while to the right is that plot for the data in LinearRegress2. The first plot looks random, unlike the second one where the parabolic shape suggests a small term in x2 might be present.
Figure 4.3. Plotting residuals to check for lurking variables.
4.2 Zero intercept In many cases one needs to find a line of best fit that passes through the origin. When the intercept is constrained to be zero the slope m is found with:
[LinearRegress3.sm.] There are occasions when it is appropriate to require a calibration curve to pass through the origin. The data in LinearRegress1.sm gave a very small intercept and so it can serve as suitable data for a zero intercept fit demonstration— see figure 4.4.
Figure 4.4. A linear regression with the intercept constrained to zero.
4.3 Multiple linear regression In this chapter we use various formulae to fit data to some functions. In section 10.5 there are regression examples using the built-in functions slope, intercept and fit of SMath with Maxima. Here is an example of multiple linear regression: a person’s height Y is related to the mother’s height X1, the father’s height X2 and the gender of the person X3 (1 if male, 0 if female). A study of this topic would involve measuring Y for a number of individuals and recording the other data. Then the researcher would find the values of the beta values that gave the line of best fit for Y = β1 + βX1 + β2X2 + β3X3. So we have one dependent variable and three predictors. How does this relate to fitting to, say, a cubic equation y = β1 + βx + β2x2 + β3x3? We merely let the predictors be x, x2, and x3. [LinearRegress4.sm.] In the examples above we found the fitting parameters using algebraic equations. Now we will experiment with a matrix method to fit data to a quadratic. No attempt will be made to mathematically justify the steps (essentially the method involves solving a system of equations) but the focus will be on how to get a result with SMath.
In figure 4.5 after entering the x and y values, the user has constructed a design matrix (X) using a for loop; the result is evaluated to the right of the loop. The interpretation is: column 1 indicates that coefficient b1 is multiplied by 1 (i.e. it is independent of the x values); column 2 shows the b2 coefficient is multiplied by each x value, and column 3 that b3 is multiplied by each x2 value.
Figure 4.5. Multi-linear regression. Readers familiar with the matrix math method of solving a system of equations will recognize the meaning of the row headed . This topic is covered in section 2.16. The B vector is evaluated to reveal the coefficients. A list with text was added to remind the user which term in the quadratic is associated with which coefficient. Continuing with this example, figure 4.6 shows how to find the predicted y values (a for loop is required) and the function Fitline(x) for plotting. The reader may wish to use the method in LinearRegress1.sm to show that for this data R2 = 0.9997.
Figure 4.6. Computing the predicted y values and plotting the line of best fit.
4.4 Multiple linear regression using a vector function [LinearRegress5.sm.] The page shown in the above subsection has a number of drawbacks when we wish modify it for different fitting functions. We resolve this in LinearRegress5.sm by defining φ(x) a vector function—see figure 4.7. In this example we are fitting data to a cubic equation, so the elements of this are {1, x, x2, x3}. The for loop used to construct the design matrix is now simplified by the use of this vector. The reader should note that we can modify this page to fit, for example, a quartic function. All that is needed is to drag the vector parentheses down to add a new element for x to the power of 4. Only the optional red text list would need work.
Figure 4.7. Using a vector function to simplify the work.
Figure 4.8. The vector function saves the need to change the code for a new problem.
The convenience introduced by the function vector does not end there. In figure 4.8 observe how easy it is to compute the calculated y values and the Fitline(x) function used for plotting the line of best fit. Nowhere do we need to enter the fitting function as the vector function looks after everything. These calculations will still work without modification when φ(x) is modified for a new problem, as is demonstrated in the next section.
4.5 Multiple regression: some exercises Here are two exercise that the reader may wish to attempt. 1. Can we use the vector function method for a linear formula y = mx + c? Open LinearRegress.5 and save it as LinearRegress1A. Delete the xdata and ydata definitions; using copy and paste, replace them with the values from LinearRegress1. Modify the vector function to have just two elements: {1, x}. Do you get the same results as in LinearRegress1.sm? 2. This one takes a little more work. You have temperature and pressure data as shown in the table below. Temperature (°C)
−36.7 −19.6 −11.5 −2.6 7.6 15.4 26.1 42.2 60.6 80.1
Pressure (torr)
1
5
10
20
40
60
100
200
400
760
Your task is to find the fitting parameters for log10(p) = b1 + b2/T + b3log10(T) + b4T2 where T is the temperature in Kelvin. Open LinearRegree5 and save it as LineraRegree5A.sm. Begin by deleting the xdata and ydata vectors, and entering two vectors names Temp and Press (we must avoid using P since that name is already in use on our worksheet). It will save a lot of work if we retain the names xdata and ydata. So to get the temperature values in Kelvin as the independent variable data use . To make ydata we need a for loop: ∈ . The required φ vector elements are: . The worksheet looks after everything from there on. Not quite! The statement will be red, and you may see the message “Result is above max allowed positive number.” We need to edit this to read B: to overcome the problem. Now the red box has gone thanks to the eval1 function. Did you get B1 = 216.2059?
Reference [1] http://en.wikipedia.org/wiki/Linear_regression 1It is somewhat difficult to come up with rules for when to use eval. Unless you are doing symbolic work, its use when
technically not required will not be problematic. In the Trajectories chapter we see how its use can speed up calculations.
IOP Concise Physics
SMath for Physics A primer Bernard V Liengme
Chapter 5 Root finding We have seen in the Overview and Simple Physics chapters the use of SMath’s various root finding functions: polyroots, roots, and solve. In this chapter we explore some of the traditional numerical methods for finding roots: fixed point iteration, bisection, secant, and Newton–Raphson methods. The fixed point iteration method can be used only when it is possible to recast the problem of finding x such that f(x) = 0 to find x such that x + g(x). The bisection method is the one method that is guaranteed to converge on a solution provided you can find two starting values of x that have opposite signs. The rate of convergence is slower than with the next two methods. The secant method converges faster than the bisection method. However, since the secant method does not always bracket the root, the algorithm may not converge for functions that are not sufficiently smooth. The Newton–Raphson method is much more efficient than other ‘simple’ methods such as the bisection method. However, the Newton–Raphson method requires the calculation of the derivative of a function at the reference point, which is not always easy. Furthermore, the tangent line often shoots wildly and might occasionally be trapped in a loop. In section 10.1 there are examples of the built-in functions Solve, Bisection and FindRoot of SMath with Maxima.
5.1 Fixed point iteration Suppose we need to solve f(x) = 0 and that it is possible to recast this to x = g(x). Then with some initial guess for x0 we may use the iteration xn+1 = g(xn) until successive values are the same to some required precision. [FixedIteration.sm.] For the demonstration our task will be to find the molar volume of ammonia gas at a given pressure and temperature using the van der Waals equation:
The second form suggests we try the method of fixed point iteration. We enter a value for V in the right side of the alternative form to compute a new V value; we use this second value to compute a third; we continue to do this until two successive values are the same to within the required tolerance.
In figure 5.1 the page starts with numeric definitions of the van der Waals constants a and b, the experimental conditions T and P, and the required precision or tolerance ∈. The iteration function is V(v); a starting value for v is found from the ideal gas law. The for loop computes successive values of v until the absolute difference between vn and vn+1 is less than the tolerance value. The vector R is used only to give the user an idea of how the solutions converged.
Figure 5.1. The fixed point iteration method. It was tempting to use a while loop with condition ∈. However, there is no guarantee that the method will converge on a solution so we limit the number of iterations to some reasonable value. We do, however, break out of the loop when this condition is met. The transformation of V is used here merely to make a smaller figure.
5.2 Bisection method A function changes sign when it passes through zero. By evaluating the function at the middle of an interval and replacing whichever limit has the same sign, the bisection method can halve the size of the interval in each iteration and eventually find the root. To use this method one needs to know, or guess, two values of x (call them a and b) such that f(b) < 0 < f(a). [Bisection.sm.] The bisection method will be used to solve a problem (from [1]) relating to a floating ball. The floating ball has a specific gravity of 0.6 and a radius of 5.5 cm. We wish to find the depth to which the ball is submerged when floating in water. The equation that gives the depth x (in metres) to which the ball is submerged under water is
given by x3 − 0.165x2 + 3.993 × 10−4 = 0. From the description of the problem we can see that 0 < x < 0.11 where 0.11 is twice the radius. This gives useful starting values for a and b. As can be seen in figure 5.2, the SMath script checks that f(a) and f(b) have different signs. If not, then the loop for the calculation is not entered. Since we know that this method must converge, we are safe in using a while loop with the condition where ε is our required precision. A result with this precision is obtained in 12 iterations. Note that in , the n is a subscript, not an index.
Figure 5.2. The bisection method. The final x value is in good agreement with SMath’s solve result. Because we used limits of 0 to 2 for solve, we get the two mathematical roots in this domain but only the first is physically feasible.
5.3 The secant method The secant method uses the iteration
As with the bisection method, we start with two x values but this time there are no restrictions. However, the closer they are to the root, the faster the convergence will be. For the demonstration, the same problem as in section 7.2 is tackled—see figure 5.3. Since there is the possibility that the second method will fail to converge, we again use a for loop with an ‘escape hatch’ to be used when f(x) is equal to zero within the specified precision. It is more convenient here to index x-values. The result is obtained within four iterations (note the loop stats with k = 2, and four new x-values are computed) compared to 12 in the bisection method. Furthermore, the final f(x) is a little closer to 0.
Figure 5.3. The secant method.
5.4 Newton–Raphson method The Newton–Raphson method of finding roots is also an iterative method. We have a function f(x) whose roots we wish to discover. We make a guess x0 at the root and compute a better estimate x1 using . We repeat the procedure until f(x) is zero or as close as required. Alternatively, we iterate until two successive values have essentially the same value; this is the approach taken in the example. Many textbooks on numerical analysis cover this topic thoroughly. Some of the considerations to bear in mind are: Finding the first derivative of f(x) can be difficult if f(x) is complicated. When the first derivative of f(xn) is close to zero, the Newton–Raphson method gives no solution. Near local maxima or local minima, there can be oscillations resulting in slow convergence. An initial guess far from the required root may cause the method to converge to some other root. In figure 5.4 f(x) is the equation whose roots are to be found and g(x) is its differential, found using an SMath function but only to save the time of performing the derivation on paper and typing it on the worksheet! A solution was found in five iterations with x = −0.65927. If the starting x value is set to −2, the resulting root is −1.27103, found with six iterations. These roots agree with the two SMath results, and f(x) for these values of x evaluates to very close to zero. Recall that the roots function will fail if the variable has been defined on the page before the roots function is used, so we use dummy variables like _x to safeguard against this.
Figure 5.4. The Newton–Raphson method. [Bisection2.sm & Secant2.sm.] For comparison purposes, the files for the bisection and secant methods were modified to solve the same problem as shown in figure 5.4; these new file have a ‘2’ added to their names. To get Secant2.sm to calculate in reasonable time, it was necessary to wrap the computation of xk+1 in an eval function. [NewtonRaphson2.sm.] Nobody would use the Newton–Raphson method to solve a polynomial when there is the splendid SMath polyroots function. However, the reader might like to experiment with NewtonRaphson2.sm which finds the roots of the function below. Observe the outcome from each of these three initial guesses in succession: 2.35, 2.36, and 2.37. The results are difficult to explain—this is not an SMath failure but a complication of the Newton–Raphson method.
5.5 Self-test 5.5.1 Find a root
[NewtonRaphson3.sm.] This worksheet finds one root of cos(x) + 2 sin(x) + x2, a function for which there is no analytical solution. Add to the worksheet so that it also displays the second root. Then add code to find one or both roots using either the bisection or the secant method.
5.5.2 False position method This is another method of finding roots of nonlinear functions. Search the internet to learn how it works then code an SMath page to solve the floating ball problem (see section 5.3) using this method.
Reference [1] Kaw A Holistic Numerical Methods: Transforming Numerical Methods Education for STEM Undergraduates http://nm.MathForCollege.com
IOP Concise Physics
SMath for Physics A primer Bernard V Liengme
Chapter 6 Numerical integration In the days before math applications like SMath, several numerical integration methods were used for intractable definite integrals; two of the most popular were the trapezoid rule and Simpson’s ⅓ rule. For a lucid explanation of the rule, see [1]. It is likely that the SMath tool uses the Simpson rule so a demonstration of how it works could be instructive. In section 10.5 there are notes on symbolic integration which can be done in SMath with Maxima.
6.1 Simpson’s ⅓ rule [SimpsonCos.sm.] In figure 6.1 three ways are shown of obtaining the value of an integral for which there is no analytical method. Clearly, using the SMath integration tool is the simplest; note that the setting Tools | Options | Calculations | Integration has been set to 200 rather than the default value of 100. The other two methods are shown in order to expand the reader’s exposure to SMath features. The second method uses the simple summation approach, again with 200 data points, while the third method use a for loop. The agreement between the three methods and with the value reported by Wolframalpha.com is satisfactory. Without the use of the eval function, this worksheet would take over 30 min to calculate.
Figure 6.1. The SMath integration tool and Simpson’s rule.
6.2 Simpson’s ⅓ rule with tabular data The loop method is the one traditionally used in FORTRAN and C++ programs. It can be used when the data to be integrated is available only in tabular form. [SimpsonTab.sm.] An experimenter has taken measurements of a variable y every 10 min for 200 min. She needs to find the area under the curve. Simpson’s rule works with an even number of ‘stripes’, so we need an odd number of data points; here we have 21. If one has an even number of data points then a mixture of Simpson’s rule and the trapezoid rule (or even Simpson’s ⅜ rule) must be used. In figure 6.2 the vector T holds the time data and vector Y holds the y data. The data is visualized by including a plot. The for loop computes each term in the Simpson formula and adds it to the Area variable which is evaluated in the last statement. Since we have only 21 terms to compute the script runs fairly quickly without the need to use the eval
function, but no harm results if it is used.
Figure 6.2. Simpson’s rule used with tabular data. The reader is encouraged to compute the area using the trapezoid rule for comparison purposes.
6.3 Numerical integration using a Monte Carlo method [MonteCarlo.sm.] The definite integral shown below cannot be computed by an analytical method
This makes it an interesting topic for a demonstration using a Monte Carlo method. In
figure 6.3 the plot shows the function with a red box around the domain 0 ⩽ x ⩽ 2. Imagine this plot (the part enclosed by the box) was on a cork board and darts were randomly thrown at it. Clearly:
Figure 6.3. Numerical integration using a Monte Carlo method. The SMath
expression returns an integer random value between 0 and n.
The expression will give a real number between 0 and n to a precision of three decimal places. To allow for experimentation, the page uses to compute the two random numbers. The variable throws sets the number of random (x, y) pairs to be generated in the calculation. A test is done to see whether the (x, y) point lies above or below the function’s line and the variable count records the throws that do lie below. Finally the approximate area is found with the formula above. The variable Test shows the result from SMath’s numerical integration tool. Repeated use of the F9 key will generate new values for Area; the calculation takes about 3 s. The reader with 5 min to spare might wish to try a throws value of 250,000. The page has been made fairly general. For a new integral, one needs to change the first three statements provided the lower limit of the integral is still zero. A little more work is required when the lower limit is not zero. As an exercise, readers may wish to modify the page to compute the same integral but with a lower limit of 1 (the expected result is 14.99), and then compare their code with that in MonteCarlo2.sm.
Reference [1] www.intmath.com/integration/6-simpsons-rule.php
IOP Concise Physics
SMath for Physics A primer Bernard V Liengme
Chapter 7 Solving differential equations The more powerful math applications, like Mathcad, Maple, etc, have built-in functions for finding solutions to differential equations. Typically, these are precoded Runge–Kutta functions. SMath lacks the built-in functions but one can readily code them. For comparison, we begin with the Euler approximation and then demonstrate the Runge–Kutta method. In section 10.9 there are examples of built-in functions (rkfixed, Rkadapt, and ODE2) in SMath with Maxima.
7.1 The Euler approximation Let the differential equation to be solved have the form dy/dx = y′ = f(x, y) with the initial condition that at x0, y = y0. Integrating y′ from x0 to x1 yields
The second term on the right may be thought of as the area under the curve f(x, y) between the two x-values. Provided x1 − x0 is small, this may be approximated to the area of a rectangle. The approximate value of y1 is then given by It is traditional to express the x increment as h. Having found an approximation for y1, a further iteration finds an approximation for y2. In general, the value of successive approximations are found using the equation Clearly, the accuracy of the method depends on making h small. As with all iterative methods, one should experiment with progressively smaller h values until two successive results are within the precision required by the user. It is important to understand that some problems converge faster than others. [Euler1.sm.] To demonstrate the Euler method a problem with poor convergence has purposely been chosen. Find y(2) for the differential equation below given y(0) = 4.
Figure 7.1 shows the implementation of Euler’s method in SMath for this differential equation. The known solution to this is
Figure 7.1. Euler’s approximation for an ODE. The exact answer for y(2) is 0.0000 but our result is 0.5882 with h = 0.02. The reader may wish to increase n to 10,000 (giving h = 0.0002) to find that, after about 1 min1 of calculation, the worksheet reports y(2) as 0.0060. The trace statement was added to show the reader a debug technique. Suppose your model is not generating the correct answer and you wish to examine some variables as the loop progresses. If you use the menu command View | Output Window, the values of the variables named in the trace function will be displayed at the bottom of the SMath interface. It is also useful to have the for loop variable (here that is k) displayed to answer the question “are we there yet?” [Euler2.sm.] This worksheet has the Euler routine within a for loop to get some idea of the rate of convergence. The plot in figure 7.2 shows the results2 for h = 0.2, 0.04, 0.008, and 0.0016 together with the exact solution. Within the resolution of the plot, the exact and h = 0.0016 results coincide.
Figure 7.2. Convergence with the Euler method. The reader may like to save Euler1.sm as Euler1A.sm and then modify it to solve the following differential and find y(0.5).
The exact solution is:
The Euler method is somewhat more successful with this. The error is −1.7% with h = 0.05 and −0.16% with h = 0.005. When making the modification do not bother to replace x by t. This is unnecessary work and you could make a mistake—remember Yogi Berra’s maxim “If it ain’t broke, don’t fix it!” When modifying an existing SMath page it can be helpful to temporarily uncheck Auto Calculation in the Calculation menu. You can interrupt a calculation with the Esc key. Do remember to put Auto Calculation back on! [EulerPendulum.sm & EulerCromerPendulum.sm.] In the next section we will see that the Runge–Kutta method is far superior to the Euler method. However, the interested reader might wish to look at two files that attempt to model the simple pendulum. The first
worksheet shows that Euler’s method is generally inappropriate for differential equations that deal with oscillations. The calculations result in an ever increasing pendulum angle, totally at variance with the principle of conservation of energy. Cromer tracked down the problem and made the method behave correctly with one simple modification, as shown below: note the subtle change in the middle expression.
7.2 Runge–Kutta method There are several Runge–Kutta methods for solving differential equation problems. We will look only at the so-called fourth-order one which is often referred to as the RK4 method. The RK4 sequence is shown below without explanation—the development of the equations is elucidated in a number of excellent websites, and a good starting place is [1]. It is traditional to use the symbols k1, k2, k3 and k4 for the various terms so we will avoid using k for loop counters in the examples.
[Runge-Kutta1.sm.] Figure 7.3 shows the RK4 solution to the same problem as solved in section 7.1 with the Euler method.
Figure 7.3. The fourth-order Runge–Kutta method. Some notes on the SMath code before looking at the results: a) The X values are computed before entering the loop by typing , accepting the dynamic assistance offer of range(3) and filling in the place holders. This is not essential but demonstrates another approach. b) The two statements and are used to simplify the typing of the next four statements without having to use indices. c) The last two statements in the loop block could have been combined. d) When experimenting with smaller h values (i.e. larger n values), the reader may wish to delete the code that displays values in the X, Y and Exact vectors. e) Note the absence of eval. When the author was developing the worksheet, he was concentrating on the algorithm and was prepared to return to add the eval function if needed. Even with an n value of 1000, the calculation time was a mere 2 s so it was
decide not to bother with eval. With a mere ten iterations, the RK4 method resulted in y(2) = 0.0034, which is far closer to the exact value of y(2) = 0.0000 than the Euler method gave with far more iterations. With h = 0.02 the result was y(2) = 4.337 × 10−7, and with h = 0.002 the result was y(2) = 4.303 × 10−11. Clearly, the RK4 method excels over Euler’s!
7.3 Cooling by radiation This problem is taken from [2]. A ball at 1200 K is allowed to cool down in air at an ambient temperature of 300 K. Assuming that heat is lost only by radiation, the differential equation for the temperature of the ball is given by:
where θ is in K and t is in seconds. Find the temperature at 480 s using the Runge– Kutta fourth order method. The exact solution of the ordinary differential equation is given by the solution of a nonlinear equation as:
Figure 7.4 shows the SMath page that solves the differential equation and the exact solution which is computed with the solve function. It can be seen that the RK4 result is 647.5726 while the ‘exact’ solution computed by solve is 646.4959. So the error is a mere 0.17%.
Figure 7.4. A second example of the RK4 method. The Holistic Numerical Methods website gives the final exact result as 647.57. This appears to be a typo as it is the Runge–Kutta result. Furthermore, an independent calculation using the Excel Solver tool (constraint setting at 1 × 10−9, and convergence setting at 1 × 10−7) agrees with the SMath value to seven decimal places, and Goal Seek (with the Max Change option set to 0.000001) reported 646.4958.
7.4 Runge–Kutta for systems of equations Consider a pair of simultaneous (coupled) equations
The Runge–Kutta formulas needed to solve this system are:
[RungeKuttaSystem.sm.] Kirchhoff’s voltage law states that the potential differences in a closed circuit sum to zero. In a closed circuit with a resistance of R ohms, a capacitor of C farads, an inductance of H henries, and a voltage source of V(t), the current of I(t) will satisfy the equation
This problem is adapted from [3]. Looking at the circuit in figure 7.5 the currents Ia(t) and Ib(t) must satisfy the two coupled equations
Figure 7.5. Runge–Kutta method with coupled equations. At the instant when the switch is closed at t = 0, the currents are given Ia(0) = 0 and Ib(0) = 0. These are the initial conditions. Rearranging the first equation to give Ia′, differentiating the second and substituting Ia′ gives the two equations needed for the Runge–Kutta method:
The exact solutions for these equations are
The vector T holds the time values, Ca the computed Ia values, and Cb the Ib values. The SMath program runs in about 0.1 s so there was no need to add eval functions.
The table below compares the RK and exact results; the final differences are of the order 1 × 10−5. The SMath file shows how the exact values were computed and how all the values may be displayed in a quasi-table form. time (t)
0
0.1
0.2
0.3
0.4
0.5
Ia
0
0.538255
0.968499
1.310719
1.581265
1.793507
Ia exact
0
0.538264
0.968513
1.310737
1.581284
1.793527
Ib
0
0.319626
0.568782
0.760733
0.906321
1.014402
Ib exact
0
0.319632
0.568792
0.760745
0.906333
1.014415
7.4.1 Using vector functions Figure 7.6 shows a more elegant approach using a vector function. The two functions f(t, Ia, Ib) and g(t, Ia, Ib) are united in the two-row vector function f(t, I). Similarly, the initial conditions are stored in a two-row vector Iinit. The first two statements in the loop are there merely to make it easier to code the statements that follow. It must be realized that k1, and all other k constants, are now two-row vectors, as is I, while C is a 2×n+1 matrix. A similar technique is used to compute the exact values.
Figure 7.6. Coupled functions stored in a vector.
7.5 Second-order differential equations The task is to apply the Runge–Kutta method to determine y(t) given the second-order ordinary differential equation
The second-order OED can be converted into a pair of coupled first-order OEDs with the substitutions u1 = y and u2 = y′; from this we note that
We will use an example to explain this. Let the equation to be solved with the initial conditions be Making the substitution we find we have two first-order OEDs to solve
It was convenient to write this in vector form, since that is the method we shall apply. [RungeKuttaSODE.sm.] For the demonstration we will solve Wolframalph.com gives the solution as Figure 7.7 shows the SMath page that performs the RK4 method with h = 0.25. The RK approximation is in good agreement with the exact solution even with only eight iterations.
Figure 7.7. Runge–Kutta applied to a second-order OED. [RungeKuttaSODE1.sm.] This worksheet shows an RK solution for The reader should note that to make the second page from the first, the only modifications needed were: (1) change the definition of u2 for the new problem, (2) set the initial and final conditions; and (3) set the required value of n (or of h). Of course, in a real life problem where the exact solution is unknown, one would experiment with successively smaller h values until the result converged to within the required precision.
References [1]
http://math.stackexchange.com/questions/528856/explanation-and-proof-of-the-fourth-order-runge-kutta-method? rq=1
[2] Kaw A Holistic Numerical Methods: Transforming Numerical Methods Education for STEM Undergraduates:. http://nm.MathForCollege.com [3] Burden R L and Faires J D 2011 Numerical Analysis 9th edn (Boston, MA: Brooks/Cole)
1Without the eval function, this took about one hour on the author’s Intel Core I5 computer. 2Reader beware: if you start with a starting value of n = 100 (i.e. h = 0.02), the page takes one hour to recalculate even
with the eval functions. For n = 10 (i.e. h = 0.2), the page takes about 30 seconds.
IOP Concise Physics
SMath for Physics A primer Bernard V Liengme
Chapter 8 The SMath Viewer The Viewer is best introduced with an example. Figure 8.1 shows the result of saving an SMath file with extension SM as an executable file with extension EXE.
Figure 8.1. Example of an SMath Viewer application. There are a number of reasons why one would wish to transform the SMath file into an executable file. The principal one is the ease of inputting values together with hiding the algorithm from view and hence not confusing the user. This chapter shows how to make executable files for personal use. They may not be given to other people, other than for educational purposes. A licence from the SMath developer is required to make a commercial application. Additional information on SMath Viewer can be found on these pages of the SMath Studio website [1].
8.1 The basic steps [Resistor.sm & Resistor.exe.] Except for some refinements to make a better product, all that is required is a tested SMath worksheet with which one then performs a SaveAs operation, specifying that it should be an executable file. This brings up a dialog asking if a free or commercial application is required. Figure 8.2 shows the various steps in this process and the final product. To confirm an input box entry, either press Enter or click in any of the boxes on the GUI.
Figure 8.2. The process of making an EXE file.
8.2 A better GUI [Resistor1.sm and Resistor1.exe.] The final product works but it has some confusing features. Since each R value is an element in a vector, we see items such as . It was necessary to initialize to zero so this gets displayed. We can address both issues
rather easily. First we add a descriptor to each item we wish to see in the Viewer dialog. Select the R1 definition, right click on it, and select Show description from the popup menu. Now type in the yellow rectangle, text such as . Do the same to the other two R variables and to Req. Move the insertion point (the red +) to just above the statement , and use the command Insert | Area. While we are working on the file let us round the final result to zero decimals with . The resulting SMath file is seen to the left in figure 8.3. Click on the Area’s ⊟ button (indicated by a red arrow in the left part of the figure) to hide the initialization of Ceq, as seen in the right hand side of figure 8.3. One final step before we save the SM files and then make the EXE file: open the File menu, click on Properties, and in the Title box type . This text will show in the title bar of the EXE file. The result is seen in figure 8.1.
Figure 8.3. Using Insert Area to hide unrequired variables. [Prime.sm & Prime.exe.] In figure 8.4 the SMath script is shown before closing (hiding) the Area; the insert shows the application made from the file after closing the Area.
Figure 8.4. Another example of using Insert Area.
Figure 8.5. Demonstration of units.
8.3 Working with units [Circle.sm and Circle.exe.] Figure 8.5 shows an SM file and its corresponding EXE file. Note the dropdown boxes in the GUI; these allow us to select whichever units we wish for input and output. Why do we have two elements called Area? This is because SMath has some strange area units. It offers acre, ha (hectare), barn (for nuclear calculations), and three odd ones a (1 a = 102 m2) ca (1 ca = m2) and daa (1 daa = 103 m2). By giving results in cm2 and m2 on the worksheet, these become available in the dropdown boxes.
8.4 Adding tabs [TabDemo.sm and TabDemo.exe.] The Viewer application can be given tabs by inserting separators on the SMath page. Separators are normally used on an SMath page to break a printout into separate sheets of paper but separators generate tabs when the page is saved as an executable file. Figure 8.6 shows an example of this. The two horizontal separator lines on the SMath page were added using the command Insert Separator. When the user runs the TabDemo.exe program he will find that the plot is not that wonderful; one can
drag the axes but they cannot be scaled.
Figure 8.6. Demonstration of how to create tabs.
Reference [1]
http://smath.info/wiki/Viewer.ashx http://en.smath.info/forum/yaf_postst1781_SMath-Viewer–simplesample.aspx#post9284 http://en.smath.info/forum/default.aspx?g=posts&m=9315#post9315
IOP Concise Physics
SMath for Physics A primer Bernard V Liengme
Chapter 9 Data exchange with external files There are occasions when it is helpful to exchange data with an external file. The SMath functions of interest to us will be: • wfile(variable, filename) to write data to a file • rfile(filename) to read data from a file • dfile(filename) to delete a file • importData() a more flexible function1 for reading data • other functions discussed in chapter 10; these include extended versions of wfile and rfile, functions to exchange data with Microsoft Excel®.
9.1 Wfile and rfile functions The functions wfile, rfile and dfile always point to a folder called user. With SMath installed on a Windows computer, the functions wfile, rfile, and dfile always point to files in the folder C:\Users\\AppData\Roaming\SMath\user, where is replaced by the name of the currently logged-on user. If you are using the portable version in a folder called SMathMaxima on a thumb drive with label F, then the read/write folder is F:\SMathMaxima\user. A simple way to discover the folder name is to use a command to read a file you are sure does not exist; type read(whatever)= and press Enter. The read will fail and with the mouse pointer hovering over the statement you will see
The wfile and rfile functions should be thought of as a complimentary pair: one writes and the other reads. The user is advised not to attempt to use other functions to read files made by wfile.
9.1.1 Write and read a single variable [Expt1.sm.] Figure 9.1 shows examples of writing a single variable to an external file and reading it back to the SMath page. In the first example, the user typed and SMath returned a value 1 to indicate the write was successful. Some points to bear in mind: The arguments for the filename are NOT typed as a string; this is somewhat unusual.
The wfile() function will overwrite any existing file of the same name; there is no provision to append data to an existing file. The filename is not case sensitive so would work. The only reason for using the TXT extension was to make it easy to use Notepad to view the file contents. In the first example, the variable was defined as a fraction and this is how it was stored in the file; had a real number been used in the definition that is what the TXT file would store. In the second example we see that string variables get stored with quote marks in place. In the third example the Greek π represents the mathematical constant. Of course, the vertical bar in all the Notepad screen captures is merely the mouse pointer.
Figure 9.1. Write and read a single variable.
9.1.2 Write and read a vector [Expt2.sm.] To the left in figure 9.2, the range(3) function was used to generate values in a vector which was written to a TXT file and then read back. To the right, two vectors were augmented into a matrix which was written to a second file and read back. In Try4.txt the data is stored as , the 6, 1 refers to the number of rows and columns respectively. In Try5.txt the final 6, 2 also refers to the row and column count. This way of handling data is unique to wfile and rfile and so precludes reading the file with any other function, or attempting to open the file with, for example, Excel.
Figure 9.2. Exchanging a vector and a matrix with external files.
9.2 The importData(9) function There are two importData functions: a one-argument version2 and a nine-argument version. The latter is more versatile and this is the one we will explore. The syntax is: importData(fName, dsymbol, argsep, delimiter, fmRow, toRow, fmCol, toCol, optim) fname:
file name including path, entered as text or a variable with a string value;
dsymbol
symbol used in file data as decimal point (could be a period or a comma);
argsep
symbol used in file to separate arguments in functions (we will not explore this);
delimiter
symbol used between columns (often a comma or a space);
fmRow, toRow
first and last row to be imported; a zero can be used to denote actual first/last row;
frmCol, toCol
first and last column to be imported; a zero can be used to denote actual first/last column;
optim
use 0 for numerical and 1 for symbolic (we will not explore the
symbolic option). Each of these may be entered as strings or numerical values (as appropriate) or as variables defined in the page. The documentation suggests 0’s can be entered for all but the first argument when you wish to use the function’s default values but the author has had more success using actual values for the arguments dsymbol and delimiter. [ImportDataTXT.sm.] In figure 9.3 we see an SMath page that imports data from a TXT file, shown as an inserted image in the figure. This file could have been generated by typing into Notepad but it was actually made by saving an Excel worksheet as a tabdelimited TXT file. The arguments used in importData are a mixture of variables (for filename), strings (the second and fourth arguments), and either zeros for default values or actual numbers for the row and column specifications. In the top example the entire file is read in, in the second just part of the data is imported, and in the third example two columns are read in separately and augmented into a single matrix.
Figure 9.3. Importing data from a TXT file.
[ImportDataCSV.sm.] In figure 9.4 we see an SMath page that imports data from a comma delimited (CSV) file which could have been generated by typing into Notepad but it was actually made by saving an Excel worksheet as a CSV file, shown as an inserted image in the figure. Once again, we import first the entire file then part of the data. Also in the SM file (but not shown in the figure), a matrix is generated from two columns. More use is made here of variables to define argument values.
Figure 9.4. Importing data from a CSV file. 1
As with all SMath functions, it is important to use the correct case for each letter in the function name. Note the uppercase D. 2The function importData(1) looks for files in C:\Program Files (x86)\Smath Studio. This is a serious disadvantage since
generally one is not allowed to save files in C:\Program Files; the workaround is to save the file elsewhere and use copy and paste. See importData1.sm for an example of the result from this function. When running SMath with Maxima from the folder F:\SmathMaxima, importData(1) looks in that folder; it is easy to save files there.
IOP Concise Physics
SMath for Physics A primer Bernard V Liengme
Chapter 10 SMath with Maxima Professor Martin Kraska’s portable version of SMath, with the Maxima and several other plug-ins incorporated, greatly expands the capabilities of native SMath. It must be borne in mind that this is an unofficial version1, and there is no guarantee that it will be updated as the SMath developer releases new versions of the basic SMath application. The author placed the SMath with Maxima application on a thumb drive in the folder F:\SMathMaxima. He saved his SM files in the folder F:\SMathFiles. It can take a little while for the application to start after you double click its file name SMathStudio_Desktop.exe; there will be no Windows hourglass informing you to wait. It is beyond the scope of this book to give more than just a few examples of the extensions available in the portable version of SMath with Maxima. A machine translation of Professor Kraska’s documentation2 is available from the author’s OneDrive space; please visit3 http://1drv.ms/11uZ6QE.
10.1 Saving options SMath with Maxima has a few additional options for saving a file. These include PDF, XeLaTex, ODF, and XLS or XLSX. The PDF option can be of use. The author was unable to see much use for saving an SM file as XLS or XLSX; see however, the section below on data exchange with Excel. This version of SMath does not support the ability to make executable files as discussed in the SMath Viewer chapter.
10.2 The XY plot feature The Insert dropdown menu contains XY Plot. Figure 10.1 show the plot of a cubic function using both the native SMath 2Dplot feature and the new XY Plot. The second plot is what one gets initially. The origin can be relocated by dragging, and the two axes can be scaled simultaneously with the mouse wheel but not independently. Double clicking an XY plot brings up a dialog box in which various elements of the plot may be formatted. Since the XY plot gives no axes, a red line was added with a Boolean expression. Within the range of the plot (i.e. within −2 < x < 6), the expression (x ⩽ −10) is always false so this plots as zero across the graph.
Figure 10.1. The XY Plot tools.
10.3 Maxima’s equation solving functions SMath with Maxima has several root finding functions including Solve, Bisection, FindRoot, Secant, and Newton–Raphson. The first three are demonstrated here.
10.3.1 Solve function [SolveM.sm.] The Maxima Solve function (note the uppercase S) is more powerful than the native SMath solve. In figure 10.2 we see Solve performing a symbolic operation; given 2y + x = 4 it computes y = (−4 + x)/2. In the first statement the user typed (carefully note the use of the Boolean =), then he used the keyboard shortcut Ctrl+ to get a symbolic optimization, causing SMath to return the left-hand part of the statement . Had the user merely typed = to end the input, the result would have been a red error border. This could be rectified by selecting the statement, right clicking and using Optimization Symbolic.
Figure 10.2. An Example of the Solve function—single equation. The Assign function is not native to SMath, it is used to extract numerical values. [SolveM2.sm.] Figure 10.3 demonstrates the Solve function being use to solve a system of equations (the functions and the variables are placed in row vectors) and a problem with multiple solutions. The Maxima Solve function, like the native roots function, does not work if the variable to be found already has a definition within the worksheet.
Figure 10.3. An example of the Solve function—system of equations. [SolveM3.sm.] A Venturi tube is used to measure the velocity of water in a pipe—see figure 10.4. The Bernoulli principle tells us that
Figure 10.4. Another example of Solve. We are told that A1 is four times A2; conservation of matter tells us how the areas and velocities are related. Since the pipes run horizontally we know that z1 = z2. The experimental data tells us that the manometer height h is 25 cm; given the density of mercury we can compute ΔP = P1 − P2. Then with some algebra we could find a formula for v1. This is shown in the lower right corner of the figure. We would like SMath with Maxima to do that work for us. A function called Berno is defined, the experimental data is added to the page, and the Solve function wrapped in an Assign gives us the answer. All without having to perform all that algebra!
10.3.2 Bisection function The syntax for this nonlinear solver is Bisection (function, variable, upper_limit, lower_limit, precision) with the fourth argument being optional. The Bisection function is very useful when we wish to zone in on a solution known to be within a certain range. [BisectionM.sm.] In section 5.2 the function x3 − 0.165x2 + 3.993×10−4 = 0 was solved by programming the bisection method. Here we solve the same problem using the Bisection function from one of the plug-ins of the SMath with Maxima application. Two forms are shown in figure 10.5; the first uses the three-argument syntax while the second uses four arguments. The fourth one sets the precision, overriding the default of 0.0001. There are other syntax forms with additional arguments.
Figure 10.5. Example of the Bisection function. The first result da = 0.55 looks very suspicious as this is the midpoint between the two limits of 0 and 0.11. However, that result is not surprising when we consider the plot of f(x); the function evaluates to close to zero over a wide range of x. Clearly we need a high precision method to solve f(x) = 0. With the fourth argument set to 1 × 10−8 in the computation of db, we get a solution much closer to zero. Indeed, this value gives an f(x) value closer to zero than does the native solve root.
10.3.3 FindRoot function The syntax for this nonlinear solver is FindRoot (function, starting_values, function_precision, variable_precision) with the third and fourth arguments being optional. The functions are defined using the Boolean = operator in the form constant = function. When the constant and the operator are omitted, FindRoots locates the zeros of the function. [FindRootM1.sm.] The first example for this function solves the same equation as in section 5.4. In figure 10.6 we see how the value used for the Starting_value (aka the
guess) influences the result. These are compared to the results from the native solve function.
Figure 10.6. Example of the FindRoot function. [FindRootM2.sm.] In the next example we use a vector function and a vector list of starting values. For demonstration purposes, units have been included. This worksheet (figure 10.7) finds the values of radius and height which are needed for a cylinder to have a specified volume (here 1 m3) and surface area (here 10 m2). The two functions are entered as elements of the vector f. Oddly, when this is evaluated, the second element lacks the 1 before m3. If V is given a value 2 m3, the 2 is displayed. Carefully note the Boolean equality symbols in both the definition of functions and the settings for the starting values.
Figure 10.7. The FindRoot function with vectors. The use of the Unknowns function is critical. The second argument in FindRoot lists
the unknown variable but we need to know in which order they should be entered—that is the purpose of the Unknowns function. Clearly, this problem has many possible answers. The reader might wish to try other starting values; for example r = 500 cm.
10.4 Golden section search To quote from Wikipedia: “The golden section search is a technique for finding the extremum (minimum or maximum) of a strictly unimodal function by successively narrowing the range of values inside which the extremum is known to exist. The technique derives its name from the fact that the algorithm maintains the function values for triples of points whose distances form a golden ratio.” [GoldenSectionM.sm.] To the left in figure 10.8, the GoldenSectionSearch functions are used to find the extremum of a simple cubic function. To the right there is a more traditional approach; namely, find the values of x which make the differential of the equation zero. The problem here is so trivial that we know that the right hand answers (found with both solve and polyroots) are correct. It was necessary to use fairly narrow ranges to obtain similar results from the golden section. Maybe they are best reserved for problems where the traditional methods are more tiresome.
Figure 10.8. Example of the GoldenSectionSearch functions.
10.5 Linear regression
The portable SMath contains linear regression functions not found in the native version. These include Slope(x-values, y-values), Intercept(x-values, y-values). and Fit(data, variables, equation, parameter_names, initial_values). [LinearRegressM1.sm.] This file uses the first two functions to compute the slope and intercept of the same data as was used in section 4.1. The results (see figure 10.9) are exactly the same, but far less work was required.
Figure 10.9. Example of the Slope and Intercept functions. [LinearRegressM1.sm.] The second example uses the Fit functions to compute the coefficients to fit data to a quadratic. The data was as used in section 4.3. The results (see figure 10.10) are in agreement with the previous calculations within ±1 × 10−6. In this worksheet subscripts (not indices) for the b terms were used. In the definition of the fitting equation, the symbol after y is a Boolean equality.
Figure 10.10. Example of the Fit function.
10.6 Symbolic integration Figure 10.11 demonstrates Maxima’s ability to perform symbolic integration. First the user must cause Maxima to take over the int( ) function by typing followed by =. A ‘thermometer’ gauge appears temporarily and the statement is completed by SMath, as seen in the figure. The same gauge appears whenever a file using Maxima features is opened.
Figure 10.11. Symbolic integration.
The statement with the red border (indicating an error) results when the user types the evaluate operator. There are two remedies: (a) right click the offending statement and
specify Optimization Symbolic, or (b) having typed the integral use not = but Ctrl+ as the keyboard shortcut for symbolic optimization. The author is in the habit of nullifying the takeover at the end of each worksheet as a precaution.
10.7 Data exchange (wfile and rfile) [WfileM.sm.] These two functions have been extended in SMath with Maxima to allow the user to specify the path for writing and reading a file. Figure 10.12 shows two examples. The user was running the SMath application from the folder SMathMaxima on a thumb drive called D. In the top part of the worksheet, data is sent to and read from the user folder within the folder holding the application—this is the normal path for the native wfile and rfile. In the lower part, data is sent to and read from another path. In each example, the file has been given the extension TXT to facilitate examining the file with Notepad.
Figure 10.12. The extended wfile and rfile functions.
10.8 Data exchange with Microsoft Excel® This section gives some simple examples of data exchange with Excel. It is important that the Excel file not be open while running the SMath script. [ReadXLSX.sm.] Figure 10.13 shows how to read data from an existing Excel file using the importData.XLSX functions. In the top example, the first argument gives the full
file name (path included), the second one the worksheet name. In this example, the Excel file was in the folder Test on a thumb with label F. It the path is omitted, the function looks in the same folder as used to store the SM file. The second and third examples show how to read in a single cell and a range, respectively.
Figure 10.13. Importing from an existing Excel file. There are similar functions for Open Document Spreadsheets (ODS) files. [WriteReadXLSX2.sm.] Figure 10.14 demonstrates how to export and import data. After typing , the user adds the evaluate operator (=) and SMath returns 1 if the operation was successful. If no path is included in the filename, the files is generated in “the current folder”—this means the same folder as used to store the SMath file—in the author’s case, this was F:\SMathFiles.
Figure 10.14. Creating an Excel file and reading data back. In the three-argument version, the first argument is the variable as before, the second is just the filename, while the third is the path; e.g. . If the folder does not exist, one is created. With either version of the function, the data is stored in a worksheet named SMath Studio Data. The export functions overwrite existing files of the same name. If an Excel file is open when you execute either an import or an export function, an error results. Sometimes the error states the file is already in use; at other times the error message can be confusing.
10.9 Differential equations SMath with Maxima contains functions for solving differential equations. These include the functions4 rkfixed and Rkadapt which use the Runge–Kutta method, and one called ODE.2 which is little more complicated in that it retuned a Boolean expression which can be converted into an assignment using the Assign function.
10.9.1 The rkfixed function; example 1 [RKfixedM1.sm.] This page uses rkfixed to solve the cooling ball problem we met in
section 7.3 (this problem is from [1]). A ball at 1200 K is allowed to cool down in air at an ambient temperature of 300 K. Assuming that heat is lost only by radiation, the differential equation for the temperature of the ball is given by:
where θ is in K and t is in seconds. Find the temperature at 480 s. The exact solution of the ordinary differential equation is given by the solution of a nonlinear equation as:
The name of this function tells us that the step size is constant as it was in our program in section 7.3. The syntax should be clear from the example—figure 10.15. The result is the matrix R which has n + 1 rows and 2 columns; its first column has the independent variable (here it is t) and the second column holds the computed approximations of the dependent variable (θ). The Math file displays R but the figure shows just data in the last row. The result is exactly the same as we obtained in section 7.3 with the same number of steps. Changing n from 20 to 500 results in very little change in the final temperature so we know we have a method that converges.
Figure 10.15. The rkfixed function: cooling ball problem.
10.9.2 The rkfixed function; example 2 [RKfixedM2.sm.] This page uses rkfixed to solve the simple ODE from section 7.2: find y(2) for the differential equation below given y(0) = 4.
The known solution to this is The author’s first attempt at using rkfixed for this problem yielded unsatisfactory results. Using ten steps as was done in section 7.2, the result was y(2) = 9.2131 which is far from the exact value of zero. Figure 10.16 shows what happens when one experiments
with progressively smaller steps. The matrix Y shows the value of y(2) computed with ever decreasing steps. Even changing the for loop to make 50 calculations resulted in y(2) = 0.849 after 990 steps.
Figure 10.16. The rkfixed function: this time it fails. It is tempting to say the solutions are approaching zero asymptotically but that is only because we know the true solution is zero; the asymptotic limit could well be some small number like 0.025. The fact is that this function fails to solve the differential equation even with 990 steps. Why the built-in function should fail while the program in section 7.2 with ten steps gives a satisfactory result is a mystery that cannot be solved as we have no access to the code for the rkfixed function. [RKfixedM3.sm.] The reader may wish to open this file which solves another ODE with more success, as demonstrated by a satisfactory convergence with decreasing step sizes.
10.9.3 The Rkadapt function The Rkadapt function implements the Runge–Kutta–Fehlberg adaptive method. Unlike rkfixed, Rkadapt examines how fast the solution is changing and adapts its step size accordingly. Although Rkadapt uses non-uniform step sizes internally when it solves the differential equation, it nevertheless returns the solution at equally spaced points. [RKadaptM1.sm.] In this file the problematical OED function in section 10.9.3 is tacked with Rkadapt. Figure 10.17 shows this function is far superior to rkfixed. The computed approximations and the exact results more or less overlap. The final y(2) value is very close to zero; increasing n from 20 to 100 brings it even closer to zero. Experimentation shows this is the value to which it is converging.
Figure 10.17. Rkadapt comes to the rescue.
10.9.4 The Rkadapt function with a system of equations When used to solve systems of equations, the first and fifth arguments in rkfixed and in Rkadapt are vectors. [RKadaptM2.sm.] For this example we revisit the electric circuit problem introduced in section 7.4. Figure 10.18 shows that Rkadapt produces results in excellent agreement with the known values.
Figure 10.18. Rkadapt used with a system of equations.
10.9.5 The ODE.2 function The ODE.2 function does not use a numerical method but rather a symbolic one, producing the solution to the ODE as an equation. [ODE2M1.sm.] In the first example using ODE.2 we solve the differential equation
In figure 10.19 the variable L is assigned the results from the ODE.2 function; in this case there is only one result. The Assign statement is used to ‘capture’ the second element in L. Note that this is a symbolic optimization, so it is quicker to use Ctrl+period rather than = which would require you to reset the optimization of the region. The same is true of all evaluation statements on the page other than the evaluation of the two k values on the last line.
Figure 10.19. Example of ODE.2 function. When the user symbolically evaluated y(t), SMath returned the equations for y(t). Next we define yy as the differential of y (it is hard to give a variable a name like y’). The value 2π is given to ω before solving to evaluate the k terms. Note that this is where the initial conditions are entered. The Solve is wrapped in an Assign so we can capture the k terms. Now when y(t) and yy(t) are evaluated, the k terms are replaced by their numerical values. We can also display the numerical values of the k terms. [ODE2M2.sm.] Once again we look at the problem in section 10.9.2, this time5 using both rkfixed and ODE.2. In figure 10.20 the ODE is solved numerically with rkfixed and symbolically with ODE.2. The L gets data generated by the ODE.2 function, an Assign statement is used to extract the result; this is seen to contain the constant c which needs to be discovered. A Solve within an Assign shows this to be −5. The Maxima function radcan is used to produce y(x) which is our solution; happily, this agrees with what we were told to be the exact solution.
Figure 10.20. A symbolic solution from ODE.2. To enable experimentation, a slider was added to the worksheet. The user can move this to increase n and observe how the rkfixed solution gradually converges toward the exact solution, but never quite reaches it.
10.10 Statistics The portable version of SMath contains many statistics function. There are the descriptive functions including Min, Max, Median, StdDev; distribution functions such as Normal, Student-t, Binomial, Poisson, etc, and a variety of special functions. Details can be found in the translation of Professor Kraska’s manual. However, the researcher with serious
statistics calculation needs is probably best served by the free ‘R’ statistics program.
Reference [1] Kaw A Holistic Numerical Methods: Transforming Numerical Methods Education for STEM Undergraduates http://nm.MathForCollege.com 1See the opening sections of the Overview chapter for the download site for SMath with Maxima. 2The author thanks Professor Kraska for permission to do this. 3OneDrive links can be volatile so if the reader cannot open my folder please email me. 4Note the different capitalization of the two names. 5The author is most grateful to Professor Kraska for this worksheet.