import numpy as np
def thomas_algorithm(a, b, c, d):
"""
Solve the system of linear equations Ax = d for a tridiagonal matrix A using the Thomas algorithm.
Parameters:
a : list or numpy array
Sub-diagonal (a_1, ..., a_{n-1}) of the tridiagonal matrix A
b : list or numpy array
Main diagonal (b_0, ..., b_{n-1}) of the tridiagonal matrix A
c : list or numpy array
Super-diagonal (c_0, ..., c_{n-2}) of the tridiagonal matrix A
d : list or numpy array
Right-hand side vector
Returns:
x : numpy array
Solution vector
"""
n = len(d)
# Allocate space for the modified coefficients
c_prime = np.zeros(n - 1)
d_prime = np.zeros(n)
# Modify the coefficients
c_prime[0] = c[0] / b[0]
d_prime[0] = d[0] / b[0]
for i in range(1, n):
denom = b[i] - a[i - 1] * c_prime[i - 1]
if i < n - 1:
c_prime[i] = c[i] / denom
d_prime[i] = (d[i] - a[i - 1] * d_prime[i - 1]) / denom
# Backward substitution
x = np.zeros(n)
x[-1] = d_prime[-1]
for i in range(n - 2, -1, -1):
x[i] = d_prime[i] - c_prime[i] * x[i + 1]
return x
# Example usage
a = np.array([1, 1, 1], dtype=float) # Sub-diagonal (n-1 elements)
b = np.array([4, 4, 4, 4], dtype=float) # Main diagonal (n elements)
c = np.array([1, 1, 1], dtype=float) # Super-diagonal (n-1 elements)
d = np.array([5, 6, 6, 5], dtype=float) # Right-hand side vector (n elements)
x = thomas_algorithm(a, b, c, d)
print("Solution:", x)