Assignment 1

General feedback

Remember to use the validate to check your code and you must submit it by clicking submit

Don’t change the import numpy at the top, otherwise the checks will break and you will lose marks.

You only need to import numpy once, not in every cell.

The main mistakes were misunderstanding the round off error with the smallest dx, and a number of students thought the error in the large dx was also caused by round off.

There were some students who lost marks for not having titles, legends and axes labels.

Other than that it was well done.

Model solution

Automatically marked cells:

def f(x):
    '''Function equivalent to cos(2x), should work for one argument or a numpy array'''
    return numpy.sin(2.*x)
def df_analytic(x):
    '''
    The analytic derivative
    '''
    return 2.*numpy.cos(2.*x)
def central_difference(f, x, dx):
    '''
    This function implements the central difference method for the 
    first derivative of the function f at position x using interval
    dx.
    '''
    return (f(x+dx)-f(x))/dx

Plotting task

xs = numpy.linspace(-2*numpy.pi,2*numpy.pi,100)
df_dx_1 = forward_difference(f, xs, dx=1e-4)
df_dx_2 = forward_difference(f, xs, dx=1e-8)
df_dx_3 = forward_difference(f, xs, dx=1e-12)
df_dx_analytical = df_analytic(xs)
plt.figure(figsize=(8, 4))
plt.plot(xs, df_dx_1 - df_dx_analytical,label="$\Delta x=10^{-4}$ Too large")
plt.plot(xs, df_dx_2 - df_dx_analytical,label="$\Delta x=10^{-8}$ About right")
plt.plot(xs, df_dx_3 - df_dx_analytical,label="$\Delta x=10^{-12}$ Too Small")
plt.legend(loc='lower right')
plt.title("Difference between analytic and numerical derivative of $\sin(2x)$")
plt.xlim([-2.*numpy.pi,12])
plt.ylabel("$f(x)$")
plt.xlabel("$x$")

png

Free text question

So for too large a value of $\Delta x$ then our numerical approximation to the derivative is poor and in the plot we see the first neglected term in the Taylor series. (Not expected for the marks the neglected term is $\propto f’’(x)\Delta x \propto \sin(2x) \Delta x$ which is why we see the sinuosoidal behaviour.)

For too small a value of $\Delta x$ then the difference between $f(x+\Delta x)$ and $f(x)$ becomes small and we lose numerical precision on the calculation of the numerator in the central difference giving the jagged result.