数值分析是数学的一个分支,主要研究如何利用计算机等数值计算工具来解决实际问题中的数学问题。翟瑞彩的《数值分析》是一本深受广大学生和教师喜爱的教材。以下是对其中部分课后习题的详细解答。

习题一:牛顿法求根

题目描述:用牛顿法求方程 ( f(x) = x^3 - 3x + 2 ) 的根,初始值为 ( x_0 = 1 )。

解答

牛顿法是一种在实数域和复数域上求解方程近似根的方法。其基本思想是利用函数在某点的切线来逼近函数的根。

def f(x):
    return x**3 - 3*x + 2

def df(x):
    return 3*x**2 - 3

def newton_method(f, df, x0, tol=1e-5, max_iter=100):
    x = x0
    for i in range(max_iter):
        fx = f(x)
        if abs(fx) < tol:
            return x
        dfx = df(x)
        if dfx == 0:
            raise ValueError("Zero derivative encountered.")
        x = x - fx/dfx
    raise ValueError("Maximum iterations reached without convergence.")

root = newton_method(f, df, 1)
print("The root is:", root)

习题二:矩阵求逆

题目描述:求矩阵 ( A = \begin{bmatrix} 1 & 2 \ 3 & 4 \end{bmatrix} ) 的逆矩阵。

解答

求矩阵的逆矩阵是数值分析中的一个基本问题。我们可以使用高斯-约当消元法来求解。

import numpy as np

def inverse_matrix(A):
    A = np.array(A)
    B = np.copy(A)
    n, m = A.shape
    if n != m:
        raise ValueError("Matrix is not square.")
    I = np.eye(n)
    for i in range(n):
        # Find pivot
        max_row = abs(B[i:, i])
        max_row_index = np.argmax(max_row)
        if max_row_index != i:
            B[[i, max_row_index], :] = B[[max_row_index, i], :]
            I[[i, max_row_index], :] = I[[max_row_index, i], :]
        # Make pivot 1
        pivot = B[i, i]
        B[i, :] /= pivot
        I[i, :] /= pivot
        # Eliminate other rows
        for j in range(n):
            if i != j:
                factor = B[j, i]
                B[j, :] -= factor * B[i, :]
                I[j, :] -= factor * I[i, :]
    return I

A = [[1, 2], [3, 4]]
A_inv = inverse_matrix(A)
print("The inverse of A is:\n", A_inv)

习题三:最小二乘法

题目描述:使用最小二乘法求解线性方程组 ( Ax = b ),其中 ( A = \begin{bmatrix} 1 & 2 \ 3 & 4 \end{bmatrix} ),( b = \begin{bmatrix} 8 \ 14 \end{bmatrix} )。

解答

最小二乘法是一种常用的数值方法,用于求解线性方程组的最优解。其基本思想是最小化误差的平方和。

def least_squares(A, b):
    A = np.array(A)
    b = np.array(b)
    x = np.linalg.lstsq(A, b, rcond=None)[0]
    return x

A = [[1, 2], [3, 4]]
b = [8, 14]
x = least_squares(A, b)
print("The solution is:\n", x)

通过以上解答,我们可以看到数值分析在实际问题中的应用。这些方法在工程、科学和经济学等领域都有着广泛的应用。希望这些解答能够帮助你更好地理解和掌握数值分析方法。