<jupyter_start><jupyter_text>10 Differentiation – Student ActivitySee *Computational Physics* (Landau, Páez, Bordeianu), Chapter 5.5  Implementation of Finite Difference Algorithms in Python*Forward difference* and *central difference* (discussed in class):\begin{align}D_\text{fd} y(t) &\equiv \frac{y(t+h) - y(t)}{h} \\D_\text{cd} y(t) &\equiv \frac{y\Big(t + \frac{h}{2}\Big) - y\Big(t - \frac{h}{2}\Big)}{h}\end{align}and also the *extended difference algorithm*\begin{align}D_\text{ep} y(t) &\equiv \frac{4 D_\text{cd}y(t, h/2) - D_\text{cd}y(t, h)}{3} \\  &= \frac{8\big(y(t+h/4) - y(t-h/4)\big) - \big(y(t+h/2) - y(t-h/2)\big)}{3h}\end{align}<jupyter_code>def D_fd(y, t, h):
    """Forward difference"""
    return (y(t + h) - y(t))/h

def D_cd(y, t, h):
    """Central difference"""
    # implement

def D_ep(y, t, h):
    """Extended difference"""
    # implement<jupyter_output><empty_output><jupyter_text>Test your implementationsTest function: $y(t) = \cos t$1. What is the analytical derivative $\frac{d\cos(t)}{dt}$?1. Calculate the derivative of $y(t) = \cos t$ at $t=0.1, 1, 100$.1. Print derivative and relative error $E = \frac{D y(t) - y^{(1)}(t)}{y^{(1)}(t)}$ (finite difference value $D y(t)$ compared to the analystical value $y^{(1)}(t)$– use numpy functions for "exact" values) as function of $h$.1. Reduce $h$ until you reach machine precision, $h \approx \epsilon_m$1. Plot $\log_{10} |E(h)|$ against $\log_{10} h$.Try to do the above for all three algorithms  Function definitions<jupyter_code>import numpy as np
# test function
y = np.cos

# Analytical derivative (use np.cos, np.sin, np.exp or whatever else you need)
def y1(t):
    # IMPLEMENT ME (remove `pass`)
    pass

t_values = np.array([0.1, 1, 100], dtype=np.float64)<jupyter_output><empty_output><jupyter_text>Use numpy functions for everything because then you can operate on all `t_values` at once.  Evaluate the finite difference derivativesNote that we pass *a function* `y` to the forward difference function `D_fd` and we can also pass a whole array of `t_values`!<jupyter_code>D_fd(y, t_values, 0.1)<jupyter_output><empty_output><jupyter_text>Evaluate the exact derivativesCompute the exact derivatives (again, operate on all $t$ together... start thinking in numpy arrays!)<jupyter_code>y1(t_values)<jupyter_output><empty_output><jupyter_text>Calculation of the **absolute error**: subtract the two arrays that you got previously:<jupyter_code># IMPLEMENT ME<jupyter_output><empty_output><jupyter_text>Calculate the relative error $E$<jupyter_code>def error(Dxx, y, y1, t, h):
    """Relative error."""
    # INCOMPLETE ... replace None with appropriate terms
    return (Dxx(y, t, h) - None)/None<jupyter_output><empty_output><jupyter_text>Note that we pass again a general function for the difference operator so that we can use `error()` with `D_fd()`, `D_cd()` and `D_ep()`.<jupyter_code>error(D_fd, y, y1, t_values, 0.1)<jupyter_output><empty_output><jupyter_text>Plot $|E|$Plot $\log_{10} |E(h)|$ against $\log_{10} h$.<jupyter_code>import matplotlib.pyplot as plt
%matplotlib inline
h_values = 10**(np.arange(-15, -1, 0.1))
abs_errors = np.abs(error(D_fd, y, y1, 0.1, h_values))
# INCOMPLETE, replace None with appropriate terms
plt.loglog(None, None, label="t=0.1")<jupyter_output><empty_output><jupyter_text>Plot the three different $t$ values together in one plot:<jupyter_code># INCOMPLETE: replace None values by appropriate terms
for t in t_values:
    abs_errors = None
    plt.loglog(None, None, label=r"$t={}$".format(t))
ax = plt.gca()
ax.legend(loc="best")
ax.set_xlabel(r"$h$")
ax.set_ylabel(r"$|E|$")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.16232519879352894, 'fraction_numerical': 0.01782286811077598, 'mean_word_length': 5.4911032028469755, 'pattern_counts': {'":': 0, '<': 37, '<?xml version=': 0, '>': 37, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '75766', 'license': 'CC-BY-4.0', 'n_tokens_mistral': 1385, 'n_tokens_neox': 1335, 'n_words': 367, 'path': '10_differentiation/10-differentiation-students.ipynb', 'repo_name': 'nachrisman/PHY494', 'size': '3647'}