UC SCI 111, vM+.  
Notebook 2

Off[General::spell1];
Off[Break::nofwd];
<< Graphics`Colors`

Mathematica prerequisites.

Derivatives : D.

Suppose we have defined a function f:

f[x_] := x^10

We can calculate the derivative with the expression D.

D[f[x], x]

Or, by using the widespread symbol ':

f'[x] == D[f[x], x]

But, you have to be aware that this symbol ' only has a meaning for functions of one argument! For example, what is the interpretation of the following expresssion?

	(sin x y)'

We can calculate the second derivative in at least three different ways:

D[D[f[x], x], x]
f''[x]
D[f[x], {x, 2}]

The tenth derivative would be

D[f[x], {x, 10}]

If we want to define a function that is the derivative of f we can write

h[x_] = D[f[x], x]

Note that in this case we don't use the ":=" in the definition of h, like we did when we defined f. The reason is that in this case an immediate assignment "="  is essential. It assures that the derivative is computed before it is assigned to h. What is the problem with computing it afterwards, like in the case of a delayed assignemnt ":=" ? Find out, by adding a ":", and try for example to explain what happens when you compute h(0).

Exercise 4. 
Define the following function in Mathematica:

	g(x) = ln(1 + (Sqrt[1 - (x^2)]))

What is its derivative? Evaluate it in x=0

Taylor series : Series.

The help files say that Series[f[x],{x,0,n}] constructs the (n^th)order Taylor approximation in x=0 for f according to the formula

	f(
          x)  =  f(0) + (f^′)(0) 
                x + (f^′)′(0) 
                (x^2)/2 +  ...   + (f^((n)))(0) (x^n)/n!
	
Let's try!

f[x_]  :=  x^2
Series[f[x], {x, 0, 3}]

To get some more interesting series we consider a different function

f[x_] := x^2/(2 + Sin[x])
Series[f[x], {x, 0, 3}]

We are tempted to define, by analogy with the construction we used for the derivative,

Clear[h]
h[x_] = Series[f[x], {x, 0, 3}]

This works fine when the argument of h is a variable, or some non-numeric entity:

h[x]

However we can run into trouble, because of the O[x]^4, when we try to evaluate h in a particular point.

h[1]

This is basically because

	((1^2)/2)-((1^3)/4)+O[1]^4
	
is a nonsensical expression. We cannot have something that is of the order (1^4) near 0. However we can evaluate

((1^2)/2) - ((1^3)/4)

which is probably what we wanted to be evaluated in the first place when we typed h[1]. The command that comes to rescue is Normal:

Normal[h[x]]

And we could have written, instead of the above,

h[x_] = 
      Normal[Series[
          f[x], {x, 0, 3}]]

h[1]

Remember though, that the new definition of h forgets about the remainder in terms of an order symbol.

Exercise 5. 
Let f be the function

	f(x) = 1 - sin x + sin\(TraditionalForm\`\(\^2\) x\) +  sin\(TraditionalForm\`\(\^3\) x\) - sin\(TraditionalForm\`\(\^4\) x\)
	
Plot in one picture the graph of f and the n-th  order Taylor approximation of f around x=0 for n=1..10.
Use as domain [-1,1]  and as range [0,2].

Hint: your command should probably look like

	Plot[{f, Taylor Series}, domain, range]

Repeated tasks: Do,  While.

We define a new f

f[x_] := x (1 - x)

Consider the iteration scheme, defined by f. 

	(Subscript[x, n + 1]) = f((Subscript[x, n]))
	
We also choose some starting value (Subscript[x, 0]) and we are interested in the sequence

	(Subscript[x, 0]), (Subscript[x, 1]), (Subscript[x, 2]), (Subscript[x, 3]),(Subscript[x, 4]),...
	
If we do this one by one...

x0 = 1/3

x1 = f[x0]

x2 = f[x1]

... we have a long task ahead of us. 
There are shortcuts available.  The Do statement is a comment that does perform some task we give it as many times as we request.

Do[Print["hi"], {i, 1, 3}]

Do expects two arguments. The first argument is the task, or a collection of tasks we want Do to perform. The second argument tells Do how many times we expect Do to perform the given task(s).

number  =  100;
Do[
Print[i, "  ", 
        number]; 
number  =  
        number  - 10, 
{i, 1, 5}]

Exercise 6. 
Fix  (Subscript[x, 0]) = 1/3. Compute (Subscript[x, 1])... (Subscript[x, 10]) by using Do.

Hint: you'll find out that Mathematica is most willing to show huge fractions. You can avoid this by asking for a numerical approximation.This is given by the command N. So, part of the task that you'll give to Do will look like
	
	val = N[ f[ val ] ]
	
when you started by saying val=1/3.

It looks as if the sequence tends to zero. That is, we did found

	(Subscript[x, 10]) =  0.067625
	
and remark that (Subscript[x, i + 1]) < (Subscript[x, i]), for i =1..10 at least and for our choiche of startvalue (Subscript[x, 0]). 
How could we check if, on the long run,  the sequence indeed tends to zero? Now the While command gives help.

i = 1;
While[
      i  <=  5, 
Print[i]; 
i = 
        i + 1;
]

The While statement performs the tasks we give it, in this case

	Print[i];
	i=i+1;
	
as long as a certain condition holds. In this example the condition is

	i <= 5

Now, let's check if (Subscript[x, n]) becomes smaller then, say, .0001.

n = 0;
val = 1/3;                  
\(While[val >  .0001, 
	n = n + 1; 
	val = N[f[val]]
]\)
Print[n]

This works good! When n=9989, the condition fails which forces While to stop performing it tasks. But what would have happened when the condition that While checks would stay true for every n?

Exercise 7. 
Choose as startvalue  (Subscript[x, 0]) = 1.0001. Check if  the absolute value of (Subscript[x, n]) becomes smaller then .0001. But, make sure that While doesn't perform more then thousands step by building in a safety check in the condition.

Hint: && is the Mathematica command for logical `and' .

Bonus subject:  Nest and recursive functions.

Try this

val = 0.33;
Nest[f, val, 1000]

Nest is one of the statements in Mathematica that is part of functional programming. Roughly functional programming employs expressions that manipulate functions and lists. If ndef is an undefined function we can see what Nest does.

Nest[ndef, x, 3]

Another way of defining an iteration scheme is by using recursive functions.

seq[n_] := f[seq[n - 1]]

seq[0] =  .333;
seq[100]

However, this seems in general slower then using Nest.

The depth of water in a trough.

Introduction.

A trough of length L  has a cross section in the shape of a semicircle with radius r, see the figure below.

Let V denote the volume of the water when the trough is filled to a distance h of the top, then

	V = L {  (r^2)( (π/2) - arcsin (h/r)) - h (Sqrt[(r^2) - (h^2)]) }

In the following interlude, that may be skipped, we derive this formula.

☺ Interlude: derivation of the volume formula.

We start by computing the blue area, that we will call B, in the figure above. First note that ± ((Sqrt[(r^2) - (h^2)]), -h) are  the points of intersection of our circle (x^2) + (y^2) = (r^2)and  the line y = - h. Then
	
	B =  (∫_(-r)^(-h))  \(∫\_\(-\@\(\(r\^2\)\(-\)\(h\^2\)\(\ \)\)\)\%\(\@\(r\^2 - h\^2\)\)\)   dx   dy
	
	    = \(\(2 ∫\)\+\(-r\)\%\(-h\)\) (Sqrt[(r^2) - (y^2)])d y

Mathematica can already integrate this expression, but the answer is a bit dirty yet, so we prefer to continue by hand. We do so by stepping over to polar coordinates. As on the border of the circle r is a constant, φ, the angle of a point on the circle, will be our new integration variable. 

From the sketch we can conclude immediately that we have to integrate from φ = - (π/2), corresponding with the bottom of the circle to φ = -arcsin (h/r), the angle of the point ((Sqrt[(r^2) - (h^2)]), 0). In order to make this precise we  substitute y = r sin φ. Therefore we get (verify!) that

	B = 2 (r^2) (∫_(-(π/2))^(-arcsin(h/r)))(cos^2)φ  dφ

2 r^2 Integrate[(Cos[φ])^2,  {φ, -Pi/
              2, -ArcSin[h/r]}]  // TrigExpand

As you see, Mathematica easily solves this one and we're done when we notice that the total volume equals B times the length L of the trough.

Computing the depth.

Suppose  L= 10  feet,  r=1  foot, and  V=12.4  cubic feet. Having the formula, we can compute the height h, can't we?

Exercise 8.
a)  We can regard our expression for V as a function of h. What is the domain of V=V(h)?
b) Write a function volume[h_].
c) Make a plot of this function and estimate when the volume equals 12.4 cubic feet.
d) Let t(h) be the second order Taylor expansion of V(h) around h=0. Use Mathematica to find an expression for t(h).
e) Solve t(h)=12.4. Does this give a reasonable approximation for the depth of the water? What's the problem with this approach?

Now we want a good and reliable approximation for the depth of the water. So we will use Newton's method. We want to find the depth of the water in the trough to within  0.01  feet.

f) Newton's method finds zeros. Which function will you use for the iteration scheme ?
g) Carry out the Newton iteration using the Do or While statement.

The minimal interest rate of a savings account.

The accumulated value of a savings account based on regular periodic   payments can be determined from the `annuity due equation':

	A = (P/i) ( (((1+i))^( n)) - 1)

In this equation,  A  is the amount of money in the account,  P  is the amount regularly deposited, and  i  is the rate of interest per period for the n deposit periods. To derive the annuity due equation we note that if (Subscript[A, k ])is the amount of money after the k-th deposit than it is obvious that there should hold

	(Subscript[A, 0]) = 0
(Subscript[A, k + 1]) = (1 + i) (Subscript[A, k]) + P

You can check that these conditions are satisfied by the annuity due equation.

You would like to have a savings account valued at $75000 upon retirement in 20 years and you can afford to put $150 per month toward this goal.

Exercise 9.
What is the minimal interest rate at which this amount can be deposited, assuming that the interest is compounded monthly?
Hint: use Newton's method or the bisection method (Kreyszig).