def plot_runge_different_nodes(): """Plot runge function at different nodes.""" get_interpolator = partial(get_interpolator_monomial_flexible_nodes, problem_runge, 11) interp_unif = get_interpolator(nodes="uniform") interp_cheby = get_interpolator(nodes="chebychev") xvalues = np.linspace(-1, 1, 10000) fig, ax = plt.subplots() ax.plot(xvalues, problem_runge(xvalues), label="True") ax.plot(xvalues, interp_unif(xvalues), label="Uniform") ax.plot(xvalues, interp_cheby(xvalues), label="Chebychev") ax.legend() ax.set_title("Runge function") fig, ax = plt.subplots() ax.plot( xvalues, interp_unif(xvalues) - problem_runge(xvalues), label="Uniform", ) ax.plot( xvalues, interp_cheby(xvalues) - problem_runge(xvalues), label="Chebychev", ) ax.legend() ax.set_title("Approximation error")
def plot_runge_function_cubic(): """Plot cubic runge function.""" xvalues = get_uniform_nodes(10000, -1, 1) for degree in [5, 10, 15]: x_fit = get_uniform_nodes(degree, -1, 1) interp = interp1d(x_fit, problem_runge(x_fit), kind="cubic") yfit = interp(xvalues) fig, ax = plt.subplots() ax.plot(xvalues, problem_runge(xvalues), label="True") ax.plot(xvalues, yfit, label="Approximation") ax.legend() ax.set_title(f"Degree {degree}")
def plot_runge_multiple(): """Plot multiple runge functions.""" a, b = -1, 1 xvals = np.linspace(a, b, 1000) yvals = problem_runge(xvals) fig, ax = plt.subplots() ax.plot(xvals, yvals, label="Function") for degree in [5, 9]: xnodes = np.linspace(a, b, degree) poly = np.polynomial.Polynomial.fit(xnodes, problem_runge(xnodes), degree) yfit = poly(xvals) ax.plot(xvals, yfit, label=" 9th-order") ax.legend()
def test_exercise_1(): """Run test exercise 1.""" index = product([10, 20, 30, 40, 50], np.linspace(-1, 1, 1000)) index = pd.MultiIndex.from_tuples(index, names=("Degree", "Point")) df = pd.DataFrame(columns=["Value", "Approximation"], index=index) df["Value"] = problem_runge(df.index.get_level_values("Point")) for degree in [10, 20, 30, 40, 50]: xnodes = get_uniform_nodes(degree, -1, 1) poly = np.polynomial.Polynomial.fit(xnodes, problem_runge(xnodes), degree) xvalues = df.index.get_level_values("Point").unique() yvalues = poly(xvalues) df.loc[(degree, slice(None)), "Approximation"] = yvalues df["Error"] = df["Value"] - df["Approximation"] df.groupby("Degree").apply(compute_interpolation_error_df).plot()
def plot_problem_runge(): """Plot runge function.""" fig, ax = plt.subplots() xvals = np.linspace(-1, 1, 1000) yvals = problem_runge(xvals) ax.plot(xvals, yvals, label="Function")