using LinearAlgebra using Plots default(linewidth=4, legendfontsize=12) function vander(x, k=nothing) if isnothing(k) k = length(x) end m = length(x) V = ones(m, k) for j in 2:k V[:, j] = V[:, j-1] .* x end V end function vander_chebyshev(x, n=nothing) if isnothing(n) n = length(x) # Square by default end m = length(x) T = ones(m, n) if n > 1 T[:, 2] = x end for k in 3:n #T[:, k] = x .* T[:, k-1] T[:, k] = 2 * x .* T[:,k-1] - T[:, k-2] end T end function chebyshev_regress_eval(x, xx, n) V = vander_chebyshev(x, n) vander_chebyshev(xx, n) / V end runge(x) = 1 / (1 + 10*x^2) runge_noisy(x, sigma) = runge.(x) + randn(size(x)) * sigma CosRange(a, b, n) = (a + b)/2 .+ (b - a)/2 * cos.(LinRange(-pi, 0, n)) vcond(mat, points, nmax) = [cond(mat(points(-1, 1, n))) for n in 2:nmax] degree = 30 x = LinRange(-1, 1, 500) Y = [] for i in 1:20 yi = runge_noisy(x, 0.3) push!(Y, chebyshev_regress_eval(x, x, degree) * yi) end Y = hcat(Y...) @show size(Y) # (number of points in each fit, number of fits) plot(x, Y, label=nothing); plot!(x, runge.(x), color=:black) Ymean = sum(Y, dims=2) / size(Y, 2) plot(x, Ymean, label="\$ E[\\hat{f}(x)] \$") plot!(x, runge.(x), label="\$ f(x) \$") function variance(Y) """Compute the Variance as defined at the top of this activity""" n = size(Y, 2) sum(Y.^2, dims=2)/n - (sum(Y, dims=2) / n) .^2 end Yvar = variance(Y) @show size(Yvar) plot(x, Yvar)