# PHYCS 3730/6720 Lab Exercise

This exercise provides practice with code organization.

The answer file is Mylab09.txt.

#### Exercise 1. Numpy arrays

Use the Python numpy package in Python interactive mode to calculate the following matrix-vector product:
```[  3.   5.  1.] [  1.]
[ -1.   0.  2.] [ -2.]  = ?
[ -4.  -1.  3.] [  1.]
```

#### Exercise 2. Python modular programming

The modular programming style (used by professionals) breaks a problem down into small units that each have a distinct logical function. That makes it much easier to understand, maintain and upgrade the code. So in this exercise you are asked to reorganize the Newton-Raphson nr2.py discussed in the online notes. You can find a copy of that code in ~p6720/examples/python/nr2.py. Optionally, you may use your modified code from lab07 Exercise 3 that combines the evaluation of the function and its derivative in a single function call f_and_df.

For definiteness, call your code findroot.py, but when you hand it in, copy it into the file Mylab09.txt.

Here is how you should organize the code. We want four (three if you use f_and_df) code units, namely, (1 and 2) the existing two called f and dfdx that evaluate the function and its derivative, (3) a new function called nr that runs the Newton-Raphson algorithm, (4) a revised main function main that interacts with the user and calls the function nr to get the solution.

Apart from simply rearranging the existing code, the creative challenge is to arrange the call to nr so it gets the parameters it needs from main and returns the answer and status (converged/not converged) to main.

More specifically, the main function should prompt for and read two values in this order: (1) The starting guess for the solution and (2) the tolerance. When it calls nr it should pass those two input values and get back three output values, namely, the solution (if found), the number of iterations, and an integer giving the status of the solution. The status integer should be equal to zero if the solution was found and one if the method did not converge. The main program should check the status and tell the user if the solution couldn't be found, or tell the user the answer. It should also say how many iterations were taken.

The function nr should have no communication with the user, not even when it fails, and it should not exit if a solution was not found. The function main should take care of that, reporting the solution or reporting the lack of convergence.

When you have checked that your code works correctly, copy it to the answer file.