diff --git a/project1/Project1_A3c_least_squares_approximation.png b/project1/Project1_A3c_least_squares_approximation.png index 874382b..f6d6f8c 100644 Binary files a/project1/Project1_A3c_least_squares_approximation.png and b/project1/Project1_A3c_least_squares_approximation.png differ diff --git a/project1/Project1_A3d_least_squares_approximation.png b/project1/Project1_A3d_least_squares_approximation.png index 4ec3c5f..3368e41 100644 Binary files a/project1/Project1_A3d_least_squares_approximation.png and b/project1/Project1_A3d_least_squares_approximation.png differ diff --git a/project1/Project1_A3e_coefficient_error.png b/project1/Project1_A3e_coefficient_error.png index b24d0fb..243f1b0 100644 Binary files a/project1/Project1_A3e_coefficient_error.png and b/project1/Project1_A3e_coefficient_error.png differ diff --git a/project1/Project1_Q3.py b/project1/Project1_Q3.py index 474dcda..2125899 100644 --- a/project1/Project1_Q3.py +++ b/project1/Project1_Q3.py @@ -73,18 +73,18 @@ def f1(t: float) -> float: """ return 1.0 / (1.0 + t**2) -def build_A(N: int, n: int, f: callable) -> tuple[np.ndarray, np.ndarray]: +def build_A(N: int, n: int, f: callable, f_range: tuple) -> tuple[np.ndarray, np.ndarray]: """ Build the matrix A for the least squares problem. Parameters: n + 1 (int): The number of columns in the matrix A. - + f_range (tuple): The range of the function f. Returns: np.ndarray: The constructed matrix A. """ """ - {t_j}j=0->N, t_0=-5, t_N=5, t_j divides [-5, 5] equally + {t_j}j=0->N, t_0=f_range[0], t_N=f_range[1], t_j divides [f_range[0], f_range[1]] equally A = [[1, t_0, t_0^2, t_0^3, ..., t_0^n], [1, t_1, t_1^2, t_1^3, ..., t_1^n], ... @@ -95,7 +95,7 @@ def build_A(N: int, n: int, f: callable) -> tuple[np.ndarray, np.ndarray]: Ax = b, x is the coeffs of the polynomial """ A = np.zeros((N + 1, n + 1), dtype=float) - t = np.linspace(-5, 5, N + 1) + t = np.linspace(f_range[0], f_range[1], N + 1) for i in range(N + 1): A[i, :] = [t[i]**j for j in range(n + 1)] b = np.array([f(t_i) for t_i in t]) @@ -113,7 +113,7 @@ def question_3c(): N = Ns[i] n = ns[i] A = np.zeros((N + 1, n + 1), dtype=float) - A, b = build_A(N, n, f1) + A, b = build_A(N, n, f1, (-5, 5)) x = householder_lstsq(A, b) p_t = sum([x[j] * t**j for j in range(n + 1)]) plt.subplot(1, 3, i + 1) @@ -145,7 +145,7 @@ def question_3d(): N = Ns[i] n = ns[i] A = np.zeros((N + 1, n + 1), dtype=float) - A, b = build_A(N, n, f1) + A, b = build_A(N, n, f1, (-5, 5)) x = householder_lstsq(A, b) p_t = sum([x[j] * t**j for j in range(n + 1)]) plt.subplot(1, 3, i + 1) @@ -169,7 +169,7 @@ def question_3e(): losses = [] for n in ns: N = 2 * n - A, b = build_A(N, n, lambda t: f2(n, t)) + A, b = build_A(N, n, lambda t: f2(n, t), (0, 1)) x = householder_lstsq(A, b) true_coeffs = np.array([1.0 for _ in range(n + 1)]) loss = np.linalg.norm(x - true_coeffs)