fix project1 q3 bug

This commit is contained in:
2025-10-21 16:49:59 -04:00
parent 1ecd5a4bbe
commit 323f757b14
4 changed files with 7 additions and 7 deletions

View File

@@ -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)