1. Solving nonlinear equations, python modules, arrays, lists, functions, scipy, timing and plotting
In this example we investigate the time it takes to reach a certain accuracy using the Newton method and the secant method. Three test cases are considered: rst, conrm that your own code is second order accurate using the number of Newton iterations as a parameter. Then study scipy's Newton and secant method using the tolerance tol as parameter. Consider the determination of the zero of f(x) = exp( x) x.
First some preparations:
- We will use the modules math, time, scipy, scipy.optimze and scilab which need to be imported
- Then we will require an implementation of the function f(x) and of its derivative f0(x)
- As we are interested in the performance of our method in the case where the function evaluation is very costly we will articially increase the time for evaluation of f(x) and its derivative by a substantial amount using the sleep function from the time module
- As we do not know the exact solution, we will use the scipy library Newton method to determine a very accurate approximation as reference solution
- We will use the time function from the time module to determine the time required for the solvers. You might have to do multiple runs of the timing to get an accurate time.
In [ ]: # labbook -- fill in the missing bits see LB
# you will need the modules: math, time, scipy, scipy.optimze and pylab import math as ma
#LB ... fill in the missing bits here ...
# define function and derivative tev = 0.01 # time for one function evaluation (see sleep below)
def f(x):
""" function evaluation """
#LB include the function here as fx = .... tm.sleep(tev) # add some time to mimic a lengthy function evaluation return fx
def df(x):
""" derivative evaluation """
#LB fill in the derivative1.1.1 First experiment: implement very simple Newton method and compare accuracy against time spent.
Second experiment: investigate the tolerance parameter of the scipy newton method
Third experiment: investigating the tolerance parameter for the scipy secant method
Show how to convert any of the three container structures into any other.
What is the shape of an array? How can it be changed? Provide an example.