Start R in Calculus
Start R in Calculus
Start R in Calculus
S TA R T R IN CALCULUS
PROJECT MOSAIC
2
& partant
ers were la difference de xyz^ fera yz^dx -t- x
unimaginable. Sensibly, the calculations were
+-
presented
xydz^ in a means suitable to the technology of those
3. Lapaper
centuries:
difference de xyz.it eft uyzjlx -+- ux^dy
and quill. The calculus computations of
Ce qui fe prouve comme dans Ic
that era involved the
xygjiu.manipulation of symbols according
regardant le produit xyz^ comme
cas precedent en unc
tofeumathematicallyenderived rules, for instance x2 ! 2x.
eft ainfi des autres a rinfini d oul on
lequantite.il ,
=yd^ -t-
*dy ^.d^=^~^LL
%
l^L=^ en mettanc
^ fa valeur ~ Ce il falloit &c. d ou Ton forme
pour qu
.
,
5
RStudio 11
Fitting 34
Solving 41
Derivatives 54
Anti-Derivatives 59
Dynamics 64
Activities 69
Instructor Notes 73
10
Index 80
1. Starting with RStudio
3+2
[1] 5
2^3
[1] 8
Figure 3: Arithmetic in R
first = 3
second = 4
hypot = sqrt(first^2 + second^2)
myangle = asin(second/hypot)
hypot*cos(myangle)
[1] 3
hypot
[1] 5
Exercises
y = mx + b. install.packages("mosaic")
In order to apply mathematical concepts to realistic You need install the package
only once. (It may already
settings in the world, its important to recognize three have been done for you.) But
things that a notation like y = mx + b does not support you need to load the mosaic
well: package each time you restart
R.
1. Real-world relationships generally involve more than
two quantities. (For example, the Ideal Gas Law in
chemistry, PV = nRT, involves three variables:
pressure, volume, and temperature.) For this reason,
you will need a notation that lets you describe the
multiple inputs to a function and which lets you keep
track of which input is which.
functions & graphing 17
3*x-2
an example of plotting out a linear function: 15
10
plotFun(3*x - 2 ~ x, x.lim=range(0,10) ) 5
20
plotFun(m*x + b ~ x, x.lim=range(0,10), m=3, b=-2 )
m*x+b
15
10
Try these examples: 5
0
plotFun(A*x^2 ~ x, x.lim=range(-2,3), A=10)
plotFun(A*x^2 ~ x, add=TRUE, col="red", A=5) 2 4 6 8
x
plotFun(cos(t) ~ t, t.lim=range(0,4*pi))
g = makeFun(2*x^2 - 5*x + 2 ~ x)
g(x=2) g(x=5)
[1] 0 [1] 27
functions & graphing 19
plotFun(g(x) ~ x, x.lim=range(-5,5))
Exercises
2*x3
t^2
2 2
Translate each of these expressions in 0
traditional math notation into a plot made by
1
2
1 2 3 4 1 0 1
gave to make the plot (not the plot itself). x t
Once the data are read in, you can look at the data just
by typing the name of the object (without quotes!) that is
holding the data. For instance,
housing
names(housing)
housing$Income
housing$CrimeProblem
housing$crim
NULL
40
CrimeProblem
35
dot at the coordinate location given by two variables. For 20000 40000 60000
Income
instance, heres a scatter plot of the percentage of
household that regard their neighborhood as having a Figure 6: A scatterplot.
crime problem, versus the median income in their
bracket.
35
The R statement closely follows the English
equivalent: plot CrimeProblem versus (or, as a function 30
data, then asking plotFun() to add a graph of the 20000 40000 60000
Income
function:
Figure 7: Adding a mathemati-
cal function to the scatterplot.
functions & graphing 23
If, when plotting your data, you prefer to set the limits
of the axes to something of your own choice, you can do
this. For instance:
40
plotPoints( CrimeProblem ~ Income, data=housing,
CrimeProblem
xlim=range(0,100000), ylim=range(0,50) ) 30
Income=range(0,80000), add=TRUE ) 10
Properly made scientific graphics should have 2e+04 4e+04 6e+04 8e+04
informative axis names. You can set the axis names Income
directly in either plotFun() or plotPoints():
40
main="Crime Problem",
30
xlim=range(0,100), ylim=range(0,45) )
20
Exercises
Exercise 1 Exercise 2
Make each of these plots: Construct the R commands to duplicate
(a) Prof. Stan Wagon (see each of these plots. Hand in your commands
http://stanwagon.com) illustrates curve (not the plot):
fitting using measurements of the (a) The data file "utilities.csv" has utility
temperature (in degrees C) of a cup of records for a house in St. Paul, Minnesota,
coffee versus time (in minutes): USA. Make this plot, including the labels:
Ave. Monthly Temp.
s = fetchData("stan-data.csv")
plotPoints(temp ~ time, data=s) 80
Temperature (F)
60
100 40
80 20
temp
60 2 4 6 8 10 12
250
h = fetchData("hawaii.csv") 200
100
50
0
2.0
20 40 60 80
1.5 Temperature (F)
water
1.0
0.5
0.0
0 20 40 60 80
time
95 - 73 * exp(-0.2 * t)
one variable, for instance: 80
60
plotFun(95-73*exp(-.2*t) ~ t,
t.lim=range(0,20)) 40
20
This lesson is about plotting functions of two 5 10 15
variables. For the most part, the format used will be a t
contour plot, but its also possible to make the graph of
the function, as youll see later.
You use the same plotFun() function to plot with two
input variables. The only change is that you need to list
the two variables on the right of the ~ sign, and you need
to give a range for each of the variables. For example:
0.0
8
plotFun( sin(2*pi*t/10)*exp(-.2*x) ~ t & x,
t.lim=range(0,20),x.lim=range(0,10)) 6
x
4 -0.5 0.5
0.5 -0.5
Each of the contours is labeled, and by default the plot
0.0
0.0
2
is filled with color to help guide the eye. If you prefer just
to see the contours, without the color fill, use the 5 10 15
filled=FALSE argument. t
0.0
Occasionally, people want to see the function as a 8
surface, plotted in 3 dimensions. You can get the
6
computer to display a perspective 3-dimensional plot by
x
0.0
plotFun(sin(2*pi*t/10)*exp(-.2*x) ~ t & x,
t.lim=range(0,20),x.lim=range(0,10),surface=TRUE) 5 10 15
t
If you are using RStudio, you can press on the little
gear icon in the plot and you will have a slider to
control the viewpoint. (Try moving the slider to the right,
release it, and wait for the picture to update.)
Its very hard to read quantitative values from a
surface plot the contour plots are much more useful 0.5
for that. On the other hand, people seem to have a strong 0.0
-0.5
10
8 20
6 15
4 10
x 2 5 t
00
26 start r in calculus
x
plotFun(g(t=t,x=x) ~ t & x, 4
0.5 -0.5 0.5 -0.5
0.0
0.0
t.lim=range(0,20),x.lim=range(0,10)) 2
g(t=7,x=4) g(x=4,t=7)
g(7,4) g(4,7)
Exercises
Exercise 1 Exercise 2
Refer to this contour plot: Describe the shape of the contours
produced by each of these functions. (Hint:
6 Make the plot! Caution: Use the mouse to
6
-6
4
4
2
8
2
-4
6
in shape.)
x
4 -2 0
(a) The function
0
40
30
Several three-year old pines of very similar height 20
were measured and tracked over time: age five, age ten, 10
and so on. The trees differ from one another, but they are
5 10 15 20 25
all pretty similar and show a simple pattern: linear
age
growth at first which seems to slow down over time.
It might be interesting to speculate about what sort of
algebraic function the loblolly pines growth follows, but
any such function is just a model. For many purposes,
measuring how the growth rate changes as the trees age,
all thats needed is a smooth function that looks like the
data. Lets consider two:
f1(age=8)
[1] 20.68
f2(age=8)
[1] 20.55
f2
function (age)
{
x <- get(fnames[2])
if (connect)
SF(x)
else SF(x, deriv = deriv)
}
<environment: 0x1046c06d8>
30 start r in calculus
cherry = fetchData("trees") 40
plotPoints(Volume~Girth, data=cherry)
20
g1 = spliner(Volume~Girth, data=cherry)
g2 = connector(Volume~Girth, data=cherry)
plotFun(g1(x)~x,x.lim=range(8,18),xlab="Girth (inches)")
plotFun(g2(x) ~ x, add=TRUE, col="red")
plotPoints(Volume ~ Girth, data=cherry, add=TRUE)
The two functions both follow the data ... but a bit too
faithfully! Each of the functions insists on going through 60
10 12 14 16
Girth (inches)
functions & graphing 31
g3(x)
30
plotFun(g3(x)~x,x.lim=range(8,18),xlab="Girth (inches)") 10
plotPoints(Volume~Girth, data=cherry, add=TRUE) 10 12 14 16
Girth (inches)
Smoothers are well named: they construct a smooth
function that goes close to the data. You have some
control over how smooth the function should be. The
parameter span governs this: 50
40
g4(x)
g4 = smoother(Volume ~ Girth, data=cherry, span=1.0) 30
20
Of course, often you will want to capture relationships 10
where there is more than one variable as the input. 10 12 14 16
Smoothers do this very nicely; just specify which Girth (inches)
variables are to be the inputs.
Figure 8: Control the smooth-
ness of the curve with the span
g5 = smoother(Volume ~ Girth+Height, data=cherry,
parameter.
span=1.0)
plotFun(g5(g,h) ~ g & h,
g.lim=range(8,18), h.lim=range(60,90))
80
You use the formula with the variable you want as the 75
h
40
output of the function on the left side of the tilde, and 70
20
30
[1] 63 [1] 87
Exercises
u = fetchData("utilities.csv") 200
coef(f)
A B
-3.464 253.098
f(temp)
150
100
You can add other functions into the mix easily. For 50
temp
f2 = fitModel(ccf ~ A*temp + B + C*sqrt(temp),
data=u)
plotFun( f2(temp)~temp, temp.lim = range(0,80))
plotPoints(ccf ~ temp, data=u, add=TRUE)
400
automobiles. 20 40 60
temp
hondas = fetchData("used-hondas.csv")
head(hondas)
price will depend both on the mileage and age of the car.
Heres a very simple model that uses both variables:
carPrice1 = fitModel(
Price ~ A + B*Age + C*Mileage,
data=hondas)
miles
30000
18000
16000
A somewhat more sophisticated model might include 20000
17000
whats called an interaction between age and mileage, 10000
20 19000
00
recognizing that the effect of age might be different 0
3 4 5 6 7
depending on mileage.
age
Again, once the function has been fitted, you can plot
it in the ordinary way:
10
00
0
plotFun( carPrice2(Age=age, Mileage=miles)~age & miles, 80000 12
00
0
age.lim=range(0,10), miles.lim=range(0,100000)) 60000
14
00
miles
16 0
40000 00
0
Notice that the price of a used car goes down with age 18
000
20
and with mileage. This is hardly unexpected. The fitted 20000 00
0
model quantifies the relationship, and from the graph you
2 4 6 8
can see that the effect of 2 years of age is roughly the
age
same as 20,000 miles.
Each of the above models has involved what are called
linear parameters. Often, there are parameters in
functions that appear in a nonlinear way. Examples
include k in f (t) = A exp(kt) + C and P in A sin( 2pP t ) + C.
The idea of function fitting applies perfectly well to
nonlinear parameters, but the task is harder for the
computer. Youll get the best results if you give the
computer a hint for the values of nonlinear parameters.
To illustrate, consider the "Income-Housing.csv" data
which shows an exponential relationship between the
fraction of families with two cars and income:
fitting 37
inc = fetchData("Income-Housing.csv")
plotPoints(TwoVehicles ~ Income, data=inc)
TwoVehicles
towards close to 100% of the families having two vehicles. 60
kguess = log(0.5)/25000
kguess
[1] -2.773e-05
100
plotFun(f(Income)~Income, Income.lim=range(0,100000)) 80
60
40
The graph goes satisfyingly close to the data points.
20
But you can also look at the numerical values of the
function for any income: 0
Income
f(Income=10000)
[1] 33.78
38 start r in calculus
f(Income=50000)
[1] 85.44
f(Income=inc$Income)
sum(resids^2)
[1] 5.267
Example: The cooling of a hot object to the ambient 0 50 100 150 200
temperature is generally modeled by an exponential time
process. Lets see. The data "stan-data.csv" contain
Figure 10: The temperature
temperature measurements of a cup of hot water as it of cooling water and a fitted
cools to room temperature. To fit an exponential decay exponential model.
model, T = A + Be kt , well need an estimate for the
nonlinear parameter k. Looking at a plot of the data
fitting 39
water = fetchData("stan-data.csv")
plotPoints(temp~time, data=water)
f = fitModel(temp ~ A + B*exp(-k*time), data=water,
start=list(k=log(2)/50))
plotFun( f(time)~time, add=TRUE, col="red")
You can see from the plot that the model captures the
gross shape of the data, but deviates from it at the start
and at the end. Its helpful to plot out the residuals the 8
data values minus their corresponding model values.
temp - f(time)
6
4
plotPoints( temp - f(time) ~ time, data=water) 2
particular pattern in their deviations from zero. As you 0 50 100 150 200
can see, however, these residuals show systematic trends: time
slow oscillations above and below zero. That indicates
Figure 11: Residuals from the
that the model is not representing the cooling process
model show systematic trends
very well. It turns out that there are at least two cooling around zero.
processes, water to mug and water to air. A model with
two exponentials, one fast and one slow, does a much
better job.
40 start r in calculus
Exercises
Exercise 1 The data in "stan-data.csv" (a) What is the period P (in hours) that
contains measurements made by Prof. Stan makes the sum of square residuals error
Wagon of the temperature of a cooling cup of as small as possible?
hot water. The variables are temp and time: 23.42 24.00 24.28 24.54 24.78 25.17
temperature in degrees C and time in
(b) Plot out the data and the fitted function.
minutes.
You may notice that the best fitting sine
Find the best value of k in the
wave is not particularly close to the data
exponential model A + B exp(kt).
points. One reason for this is that the
(a) Whats the value of k that gives the pattern is more complicated than a simple
smallest sum of square residuals? (Pick sine wave. You can get a better
the closest one.) approximation by including additional
-2.00 -0.20 -0.02 -0.002 -0.0002 sine functions with a period of 2P. (This
(b) What are the units of this k? (This is not is called a harmonic.) Overall, the model
an R question, but a mathematical one.) function will be:
A seconds
B minutes 2p
f 2(t) = A sin (t T0 ) +
C per second P
D per minute 2p
B sin (t T1 ) + C.
P/2
3x + 2 = y
plotFun(sin(x^2)*cos(sqrt(x^4+3)-x^2)-x+1 ~ x, 4
x.lim=range(-3,3)) 2
You can see easily enough that the function crosses the 0
-2 -1 0 1 2
x
solving 43
plotFun(sin(x^2)*(cos(sqrt(x^4+3)-x^2))-x+1 ~ x, 0.0
x.lim=range(1,2))
-0.5
x
findZeros(sin(x^2)*(cos(sqrt(x^4+3)-x^2))-x+1 ~ x,
x.lim=range(1,2))
x
1 1.558
findZeros(sin(x^2)*(cos(sqrt(x^4+3)-x^2))-x+1 ~ x,
x.lim=range(-1000,1000))
x
1 1.558
findZeros(sin(x^2)*(cos(sqrt(x^4+3)-x^2))-x+1 ~ x,
x.lim=range(-Inf,Inf))
x
1 1.558
Setting up a Problem
As the name suggests, findZeros() finds the zeros of
functions. You can set up any solution problem in this
44 start r in calculus
b
1 5e-04
b
1 5e-04
Multiple Solutions
The findZeros() function will try to find multiple
solutions if they exist. For instance, the equation
sin( x ) = 0.35 has an infinite number of solutions. Here
are some of them:
x
1 -12.2088
2 -9.7824
3 -5.9256
4 -3.4992
5 0.3576
6 2.7840
7 6.6408
8 9.0672
solving 45
Exercises
x + 5y = 1
2x + 2y = 1 .
4x + 0y = 1
b = c(1,1,1)
v1 = c(1,2,4)
v2 = c(5,-2,0)
project(b ~ v1 + v2)
[,1]
v1 0.32895
v2 0.09211
0.32894737*v1 + 0.09210526*v2
b - (0.32894737*v1 + 0.09210526*v2)
A = mat( ~ v1 + v2)
A
v1 v2
[1,] 1 5
[2,] 2 -2
[3,] 4 0
x = project( b ~ A)
x
[,1]
Av1 0.32895
Av2 0.09211
A %*% x
[,1]
[1,] 0.7895
[2,] 0.4737
[3,] 1.3158
solving 49
The Intercept
Very often, your projections will involve a vector of all 1s.
This vector is so common that it has a name, the
"intercept." There is even a special notation for the
intercept in the mat() and project() functions: +1. For
instance:
A = mat( ~ v1 + v2 + 1)
A
(Intercept) v1 v2
[1,] 1 1 5
[2,] 1 2 -2
[3,] 1 4 0
b = c(3,5,-1)
v1 = c(1,2,3)
v2 = c(2,4,6)
cars = fetchData("cardata.csv")
[,1]
(Intercept) 46.932738
pounds -0.002902
horsepower -0.144931
A B C
46.932745 -0.002902 -0.144931
Exercises
Exercise 2 Exercise 3
Using project(), solve these sets of
(a) Find x, y, and z that solve the following:
simultaneous linear equations for x, y, and z:
0 1 0 1 0 1 0 1
1 5 1 1 1. Two equations in two unknowns:
x@ 2 A+y@ 2 A+z@ 2 A = @ 1 A.
4 0 3 1 x + 2y = 1
3x + 2y = 7
Whats the value of x?
-0.2353 0.1617 0.4264 1.3235 1.5739 A x = 3 and y = 1
B x = 1 and y = 3
(b) Find x, y, and z that solve the following: C x = 3 and y = 3
0 1 0 1 0 1 0 1 2. Three equations in three unknowns:
1 5 1 1
x@ 2 A+y@ 2 A+z@ 2 A = @ 4 A. x + 2y + 7z = 1
4 0 3 3 3x + 2y + 2z = 7
2x + 3y + z = 7
Whats the value of x?
-0.2353 0.1617 0.4264 1.3235 1.5739 A x = 3.1644, y = 0.8767, z =
0.8082
B x = 0.8767,y = 0.8082, z =
3.1644
C x = 0.8082, y = 3.1644, z =
0.8767
x + 2y + 7z + 8w = 1
3x + 2y + 2z + 2w = 7
2x + 3y + z + w = 7
x + 5y + 3z + w = 3
A x = 5.500, y = 7.356, z =
3.6918, w = 1.1096
B x = 1.1096, y = 3.6918, z =
7.356, w = 5.500
C x = 5.500, y = 7.356, z =
1.1096, w = 3.6918
D x = 1.1096, y = 7.356, z =
5.500, w = 3.6918
4. Three equations in four unknowns:
x + 2y + 7z + 8w = 1
3x + 2y + 2z + 2w = 7
2x + 3y + z + w = 7
True or False There is an exact solution.
(Hint: Whats the residual?)
5. Derivatives & Differentiation
[1] 2 [1] 7
function (x)
2 * x
h = D( sin( abs(x-3) ) ~ x )
h
function (x)
numerical.first.partial(.function, .wrt, .hstep, match.call())
<environment: 0x1035a86a8>
s2 = D( A*sin(2*pi*t/P) + C ~ t)
s2
function (t, A, P, C)
A * (cos(2 * pi * t/P) * (2 * pi/P))
[1] -0.3883
1.0
0.0
-0.5
df = D( sin(x) ~ x )
ddf = D( df(x) ~ x )
Exercises
f = makeFun( x^2 ~ x )
4 4 4
3 2 3
DF(x)
df(x)
f(x)
2 0 2
1 -2 1
0 -4 0
-1 0 1 -1 0 1 -1 0 1
x x x
g = makeFun( 1/(1+exp(-x))~x )
1.0 0.25
0.4
0.8 0.20
0.2
DG(x)
0.6 0.15
dg(x)
g(x)
0.0
0.4 0.10
-0.2
0.2 0.05
-0.4
0.0 0.00
-4 -2 0 2 4 -4 -2 0 2 4 -4 -2 0 2 4
x x x
Flow (cups/sec)
another. But it often happens that the information you 0.10
time (min) 0 5 11 15 22 28 39 45 52 61
filltime (sec) 7 9 12 14 16 17 18 18 19 17
The flow rate has units of cups per second; you can
calculate it as 1/FillTime. Evidently, the leak is slowing at
4
first, then levels out, then seems to be increasing toward
leakdata = fetchData("startR/leak-example.csv")
flow = spliner( 1/filltime ~ time, data=leakdata)
volume = antiD( flow(time)~time )
F(30) - F(10)
[1] 1.335
Exercises
Exercise 1 Find the numerical value of The function being integrated can have
each of the following definite integrals. additional variables or parameters beyond
R 5 1.5
1. x dx the variable of integration. To evaluate the
2
0.58 6.32 20.10 27.29 53.60 107.9 1486.8 definite integral, you need to specify values
R 10 for those additional variables.
2. 0
sin( x2 )dx For example, a very important function
0.58 6.32 20.10 27.29 53.60 107.9 1486.8 in statistics and physics is the Gaussian,
R 4 2x which has a bell-shaped graph:
3. 1
e dx
0.58 6.32 20.10 27.29 53.60 107.9 1486.8 gauss=makeFun((1/sqrt(2*pi*s^2))*exp(-(x-m)^2/
R 2 2| x | m=2,s=1.5)
4. 2
e dx plotFun(gauss(x)~x, x.lim=range(-10,10))
0.58 6.32 20.10 27.29 53.60 107.9 1486.8
0.25
Exercise 2 0.20
0.15
Rb Ra
between a f ( x )dx and b f ( x )dx 0.10
0.05
integrating the same function f , but 0.00
experiment with them to find the (You might want to cut-and-paste this
relationship. definition of f() into your R session.) As you
A They are the same value. can see, its a function of x, but also of the
B One is twice the value of the parameters mean and sigma.
other. Evaluate each of the following definite
C One is negative the other. integrals:
D One is the square of the other. R1
1. 0 gauss( x, m = 0, s = 1)dx
Exercise 3 0.13 0.34 0.48 0.50 0.75 1.00
anti-derivatives 63
R2
2. 0
gauss( x, m = 0, s = 1)dx mathematical is represented as -Inf
0.13 0.34 0.48 0.50 0.75 1.00 on the computer.)
R2 0.13 0.34 0.48 0.50 0.75 1.00
3. 0 gauss( x, m = 0, s = 2)dx
R
0.13 0.34 0.48 0.50 0.75 1.00 5. gauss( x, m = 3, s = 10)dx
R3
4.
gauss( x, m = 3, s = 10)dx. (Hint: The 0.13 0.34 0.48 0.50 0.75 1.00
7. Dynamics
different systems: 2
of t. 1 2 3
dx Time t
= f (t) = 1 t.
dt Figure 15: Solution to dx
=1 t
dt
To find the solution, use antiD() on f (t) :
F = antiD( 1-t ~ t)
dynamics 65
0.8
State x
0.6
tdur=list(from=0,to=4)) 0.4
0.2
Note that its necessary to give an initial condition for 0.0
the state; the argument x=0 sets the initial condition to 1 2 3
zero. You also have to specify the time interval over Time t
which the solution is to be found.
Figure 16: Solution to dx
dt =
Although the two settings involve similar-looking
1 x from initial condition
formulas, they lead to completely different results. x=0
dx
= rx (1 x/K ).
dt
For x < K the population grows while for x > K the
population decays. The state x = K is a stable
equilibrium." Its an equilbrium because, when x = K, the
change of state is nil: dx/dt = 0.
The integrateODE() function takes the differential
equation as an input, together with the initial value of the
state. Numerical values for all parameters must be
specified, as they would in any case to draw a graph of
the solution. In addition, must specify the range of time
for which you want the function x (t). For example, heres
the solution for time running from 0 to 20.
soln$x(0:5)
soln$x(t)
6
plotFun( soln$x(t)~t, t.lim=range(0,20))
4
t
the SIR model of the spread of epidemics, in which the
state is the number of susceptibles S and the number of Figure 17: A solution to
infectives I in the population. Susceptibles become logistic-growth dynamics.
infective by meeting an infective, infectives recover and
leave the system. There is one equation for the change in
S and a corresponding equation for the change in I. The
initial I = 1, corresponding to the start of the epidemic.
200
In the solution, you can see the epidemic grow to a
peak near t = 5. At this point, the number of susceptibles 0
t
to fall as well. In the end, almost every susceptible has
been infected. Figure 18: A solution S(t) and
I (t) to the SIR dynamics.
The phase plane provides a powerful format to
visualize how the state of a two-variable system changes
in time. Each point in the phase plane represents a state
of the system. The dynamical rule the differential
equations describe a flow field. The evolving state of
the system is a trajectory that starts at an initial point and
follows the flow.
dynamics 67
fetchData("mPP.R")
fetchData("DiffEQ.R")
SIR = function(suscept,infective){
a=0.0026; b=0.5
dsuscept = -a*suscept*infective;
dinfective = a*suscept*infective - b*infective;
return( c(dsuscept, dinfective) );
}
Height (m)
3
variables v and x: velocity and height. 2
1
dive = integrateODE( dv~-9.8, dx~v, 0
v=1,x=5,tdur=1.2) 1
plotFun( dive$x(t)~t, t.lim=range(0,1.2)) 0.2 0.4 0.6 0.8 1.0
t
Whats nice about the differential equation format is
Figure 20: Diving without
that its easy to add features like the buoyancy of water buoyancy or drag.
and drag of the water. Well do that here by changing the
acceleration (the dv term) so that when x < 0 the
acceleration is slightly positive with a drag term
proportional to v2 in the direction opposed to the motion. 4
Height (m)
2
diveFloat = integrateODE(
dv~ifelse( h>0, -9.8, 1-sign(v)*v^2), dh~v, 0
v=1,h=5,tdur=10) 2
plotFun( diveFloat$h(t)~t, t.lim=range(0,10))
2 4 6 8
t
According to the model, the diver resurfaces after
slightly more than 5 seconds, and then bobs in the water. Figure 21: Buoyancy returns
the diver to the surface, drag
damps out the oscillations.
Exercises
H = rfun(~x&y, seed=677) 4 -4
plotFun(H(x=x,y=y)~x&y,
2
x.lim=range(-5,5),y.lim=range(-5,5))
-2
-2 0
0 2
0
y
2 6
-2
2. The partial derivatives reflect the slope of the terrain in 8
the cardinal directions along the axes. You can -4 4
example x
dHdx = D(H(x=x,y=y)~x)
0 -2
2
-2
4. Steepness can be either uphill or downhill,
-2
0
v1 = makeFun(pmin(30, 30*t/6) ~ t)
v2 = makeFun(30*pnorm(t,mean=3,sd=1)~t)
v3 = makeFun(ifelse(t>6,30,30*t/6) ~ t)
dat = fetchData("jmm2012data1.csv")
fA = spliner(A~expend,data=dat,monotonic=TRUE)
fB = spliner(B~expend,data=dat,monotonic=TRUE)
You can now use fA and fB like any other function, for
example, plotting
150
plotFun(fA(xA)~xA, xA.lim=range(0,50))
fA(xA)
100
10 20 30 40
xA
72 start r in calculus
Activity 4
Here is an AP Calculus exam problem published by the
College Board. p
If the function f is defined by f ( x ) = x3 + 2, and g
is an antiderivative of f such that g(3) = 5, then g(1) =?
(A) 3.268
(B) 1.585
(C) 1.732
(D) 6.585
(E) 11.585
You can use the antiD() operator to compute the
antiderivative.
g = antiD(sqrt(x^2+2) ~ x)
D( sin(x^2) ~ x )
function (x)
cos(x^2) * (2 * x)
fp = D( sin(x^2) ~ x )
fp( x=2 )
[1] -2.615
x
instructor notes 75
f = makeFun( sin(x^2) ~ x )
f(x=3)
[1] 0.4121
or
F = antiD( f(x) ~ x )
Multiple Variables
In modeling-based calculus, its appropriate to introduce
functions of multiple variables very early. The notation is
designed to make this straightforward. For example:
4
When you create a function of multiple variables,
theres a question of how to identify which variable is 2
x
76 start r in calculus
f( x=1, t=2 )
[1] 0.7787
f( t=2, x=1 )
[1] 0.7787
f(t = t, x = 2)
0.5
plotFun( f(t=t,x=2)~t, t.lim=range(0,10))
0.4
F = antiD( f(t=t,x=x)~x ) 2 4 6 8
Symbolic Parameters
You can use symbols as parameters. The makeFun(), D(),
antiD(), and plotFun() operators will recognize them
and keep them in symbolic form. For instance:
D( A*exp(-k*t) ~ t )
function (t, A, k)
-(A * (exp(-k * t) * k))
gp = D( A*exp(-k*t) ~ t )
plotFun( gp(t,A=2,k=1/10) ~ t, t.lim=range(0,20))
gp(t, A = 2, k = 1/10)
-0.05
-0.10
5 10 15
t
D( a*x^2 + b*x + c ~ x )
function (x, a, b, c)
a * (2 * x) + b
function (x, a, b, c)
a * 2
function (x, y, a, b, c)
c
Anti-Differentiation/Indefinite Integration
F = antiD(exp(x)*x^2 ~ x)
F(x=2) - F(x=1)
[1] 12.06
F = antiD(exp(x)*x^2 ~ x)
F(x=2) # default const. of integration is 0
[1] 12.78
[1] 22.78
[1] 0.6827
instructor notes 79
function (x, y, A, B, C)
A + B * x^2 + C * y^2