<jupyter_start><jupyter_text>Stiffness in Initial Value Problems¶<jupyter_code>import numpy as np
import matplotlib.pyplot as pt
import seaborn as sns
sns.set_context("talk", font_scale=1.5, rc={"lines.linewidth": 2.5})
sns.set_style("whitegrid")<jupyter_output><empty_output><jupyter_text>Consider $y'=-100y+100t + 101$.Exact solution: $y(t)=1+t+ce^{-100t}$.Exact solution derivative: $y'(t)=1-100ce^{-100t}$.<jupyter_code>def f(t, y):
    return -100*y+100*t + 101
t_end = 0.2

def plot_solution(t0, y0):
    c = (y0-1-t0)/np.exp(-100*t0)
    t_mesh = np.linspace(t0, t_end, 1000)
    solution = 1+t_mesh+c*np.exp(-100*t_mesh)
    
    pt.plot(t_mesh, solution, label="exact")
    pt.plot(t0, y0, "ko")
plot_solution(t0=0, y0=1)
plot_solution(t0=0, y0=1.2)
plot_solution(t0=0, y0=-0.5)
plot_solution(t0=0.05, y0=-0.5)<jupyter_output><empty_output><jupyter_text>Here's a helper function that uses a time stepper in the form of a step_function to numerically solve an ODE and plot the numerical solution:<jupyter_code>def integrate_ode(step_function, t0, y0, h):
    times = [t0]
    ys = [y0]

    while times[-1] <= t_end + 1e-14:
        t = times[-1]
        ys.append(step_function(t, ys[-1], h))
        times.append(t + h)

    pt.plot(times, ys, label=step_function.__name__)
    pt.xlim([t0, t_end])
    pt.ylim([-1, 2])
    pt.legend(loc="best")<jupyter_output><empty_output><jupyter_text>Using an Explicit Method¶ First, implement forward_euler_step(tk, yk, h):<jupyter_code>def forward_euler_step(tk, yk, h):
    return yk + h*f(tk, yk)
t0 = 0.05
y0 = -0.5
h = 0.001  # start this at 0.001, then grow

plot_solution(t0=t0, y0=y0)
integrate_ode(forward_euler_step, t0=t0, y0=y0, h=h)<jupyter_output><empty_output><jupyter_text>What's the main challenge here? Using an Implicit Method¶ Next, implement backward_euler_step(tk, yk, h):<jupyter_code>def backward_euler_step(tk, yk, h):
    tkp1 = tk+h
    return (yk + h*(100*tkp1 + 101))/(1+100*h)
t0 = 0.05
y0 = -0.5
h = 0.001  # start this at 0.001, then grow

plot_solution(t0=t0, y0=y0)
integrate_ode(backward_euler_step, t0=t0, y0=y0, h=h)
pt.xlim([t0, t_end])
pt.ylim([-1, 2])
pt.legend()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.16315307057745188, 'fraction_numerical': 0.06874427131072411, 'mean_word_length': 4.884097035040432, 'pattern_counts': {'":': 1, '<': 22, '<?xml version=': 0, '>': 21, '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': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '348072', 'license': 'MIT', 'n_tokens_mistral': 1041, 'n_tokens_neox': 958, 'n_words': 189, 'path': 'lectures/05_timeintegration/code/stiffness.ipynb', 'repo_name': 'tp5uiuc/soft_systems_course', 'size': '2182'}