{ "cells": [ { "cell_type": "markdown", "id": "73bd968b-d970-4a05-94ef-4e7abf990827", "metadata": {}, "source": [ "Chapter 04\n", "\n", "# 迹\n", "Book_4《矩阵力量》 | 鸢尾花书:从加减乘除到机器学习 (第二版)" ] }, { "cell_type": "markdown", "id": "8cc1d765-91db-4530-81ad-0220895c1e85", "metadata": {}, "source": [ "该代码定义了一个 $3 \\times 3$ 矩阵 $A$,并计算其迹(trace)。矩阵 $A$ 的定义为:\n", "\n", "$$\n", "A = \\begin{bmatrix} 1 & -1 & 0 \\\\ 3 & 2 & 4 \\\\ -2 & 0 & 3 \\end{bmatrix}\n", "$$\n", "\n", "矩阵的迹是其主对角线元素之和,公式为:\n", "\n", "$$\n", "\\text{tr}(A) = A_{11} + A_{22} + A_{33}\n", "$$\n", "\n", "因此,矩阵 $A$ 的迹为:\n", "\n", "$$\n", "\\text{tr}(A) = 1 + 2 + 3 = 6\n", "$$\n", "\n", "此代码展示了如何使用 `np.trace` 函数计算矩阵的迹。" ] }, { "cell_type": "markdown", "id": "ba8dee01-3887-4a76-93a9-274b079171a1", "metadata": {}, "source": [ "## 导入所需库" ] }, { "cell_type": "code", "execution_count": 1, "id": "650779c1-a190-44cc-a778-127b2c189962", "metadata": {}, "outputs": [], "source": [ "import numpy as np # 导入NumPy库,用于数值计算" ] }, { "cell_type": "markdown", "id": "5ff0a2c5-dcea-4891-84d4-7a72436e6772", "metadata": {}, "source": [ "## 定义矩阵A" ] }, { "cell_type": "code", "execution_count": 2, "id": "a1a28546-6d6c-4f65-a94f-c8cb27e5ead5", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "array([[ 1, -1, 0],\n", " [ 3, 2, 4],\n", " [-2, 0, 3]])" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A = np.array([[1, -1, 0], # 定义矩阵A\n", " [3, 2, 4],\n", " [-2, 0, 3]])\n", "A" ] }, { "cell_type": "markdown", "id": "7b8f3355-005a-4b5f-be18-41ada700fc7b", "metadata": {}, "source": [ "## 计算矩阵A的迹" ] }, { "cell_type": "code", "execution_count": 3, "id": "9e5b87ef-8278-4900-b60c-6e96a60e5eef", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tr_A = np.trace(A) # 计算矩阵A的迹\n", "tr_A" ] }, { "cell_type": "code", "execution_count": null, "id": "85a80909-2aac-49ed-bb7a-f8cc6b80ee7d", "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "id": "ecd322f4-f919-4be2-adc3-69d28ef25e69", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.7" } }, "nbformat": 4, "nbformat_minor": 5 }