NumPy-源码解析-三十四-

76 阅读1小时+

NumPy 源码解析(三十四)

.\numpy\numpy\polynomial\tests\test_hermite.py

"""Tests for hermite module.

"""
from functools import reduce  # 导入 functools 模块中的 reduce 函数

import numpy as np  # 导入 NumPy 库,并使用 np 别名
import numpy.polynomial.hermite as herm  # 导入 NumPy 中的 Hermite 多项式模块
from numpy.polynomial.polynomial import polyval  # 导入 NumPy 中的多项式求值函数 polyval
from numpy.testing import (  # 导入 NumPy 测试模块中的多个断言函数
    assert_almost_equal, assert_raises, assert_equal, assert_,
    )

H0 = np.array([1])  # Hermite 多项式 H0 的系数
H1 = np.array([0, 2])  # Hermite 多项式 H1 的系数
H2 = np.array([-2, 0, 4])  # Hermite 多项式 H2 的系数
H3 = np.array([0, -12, 0, 8])  # Hermite 多项式 H3 的系数
H4 = np.array([12, 0, -48, 0, 16])  # Hermite 多项式 H4 的系数
H5 = np.array([0, 120, 0, -160, 0, 32])  # Hermite 多项式 H5 的系数
H6 = np.array([-120, 0, 720, 0, -480, 0, 64])  # Hermite 多项式 H6 的系数
H7 = np.array([0, -1680, 0, 3360, 0, -1344, 0, 128])  # Hermite 多项式 H7 的系数
H8 = np.array([1680, 0, -13440, 0, 13440, 0, -3584, 0, 256])  # Hermite 多项式 H8 的系数
H9 = np.array([0, 30240, 0, -80640, 0, 48384, 0, -9216, 0, 512])  # Hermite 多项式 H9 的系数

Hlist = [H0, H1, H2, H3, H4, H5, H6, H7, H8, H9]  # Hermite 多项式系数列表


def trim(x):
    return herm.hermtrim(x, tol=1e-6)  # 调用 hermtrim 函数来修剪 Hermite 多项式的系数


class TestConstants:

    def test_hermdomain(self):
        assert_equal(herm.hermdomain, [-1, 1])  # 断言 Hermite 多项式的定义域

    def test_hermzero(self):
        assert_equal(herm.hermzero, [0])  # 断言 Hermite 多项式零函数的系数为 [0]

    def test_hermone(self):
        assert_equal(herm.hermone, [1])  # 断言 Hermite 多项式单位函数的系数为 [1]

    def test_hermx(self):
        assert_equal(herm.hermx, [0, .5])  # 断言 Hermite 多项式的 x 函数的系数为 [0, 0.5]


class TestArithmetic:
    x = np.linspace(-3, 3, 100)  # 在 [-3, 3] 区间生成 100 个均匀间隔的点作为测试用的自变量 x

    def test_hermadd(self):
        for i in range(5):
            for j in range(5):
                msg = f"At i={i}, j={j}"  # 格式化消息字符串
                tgt = np.zeros(max(i, j) + 1)  # 创建一个长度足够的全零数组
                tgt[i] += 1  # 目标 Hermite 多项式的系数调整
                tgt[j] += 1  # 目标 Hermite 多项式的系数调整
                res = herm.hermadd([0]*i + [1], [0]*j + [1])  # 调用 hermadd 函数进行 Hermite 多项式的加法
                assert_equal(trim(res), trim(tgt), err_msg=msg)  # 断言结果与目标相等,并调用 trim 函数修剪 Hermite 多项式的系数

    def test_hermsub(self):
        for i in range(5):
            for j in range(5):
                msg = f"At i={i}, j={j}"  # 格式化消息字符串
                tgt = np.zeros(max(i, j) + 1)  # 创建一个长度足够的全零数组
                tgt[i] += 1  # 目标 Hermite 多项式的系数调整
                tgt[j] -= 1  # 目标 Hermite 多项式的系数调整
                res = herm.hermsub([0]*i + [1], [0]*j + [1])  # 调用 hermsub 函数进行 Hermite 多项式的减法
                assert_equal(trim(res), trim(tgt), err_msg=msg)  # 断言结果与目标相等,并调用 trim 函数修剪 Hermite 多项式的系数

    def test_hermmulx(self):
        assert_equal(herm.hermmulx([0]), [0])  # 断言 hermmulx 函数对 [0] 返回 [0]
        assert_equal(herm.hermmulx([1]), [0, .5])  # 断言 hermmulx 函数对 [1] 返回 [0, 0.5]
        for i in range(1, 5):
            ser = [0]*i + [1]  # 构造 Hermite 多项式的系数列表
            tgt = [0]*(i - 1) + [i, 0, .5]  # 预期的 Hermite 多项式乘以 x 后的系数列表
            assert_equal(herm.hermmulx(ser), tgt)  # 断言 hermmulx 函数的返回值与预期相等

    def test_hermmul(self):
        # check values of result
        for i in range(5):
            pol1 = [0]*i + [1]  # 构造第一个 Hermite 多项式的系数列表
            val1 = herm.hermval(self.x, pol1)  # 计算第一个 Hermite 多项式在 x 上的值
            for j in range(5):
                msg = f"At i={i}, j={j}"  # 格式化消息字符串
                pol2 = [0]*j + [1]  # 构造第二个 Hermite 多项式的系数列表
                val2 = herm.hermval(self.x, pol2)  # 计算第二个 Hermite 多项式在 x 上的值
                pol3 = herm.hermmul(pol1, pol2)  # 计算两个 Hermite 多项式的乘积
                val3 = herm.hermval(self.x, pol3)  # 计算乘积 Hermite 多项式在 x 上的值
                assert_(len(pol3) == i + j + 1, msg)  # 断言乘积 Hermite 多项式的阶数正确
                assert_almost_equal(val3, val1*val2, err_msg=msg)  # 断言乘积 Hermite 多项式在 x 上的值与预期乘积相近
    # 定义测试函数 test_hermdiv,用于测试 herm 模块中的 hermdiv 函数
    def test_hermdiv(self):
        # 循环遍历 i 的取值范围 [0, 5)
        for i in range(5):
            # 循环遍历 j 的取值范围 [0, 5)
            for j in range(5):
                # 根据当前的 i 和 j 生成调试信息
                msg = f"At i={i}, j={j}"
                # 创建长度为 i 的列表 ci,最后一个元素为 1,其余为 0
                ci = [0]*i + [1]
                # 创建长度为 j 的列表 cj,最后一个元素为 1,其余为 0
                cj = [0]*j + [1]
                # 使用 herm 模块中的 hermadd 函数对 ci 和 cj 进行 Hermite 多项式的加法
                tgt = herm.hermadd(ci, cj)
                # 使用 herm 模块中的 hermdiv 函数计算 tgt 除以 ci 的商和余数
                quo, rem = herm.hermdiv(tgt, ci)
                # 使用 herm 模块中的 hermadd 函数计算 quo 乘以 ci 加上 rem 的结果
                res = herm.hermadd(herm.hermmul(quo, ci), rem)
                # 使用 assert_equal 函数断言 trim(res) 等于 trim(tgt),如果不等则输出错误信息 msg
                assert_equal(trim(res), trim(tgt), err_msg=msg)

    # 定义测试函数 test_hermpow,用于测试 herm 模块中的 hermpow 函数
    def test_hermpow(self):
        # 循环遍历 i 的取值范围 [0, 5)
        for i in range(5):
            # 循环遍历 j 的取值范围 [0, 5)
            for j in range(5):
                # 根据当前的 i 和 j 生成调试信息
                msg = f"At i={i}, j={j}"
                # 创建长度为 i+1 的 numpy 数组 c,元素为 [0, 1, ..., i]
                c = np.arange(i + 1)
                # 使用 reduce 函数和 herm 模块中的 hermmul 函数对 c 重复 j 次进行 Hermite 多项式乘法
                tgt = reduce(herm.hermmul, [c]*j, np.array([1]))
                # 使用 herm 模块中的 hermpow 函数计算 Hermite 多项式 c 的 j 次幂
                res = herm.hermpow(c, j) 
                # 使用 assert_equal 函数断言 trim(res) 等于 trim(tgt),如果不等则输出错误信息 msg
                assert_equal(trim(res), trim(tgt), err_msg=msg)
class TestEvaluation:
    # 定义一维多项式系数 [1, 2.5, 0.75]
    c1d = np.array([2.5, 1., .75])
    # 使用 einsum 函数创建二维多项式系数矩阵
    c2d = np.einsum('i,j->ij', c1d, c1d)
    # 使用 einsum 函数创建三维多项式系数张量
    c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)

    # 生成随机数组,形状为 (3, 5),数值范围在 [-1, 1)
    x = np.random.random((3, 5))*2 - 1
    # 计算多项式在随机数组 x 上的值,多项式系数为 [1, 2, 3]
    y = polyval(x, [1., 2., 3.])

    def test_hermval(self):
        # 检查空输入的情况
        assert_equal(herm.hermval([], [1]).size, 0)

        # 检查正常输入的情况
        x = np.linspace(-1, 1)
        y = [polyval(x, c) for c in Hlist]
        for i in range(10):
            msg = f"At i={i}"
            tgt = y[i]
            # 计算 Hermite 插值,并断言结果近似于目标值
            res = herm.hermval(x, [0]*i + [1])
            assert_almost_equal(res, tgt, err_msg=msg)

        # 检查形状保持不变的情况
        for i in range(3):
            dims = [2]*i
            x = np.zeros(dims)
            # 断言 Hermite 插值的输出形状与预期维度相同
            assert_equal(herm.hermval(x, [1]).shape, dims)
            assert_equal(herm.hermval(x, [1, 0]).shape, dims)
            assert_equal(herm.hermval(x, [1, 0, 0]).shape, dims)

    def test_hermval2d(self):
        x1, x2, x3 = self.x
        y1, y2, y3 = self.y

        # 测试异常情况
        assert_raises(ValueError, herm.hermval2d, x1, x2[:2], self.c2d)

        # 测试值情况
        tgt = y1 * y2
        # 计算二维 Hermite 插值,并断言结果近似于目标值
        res = herm.hermval2d(x1, x2, self.c2d)
        assert_almost_equal(res, tgt)

        # 测试形状情况
        z = np.ones((2, 3))
        # 断言二维 Hermite 插值的输出形状为 (2, 3)
        res = herm.hermval2d(z, z, self.c2d)
        assert_(res.shape == (2, 3))

    def test_hermval3d(self):
        x1, x2, x3 = self.x
        y1, y2, y3 = self.y

        # 测试异常情况
        assert_raises(ValueError, herm.hermval3d, x1, x2, x3[:2], self.c3d)

        # 测试值情况
        tgt = y1 * y2 * y3
        # 计算三维 Hermite 插值,并断言结果近似于目标值
        res = herm.hermval3d(x1, x2, x3, self.c3d)
        assert_almost_equal(res, tgt)

        # 测试形状情况
        z = np.ones((2, 3))
        # 断言三维 Hermite 插值的输出形状为 (2, 3)
        res = herm.hermval3d(z, z, z, self.c3d)
        assert_(res.shape == (2, 3))

    def test_hermgrid2d(self):
        x1, x2, x3 = self.x
        y1, y2, y3 = self.y

        # 测试值情况
        tgt = np.einsum('i,j->ij', y1, y2)
        # 计算二维 Hermite 插值网格,并断言结果近似于目标值
        res = herm.hermgrid2d(x1, x2, self.c2d)
        assert_almost_equal(res, tgt)

        # 测试形状情况
        z = np.ones((2, 3))
        # 断言二维 Hermite 插值网格的输出形状为 (2, 3, 2, 3)
        res = herm.hermgrid2d(z, z, self.c2d)
        assert_(res.shape == (2, 3)*2)

    def test_hermgrid3d(self):
        x1, x2, x3 = self.x
        y1, y2, y3 = self.y

        # 测试值情况
        tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
        # 计算三维 Hermite 插值网格,并断言结果近似于目标值
        res = herm.hermgrid3d(x1, x2, x3, self.c3d)
        assert_almost_equal(res, tgt)

        # 测试形状情况
        z = np.ones((2, 3))
        # 断言三维 Hermite 插值网格的输出形状为 (2, 3, 2, 3, 2, 3)
        res = herm.hermgrid3d(z, z, z, self.c3d)
        assert_(res.shape == (2, 3)*3)
    def test_hermint_axis(self):
        # 检查轴关键字参数的工作情况

        # 创建一个 3x4 的随机数组
        c2d = np.random.random((3, 4))

        # 使用 herm.hermint 函数对 c2d 的转置进行 Hermite 处理,并堆叠成新的数组
        tgt = np.vstack([herm.hermint(c) for c in c2d.T]).T
        # 调用 herm.hermint 函数,指定 axis=0 对 c2d 进行 Hermite 处理
        res = herm.hermint(c2d, axis=0)
        # 断言 res 与 tgt 几乎相等
        assert_almost_equal(res, tgt)

        # 对 c2d 的每一行使用 herm.hermint 函数进行 Hermite 处理,并堆叠成新的数组
        tgt = np.vstack([herm.hermint(c) for c in c2d])
        # 调用 herm.hermint 函数,指定 axis=1 对 c2d 进行 Hermite 处理
        res = herm.hermint(c2d, axis=1)
        # 断言 res 与 tgt 几乎相等
        assert_almost_equal(res, tgt)

        # 对 c2d 的每一行使用 herm.hermint 函数进行 Hermite 处理,同时指定 k=3,并堆叠成新的数组
        tgt = np.vstack([herm.hermint(c, k=3) for c in c2d])
        # 调用 herm.hermint 函数,指定 k=3 和 axis=1 对 c2d 进行 Hermite 处理
        res = herm.hermint(c2d, k=3, axis=1)
        # 断言 res 与 tgt 几乎相等
        assert_almost_equal(res, tgt)
class TestDerivative:

    def test_hermder(self):
        # 检查异常情况
        assert_raises(TypeError, herm.hermder, [0], .5)
        assert_raises(ValueError, herm.hermder, [0], -1)

        # 检查零阶导数不产生变化
        for i in range(5):
            tgt = [0]*i + [1]
            res = herm.hermder(tgt, m=0)
            assert_equal(trim(res), trim(tgt))

        # 检查导数与积分的逆关系
        for i in range(5):
            for j in range(2, 5):
                tgt = [0]*i + [1]
                res = herm.hermder(herm.hermint(tgt, m=j), m=j)
                assert_almost_equal(trim(res), trim(tgt))

        # 检查带有缩放的导数
        for i in range(5):
            for j in range(2, 5):
                tgt = [0]*i + [1]
                res = herm.hermder(herm.hermint(tgt, m=j, scl=2), m=j, scl=.5)
                assert_almost_equal(trim(res), trim(tgt))

    def test_hermder_axis(self):
        # 检查轴关键字的工作情况
        c2d = np.random.random((3, 4))

        tgt = np.vstack([herm.hermder(c) for c in c2d.T]).T
        res = herm.hermder(c2d, axis=0)
        assert_almost_equal(res, tgt)

        tgt = np.vstack([herm.hermder(c) for c in c2d])
        res = herm.hermder(c2d, axis=1)
        assert_almost_equal(res, tgt)


class TestVander:
    # 在 [-1, 1) 范围内生成一些随机值
    x = np.random.random((3, 5))*2 - 1

    def test_hermvander(self):
        # 检查 1 维 x 的情况
        x = np.arange(3)
        v = herm.hermvander(x, 3)
        assert_(v.shape == (3, 4))
        for i in range(4):
            coef = [0]*i + [1]
            assert_almost_equal(v[..., i], herm.hermval(x, coef))

        # 检查 2 维 x 的情况
        x = np.array([[1, 2], [3, 4], [5, 6]])
        v = herm.hermvander(x, 3)
        assert_(v.shape == (3, 2, 4))
        for i in range(4):
            coef = [0]*i + [1]
            assert_almost_equal(v[..., i], herm.hermval(x, coef))

    def test_hermvander2d(self):
        # 同时测试非方形系数数组的 hermval2d
        x1, x2, x3 = self.x
        c = np.random.random((2, 3))
        van = herm.hermvander2d(x1, x2, [1, 2])
        tgt = herm.hermval2d(x1, x2, c)
        res = np.dot(van, c.flat)
        assert_almost_equal(res, tgt)

        # 检查形状
        van = herm.hermvander2d([x1], [x2], [1, 2])
        assert_(van.shape == (1, 5, 6))

    def test_hermvander3d(self):
        # 同时测试非方形系数数组的 hermval3d
        x1, x2, x3 = self.x
        c = np.random.random((2, 3, 4))
        van = herm.hermvander3d(x1, x2, x3, [1, 2, 3])
        tgt = herm.hermval3d(x1, x2, x3, c)
        res = np.dot(van, c.flat)
        assert_almost_equal(res, tgt)

        # 检查形状
        van = herm.hermvander3d([x1], [x2], [x3], [1, 2, 3])
        assert_(van.shape == (1, 5, 24))


class TestFitting:

class TestCompanion:
    # 测试函数,验证 hermcompanion 函数在接收空列表时是否引发 ValueError 异常
    def test_raises(self):
        assert_raises(ValueError, herm.hermcompanion, [])
    
    # 测试函数,验证 hermcompanion 函数在接收包含一个元素的列表时是否引发 ValueError 异常
    def test_dimensions(self):
        # 对于每个 i 在范围 [1, 5) 中
        for i in range(1, 5):
            # 创建一个系数列表,长度为 i+1,末尾元素为 1,其余元素为 0
            coef = [0]*i + [1]
            # 断言 hermcompanion 函数返回的矩阵形状为 (i, i)
            assert_(herm.hermcompanion(coef).shape == (i, i))
    
    # 测试函数,验证 hermcompanion 函数在接收系数列表 [1, 2] 时,返回的第一个元素的值是否为 -0.25
    def test_linear_root(self):
        assert_(herm.hermcompanion([1, 2])[0, 0] == -.25)
class TestGauss:

    def test_100(self):
        # 调用 hermgauss 函数生成 Hermite-Gauss 积分的节点和权重
        x, w = herm.hermgauss(100)

        # 测试正交性。注意需要对结果进行归一化,否则像 Laguerre 这样快速增长的函数可能产生非常大的值,令人困惑。
        v = herm.hermvander(x, 99)
        vv = np.dot(v.T * w, v)
        # 计算对角线上的标准化因子
        vd = 1/np.sqrt(vv.diagonal())
        vv = vd[:, None] * vv * vd
        # 断言结果应接近单位矩阵
        assert_almost_equal(vv, np.eye(100))

        # 检查积分 1 的正确性
        tgt = np.sqrt(np.pi)
        assert_almost_equal(w.sum(), tgt)


class TestMisc:

    def test_hermfromroots(self):
        # 测试从根生成 Hermite 多项式
        res = herm.hermfromroots([])
        assert_almost_equal(trim(res), [1])
        for i in range(1, 5):
            roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2])
            pol = herm.hermfromroots(roots)
            res = herm.hermval(roots, pol)
            tgt = 0
            # 断言多项式的阶数
            assert_(len(pol) == i + 1)
            # 断言 Hermite 多项式的最高次数系数为 1
            assert_almost_equal(herm.herm2poly(pol)[-1], 1)
            # 断言计算的结果与目标值一致
            assert_almost_equal(res, tgt)

    def test_hermroots(self):
        # 测试 Hermite 多项式的根
        assert_almost_equal(herm.hermroots([1]), [])
        assert_almost_equal(herm.hermroots([1, 1]), [-.5])
        for i in range(2, 5):
            tgt = np.linspace(-1, 1, i)
            res = herm.hermroots(herm.hermfromroots(tgt))
            # 断言修剪后的结果与目标值一致
            assert_almost_equal(trim(res), trim(tgt))

    def test_hermtrim(self):
        coef = [2, -1, 1, 0]

        # 测试异常情况
        assert_raises(ValueError, herm.hermtrim, coef, -1)

        # 测试结果
        assert_equal(herm.hermtrim(coef), coef[:-1])
        assert_equal(herm.hermtrim(coef, 1), coef[:-3])
        assert_equal(herm.hermtrim(coef, 2), [0])

    def test_hermline(self):
        # 测试生成 Hermite 多项式的系数
        assert_equal(herm.hermline(3, 4), [3, 2])

    def test_herm2poly(self):
        for i in range(10):
            # 断言 Hermite 多项式到多项式的转换结果
            assert_almost_equal(herm.herm2poly([0]*i + [1]), Hlist[i])

    def test_poly2herm(self):
        for i in range(10):
            # 断言多项式到 Hermite 多项式的转换结果
            assert_almost_equal(herm.poly2herm(Hlist[i]), [0]*i + [1])

    def test_weight(self):
        x = np.linspace(-5, 5, 11)
        tgt = np.exp(-x**2)
        res = herm.hermweight(x)
        # 断言权重函数的计算结果与目标值一致
        assert_almost_equal(res, tgt)

.\numpy\numpy\polynomial\tests\test_hermite_e.py

"""Tests for hermite_e module.

"""
from functools import reduce  # 导入 functools 模块中的 reduce 函数

import numpy as np  # 导入 NumPy 库并简写为 np
import numpy.polynomial.hermite_e as herme  # 导入 NumPy 中的 Hermite 多项式模块
from numpy.polynomial.polynomial import polyval  # 从 NumPy 多项式模块中导入 polyval 函数
from numpy.testing import (  # 从 NumPy 测试模块中导入多个断言函数
    assert_almost_equal, assert_raises, assert_equal, assert_,
    )

He0 = np.array([1])  # 定义 Hermite 多项式 H0
He1 = np.array([0, 1])  # 定义 Hermite 多项式 H1
He2 = np.array([-1, 0, 1])  # 定义 Hermite 多项式 H2
He3 = np.array([0, -3, 0, 1])  # 定义 Hermite 多项式 H3
He4 = np.array([3, 0, -6, 0, 1])  # 定义 Hermite 多项式 H4
He5 = np.array([0, 15, 0, -10, 0, 1])  # 定义 Hermite 多项式 H5
He6 = np.array([-15, 0, 45, 0, -15, 0, 1])  # 定义 Hermite 多项式 H6
He7 = np.array([0, -105, 0, 105, 0, -21, 0, 1])  # 定义 Hermite 多项式 H7
He8 = np.array([105, 0, -420, 0, 210, 0, -28, 0, 1])  # 定义 Hermite 多项式 H8
He9 = np.array([0, 945, 0, -1260, 0, 378, 0, -36, 0, 1])  # 定义 Hermite 多项式 H9

Helist = [He0, He1, He2, He3, He4, He5, He6, He7, He8, He9]  # 将 Hermite 多项式存入列表中


def trim(x):
    return herme.hermetrim(x, tol=1e-6)  # 调用 herme.hermetrim 函数,用于修剪 Hermite 多项式


class TestConstants:

    def test_hermedomain(self):
        assert_equal(herme.hermedomain, [-1, 1])  # 断言检查 herme.hermedomain 是否为 [-1, 1]

    def test_hermezero(self):
        assert_equal(herme.hermezero, [0])  # 断言检查 herme.hermezero 是否为 [0]

    def test_hermeone(self):
        assert_equal(herme.hermeone, [1])  # 断言检查 herme.hermeone 是否为 [1]

    def test_hermex(self):
        assert_equal(herme.hermex, [0, 1])  # 断言检查 herme.hermex 是否为 [0, 1]


class TestArithmetic:
    x = np.linspace(-3, 3, 100)  # 创建一个包含 100 个元素的等差数列,范围从 -3 到 3

    def test_hermeadd(self):
        for i in range(5):  # 循环遍历 i 从 0 到 4
            for j in range(5):  # 循环遍历 j 从 0 到 4
                msg = f"At i={i}, j={j}"  # 格式化消息字符串
                tgt = np.zeros(max(i, j) + 1)  # 创建一个长度为 max(i, j) + 1 的全零数组
                tgt[i] += 1  # 将数组 tgt 的第 i 个元素设为 1
                tgt[j] += 1  # 将数组 tgt 的第 j 个元素设为 1
                res = herme.hermeadd([0]*i + [1], [0]*j + [1])  # 调用 herme.hermeadd 函数
                assert_equal(trim(res), trim(tgt), err_msg=msg)  # 断言检查修剪后的 res 是否等于修剪后的 tgt

    def test_hermesub(self):
        for i in range(5):  # 循环遍历 i 从 0 到 4
            for j in range(5):  # 循环遍历 j 从 0 到 4
                msg = f"At i={i}, j={j}"  # 格式化消息字符串
                tgt = np.zeros(max(i, j) + 1)  # 创建一个长度为 max(i, j) + 1 的全零数组
                tgt[i] += 1  # 将数组 tgt 的第 i 个元素设为 1
                tgt[j] -= 1  # 将数组 tgt 的第 j 个元素设为 -1
                res = herme.hermesub([0]*i + [1], [0]*j + [1])  # 调用 herme.hermesub 函数
                assert_equal(trim(res), trim(tgt), err_msg=msg)  # 断言检查修剪后的 res 是否等于修剪后的 tgt

    def test_hermemulx(self):
        assert_equal(herme.hermemulx([0]), [0])  # 断言检查 herme.hermemulx([0]) 是否为 [0]
        assert_equal(herme.hermemulx([1]), [0, 1])  # 断言检查 herme.hermemulx([1]) 是否为 [0, 1]
        for i in range(1, 5):  # 循环遍历 i 从 1 到 4
            ser = [0]*i + [1]  # 创建一个 Hermite 多项式系数列表
            tgt = [0]*(i - 1) + [i, 0, 1]  # 创建目标 Hermite 多项式系数列表
            assert_equal(herme.hermemulx(ser), tgt)  # 断言检查 herme.hermemulx 函数的输出是否等于 tgt

    def test_hermemul(self):
        # check values of result
        for i in range(5):  # 循环遍历 i 从 0 到 4
            pol1 = [0]*i + [1]  # 创建第一个 Hermite 多项式系数列表
            val1 = herme.hermeval(self.x, pol1)  # 计算第一个 Hermite 多项式在 x 上的值
            for j in range(5):  # 循环遍历 j 从 0 到 4
                msg = f"At i={i}, j={j}"  # 格式化消息字符串
                pol2 = [0]*j + [1]  # 创建第二个 Hermite 多项式系数列表
                val2 = herme.hermeval(self.x, pol2)  # 计算第二个 Hermite 多项式在 x 上的值
                pol3 = herme.hermemul(pol1, pol2)  # 调用 herme.hermemul 函数得到两个 Hermite 多项式的乘积
                val3 = herme.hermeval(self.x, pol3)  # 计算乘积 Hermite 多项式在 x 上的值
                assert_(len(pol3) == i + j + 1, msg)  # 断言检查乘积 Hermite 多项式的长度是否为 i + j + 1
                assert_almost_equal(val3, val1 * val2, err_msg=msg)  # 断言检查乘积 Hermite 多项式在 x 上的值是否接近于 val1 * val2
    # 定义一个测试函数,用于测试 hermediv 方法
    def test_hermediv(self):
        # 循环遍历 i 范围内的值,从 0 到 4
        for i in range(5):
            # 循环遍历 j 范围内的值,从 0 到 4
            for j in range(5):
                # 构造消息字符串,指示当前的 i 和 j 值
                msg = f"At i={i}, j={j}"
                # 创建包含 i 个 0 和一个 1 的列表 ci
                ci = [0]*i + [1]
                # 创建包含 j 个 0 和一个 1 的列表 cj
                cj = [0]*j + [1]
                # 调用 hermeadd 方法,计算 ci 和 cj 的和,并赋给 tgt
                tgt = herme.hermeadd(ci, cj)
                # 调用 hermediv 方法,计算 tgt 除以 ci 的商和余数,分别赋给 quo 和 rem
                quo, rem = herme.hermediv(tgt, ci)
                # 调用 hermeadd 方法,计算 quo 乘以 ci 加上 rem,赋给 res
                res = herme.hermeadd(herme.hermemul(quo, ci), rem)
                # 断言 trim 后的 res 等于 trim 后的 tgt,如果不等则输出错误消息 msg
                assert_equal(trim(res), trim(tgt), err_msg=msg)

    # 定义一个测试函数,用于测试 hermepow 方法
    def test_hermepow(self):
        # 循环遍历 i 范围内的值,从 0 到 4
        for i in range(5):
            # 循环遍历 j 范围内的值,从 0 到 4
            for j in range(5):
                # 构造消息字符串,指示当前的 i 和 j 值
                msg = f"At i={i}, j={j}"
                # 创建一个包含从 0 到 i 的连续整数的 numpy 数组 c
                c = np.arange(i + 1)
                # 使用 reduce 函数和 hermemul 方法,计算 c 中的元素的 j 次乘积,初始值为 1,赋给 tgt
                tgt = reduce(herme.hermemul, [c]*j, np.array([1]))
                # 调用 hermepow 方法,计算 c 的 j 次幂,赋给 res
                res = herme.hermepow(c, j)
                # 断言 trim 后的 res 等于 trim 后的 tgt,如果不等则输出错误消息 msg
                assert_equal(trim(res), trim(tgt), err_msg=msg)
class TestEvaluation:
    # 一维多项式系数,对应于 1 + 2*x + 3*x**2
    c1d = np.array([4., 2., 3.])
    # 二维数组,使用 einsum 计算外积
    c2d = np.einsum('i,j->ij', c1d, c1d)
    # 三维数组,使用 einsum 计算三阶张量
    c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)

    # 在 [-1, 1) 内生成随机值的 3x5 数组
    x = np.random.random((3, 5))*2 - 1
    # 根据多项式在 x 上的求值结果
    y = polyval(x, [1., 2., 3.])

    def test_hermeval(self):
        # 检查空输入时的行为
        assert_equal(herme.hermeval([], [1]).size, 0)

        # 检查正常输入情况下的行为
        x = np.linspace(-1, 1)
        y = [polyval(x, c) for c in Helist]
        for i in range(10):
            msg = f"At i={i}"
            tgt = y[i]
            # 调用 hermeval 函数计算 Hermite 插值结果,并进行近似相等断言
            res = herme.hermeval(x, [0]*i + [1])
            assert_almost_equal(res, tgt, err_msg=msg)

        # 检查形状是否保持不变
        for i in range(3):
            dims = [2]*i
            x = np.zeros(dims)
            # 验证 hermeval 函数在不同维度的输入下返回的结果形状
            assert_equal(herme.hermeval(x, [1]).shape, dims)
            assert_equal(herme.hermeval(x, [1, 0]).shape, dims)
            assert_equal(herme.hermeval(x, [1, 0, 0]).shape, dims)

    def test_hermeval2d(self):
        x1, x2, x3 = self.x
        y1, y2, y3 = self.y

        # 测试异常情况
        assert_raises(ValueError, herme.hermeval2d, x1, x2[:2], self.c2d)

        # 测试正常值情况
        tgt = y1 * y2
        # 调用 hermeval2d 函数计算二维 Hermite 插值结果,并进行近似相等断言
        res = herme.hermeval2d(x1, x2, self.c2d)
        assert_almost_equal(res, tgt)

        # 测试形状是否保持不变
        z = np.ones((2, 3))
        # 验证 hermeval2d 函数在不同维度的输入下返回的结果形状
        assert_(res.shape == (2, 3))

    def test_hermeval3d(self):
        x1, x2, x3 = self.x
        y1, y2, y3 = self.y

        # 测试异常情况
        assert_raises(ValueError, herme.hermeval3d, x1, x2, x3[:2], self.c3d)

        # 测试正常值情况
        tgt = y1 * y2 * y3
        # 调用 hermeval3d 函数计算三维 Hermite 插值结果,并进行近似相等断言
        res = herme.hermeval3d(x1, x2, x3, self.c3d)
        assert_almost_equal(res, tgt)

        # 测试形状是否保持不变
        z = np.ones((2, 3))
        # 验证 hermeval3d 函数在不同维度的输入下返回的结果形状
        assert_(res.shape == (2, 3))

    def test_hermegrid2d(self):
        x1, x2, x3 = self.x
        y1, y2, y3 = self.y

        # 测试值情况
        tgt = np.einsum('i,j->ij', y1, y2)
        # 调用 hermegrid2d 函数计算二维 Hermite 插值的网格结果,并进行近似相等断言
        res = herme.hermegrid2d(x1, x2, self.c2d)
        assert_almost_equal(res, tgt)

        # 测试形状是否保持不变
        z = np.ones((2, 3))
        # 验证 hermegrid2d 函数在不同维度的输入下返回的结果形状
        assert_(res.shape == (2, 3) * 2)

    def test_hermegrid3d(self):
        x1, x2, x3 = self.x
        y1, y2, y3 = self.y

        # 测试值情况
        tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
        # 调用 hermegrid3d 函数计算三维 Hermite 插值的网格结果,并进行近似相等断言
        res = herme.hermegrid3d(x1, x2, x3, self.c3d)
        assert_almost_equal(res, tgt)

        # 测试形状是否保持不变
        z = np.ones((2, 3))
        # 验证 hermegrid3d 函数在不同维度的输入下返回的结果形状
        assert_(res.shape == (2, 3) * 3)


class TestIntegral:
    # 定义一个测试函数,用于测试 hermeint 函数在不同轴上的行为
    def test_hermeint_axis(self):
        # 检查 axis 关键字参数是否有效
        c2d = np.random.random((3, 4))  # 创建一个 3x4 的随机数数组 c2d

        # 在轴为1的方向上对 c2d 中每列应用 hermeint 函数,然后垂直堆叠得到 tgt
        tgt = np.vstack([herme.hermeint(c) for c in c2d.T]).T
        res = herme.hermeint(c2d, axis=0)  # 调用 hermeint 函数,指定 axis=0
        assert_almost_equal(res, tgt)  # 断言结果 res 与目标 tgt 几乎相等

        # 在轴为0的方向上对 c2d 中每行应用 hermeint 函数,然后垂直堆叠得到 tgt
        tgt = np.vstack([herme.hermeint(c) for c in c2d])
        res = herme.hermeint(c2d, axis=1)  # 调用 hermeint 函数,指定 axis=1
        assert_almost_equal(res, tgt)  # 断言结果 res 与目标 tgt 几乎相等

        # 在轴为1的方向上对 c2d 中每行应用 hermeint 函数,同时指定额外的参数 k=3
        tgt = np.vstack([herme.hermeint(c, k=3) for c in c2d])
        res = herme.hermeint(c2d, k=3, axis=1)  # 调用 hermeint 函数,指定 axis=1 和 k=3
        assert_almost_equal(res, tgt)  # 断言结果 res 与目标 tgt 几乎相等
class TestDerivative:

    def test_hermeder(self):
        # 检查异常情况:验证在给定参数下是否会抛出 TypeError 异常
        assert_raises(TypeError, herme.hermeder, [0], .5)
        # 检查异常情况:验证在给定参数下是否会抛出 ValueError 异常
        assert_raises(ValueError, herme.hermeder, [0], -1)

        # 检查零阶导数是否不做任何操作
        for i in range(5):
            tgt = [0]*i + [1]
            res = herme.hermeder(tgt, m=0)
            assert_equal(trim(res), trim(tgt))

        # 检查导数是否是积分的逆过程
        for i in range(5):
            for j in range(2, 5):
                tgt = [0]*i + [1]
                res = herme.hermeder(herme.hermeint(tgt, m=j), m=j)
                assert_almost_equal(trim(res), trim(tgt))

        # 检查带有缩放的导数计算
        for i in range(5):
            for j in range(2, 5):
                tgt = [0]*i + [1]
                res = herme.hermeder(
                    herme.hermeint(tgt, m=j, scl=2), m=j, scl=.5)
                assert_almost_equal(trim(res), trim(tgt))

    def test_hermeder_axis(self):
        # 检查 axis 关键字的工作情况
        c2d = np.random.random((3, 4))

        # 沿轴 0 进行导数计算的结果
        tgt = np.vstack([herme.hermeder(c) for c in c2d.T]).T
        res = herme.hermeder(c2d, axis=0)
        assert_almost_equal(res, tgt)

        # 沿轴 1 进行导数计算的结果
        tgt = np.vstack([herme.hermeder(c) for c in c2d])
        res = herme.hermeder(c2d, axis=1)
        assert_almost_equal(res, tgt)


class TestVander:
    # 在 [-1, 1) 范围内生成随机值
    x = np.random.random((3, 5))*2 - 1

    def test_hermevander(self):
        # 检查 1 维 x 的情况
        x = np.arange(3)
        v = herme.hermevander(x, 3)
        assert_(v.shape == (3, 4))
        for i in range(4):
            coef = [0]*i + [1]
            assert_almost_equal(v[..., i], herme.hermeval(x, coef))

        # 检查 2 维 x 的情况
        x = np.array([[1, 2], [3, 4], [5, 6]])
        v = herme.hermevander(x, 3)
        assert_(v.shape == (3, 2, 4))
        for i in range(4):
            coef = [0]*i + [1]
            assert_almost_equal(v[..., i], herme.hermeval(x, coef))

    def test_hermevander2d(self):
        # 同时测试非方形系数数组的 hermeval2d 函数
        x1, x2, x3 = self.x
        c = np.random.random((2, 3))
        van = herme.hermevander2d(x1, x2, [1, 2])
        tgt = herme.hermeval2d(x1, x2, c)
        res = np.dot(van, c.flat)
        assert_almost_equal(res, tgt)

        # 检查形状
        van = herme.hermevander2d([x1], [x2], [1, 2])
        assert_(van.shape == (1, 5, 6))

    def test_hermevander3d(self):
        # 同时测试非方形系数数组的 hermeval3d 函数
        x1, x2, x3 = self.x
        c = np.random.random((2, 3, 4))
        van = herme.hermevander3d(x1, x2, x3, [1, 2, 3])
        tgt = herme.hermeval3d(x1, x2, x3, c)
        res = np.dot(van, c.flat)
        assert_almost_equal(res, tgt)

        # 检查形状
        van = herme.hermevander3d([x1], [x2], [x3], [1, 2, 3])
        assert_(van.shape == (1, 5, 24))


class TestFitting:

class TestCompanion:
    # 定义测试函数,用于测试 herme.hermecompanion 函数是否能正确引发 ValueError 异常,当输入为空列表或包含一个元素时
    def test_raises(self):
        # 断言调用 herme.hermecompanion 函数时会引发 ValueError 异常,传入空列表作为参数
        assert_raises(ValueError, herme.hermecompanion, [])
        # 断言调用 herme.hermecompanion 函数时会引发 ValueError 异常,传入包含一个元素的列表作为参数
        assert_raises(ValueError, herme.hermecompanion, [1])

    # 定义测试函数,用于测试 herme.hermecompanion 函数生成的伴随矩阵的维度是否符合预期
    def test_dimensions(self):
        # 循环测试不同长度的系数列表
        for i in range(1, 5):
            # 构造系数列表,前 i-1 个元素为 0,最后一个元素为 1
            coef = [0]*i + [1]
            # 断言生成的伴随矩阵的形状是否为 (i, i)
            assert_(herme.hermecompanion(coef).shape == (i, i))

    # 定义测试函数,用于测试 herme.hermecompanion 函数生成的伴随矩阵中特定元素的值是否符合预期
    def test_linear_root(self):
        # 断言生成的伴随矩阵的第一个元素是否为 -0.5,当传入系数列表为 [1, 2] 时
        assert_(herme.hermecompanion([1, 2])[0, 0] == -.5)
class TestGauss:

    def test_100(self):
        # 调用 herme 模块的 hermegauss 函数,获取 Hermite-Gauss 积分的节点和权重
        x, w = herme.hermegauss(100)

        # 测试正交性。注意需要对结果进行归一化,否则由于 Laguerre 等快速增长函数可能产生的巨大值会很令人困惑。
        v = herme.hermevander(x, 99)
        vv = np.dot(v.T * w, v)
        vd = 1/np.sqrt(vv.diagonal())
        vv = vd[:, None] * vv * vd

        # 断言计算出的 vv 与单位矩阵近似相等
        assert_almost_equal(vv, np.eye(100))

        # 检查积分 1 的结果是否正确
        tgt = np.sqrt(2*np.pi)
        assert_almost_equal(w.sum(), tgt)


class TestMisc:

    def test_hermefromroots(self):
        # 调用 herme 模块的 hermefromroots 函数,验证结果近似等于 [1]
        res = herme.hermefromroots([])
        assert_almost_equal(trim(res), [1])

        # 对于范围从 1 到 4 的每个 i
        for i in range(1, 5):
            # 生成 Hermite 多项式的根
            roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2])
            # 使用 hermefromroots 生成多项式
            pol = herme.hermefromroots(roots)
            # 计算多项式在给定根处的值
            res = herme.hermeval(roots, pol)
            tgt = 0

            # 断言多项式的长度为 i+1
            assert_(len(pol) == i + 1)
            # 断言 Hermite 多项式转换为多项式的最后一个系数近似为 1
            assert_almost_equal(herme.herme2poly(pol)[-1], 1)
            # 断言计算的值近似为目标值
            assert_almost_equal(res, tgt)

    def test_hermeroots(self):
        # 测试 hermeroots 函数对 [1] 的近似值
        assert_almost_equal(herme.hermeroots([1]), [])
        # 测试 hermeroots 函数对 [1, 1] 的近似值
        assert_almost_equal(herme.hermeroots([1, 1]), [-1])

        # 对于范围从 2 到 4 的每个 i
        for i in range(2, 5):
            # 生成 -1 到 1 之间的均匀分布的长度为 i 的目标值
            tgt = np.linspace(-1, 1, i)
            # 生成 Hermite 多项式的根
            res = herme.hermeroots(herme.hermefromroots(tgt))
            # 断言修剪后的结果近似等于目标值的修剪版本
            assert_almost_equal(trim(res), trim(tgt))

    def test_hermetrim(self):
        coef = [2, -1, 1, 0]

        # 测试异常情况
        assert_raises(ValueError, herme.hermetrim, coef, -1)

        # 测试结果
        assert_equal(herme.hermetrim(coef), coef[:-1])
        assert_equal(herme.hermetrim(coef, 1), coef[:-3])
        assert_equal(herme.hermetrim(coef, 2), [0])

    def test_hermeline(self):
        # 断言 hermeline 函数的返回值与输入参数相等
        assert_equal(herme.hermeline(3, 4), [3, 4])

    def test_herme2poly(self):
        # 对于范围从 0 到 9 的每个 i
        for i in range(10):
            # 断言 herme2poly 函数近似等于 Helist[i]
            assert_almost_equal(herme.herme2poly([0]*i + [1]), Helist[i])

    def test_poly2herme(self):
        # 对于范围从 0 到 9 的每个 i
        for i in range(10):
            # 断言 poly2herme 函数近似等于 [0]*i + [1]
            assert_almost_equal(herme.poly2herme(Helist[i]), [0]*i + [1])

    def test_weight(self):
        # 生成 -5 到 5 之间的均匀分布的长度为 11 的目标值
        x = np.linspace(-5, 5, 11)
        # 计算 Hermite 权重函数的值
        tgt = np.exp(-.5*x**2)
        res = herme.hermeweight(x)
        # 断言计算结果近似等于目标值
        assert_almost_equal(res, tgt)

.\numpy\numpy\polynomial\tests\test_laguerre.py

"""Tests for laguerre module.

"""
# 导入 reduce 函数
from functools import reduce

# 导入 numpy 库,并使用别名 np
import numpy as np
# 导入 numpy.polynomial.laguerre 模块,并使用别名 lag
import numpy.polynomial.laguerre as lag
# 导入 numpy.polynomial.polynomial 模块中的 polyval 函数
from numpy.polynomial.polynomial import polyval
# 导入 numpy.testing 中的多个断言函数
from numpy.testing import (
    assert_almost_equal, assert_raises, assert_equal, assert_,
    )

# 定义 Laguerre 多项式 L0 到 L6
L0 = np.array([1])/1
L1 = np.array([1, -1])/1
L2 = np.array([2, -4, 1])/2
L3 = np.array([6, -18, 9, -1])/6
L4 = np.array([24, -96, 72, -16, 1])/24
L5 = np.array([120, -600, 600, -200, 25, -1])/120
L6 = np.array([720, -4320, 5400, -2400, 450, -36, 1])/720

# 将 Laguerre 多项式存储在列表 Llist 中
Llist = [L0, L1, L2, L3, L4, L5, L6]

# 定义 trim 函数,使用 lag.lagtrim 函数对输入进行修剪
def trim(x):
    return lag.lagtrim(x, tol=1e-6)

# 定义 TestConstants 类
class TestConstants:

    # 测试 lagdomain 是否等于 [0, 1]
    def test_lagdomain(self):
        assert_equal(lag.lagdomain, [0, 1])

    # 测试 lagzero 是否等于 [0]
    def test_lagzero(self):
        assert_equal(lag.lagzero, [0])

    # 测试 lagone 是否等于 [1]
    def test_lagone(self):
        assert_equal(lag.lagone, [1])

    # 测试 lagx 是否等于 [1, -1]
    def test_lagx(self):
        assert_equal(lag.lagx, [1, -1])

# 定义 TestArithmetic 类
class TestArithmetic:

    # 定义 x 数组,包含从 -3 到 3 的 100 个均匀分布的数值
    x = np.linspace(-3, 3, 100)

    # 测试 lagadd 函数的行为
    def test_lagadd(self):
        for i in range(5):
            for j in range(5):
                msg = f"At i={i}, j={j}"
                tgt = np.zeros(max(i, j) + 1)
                tgt[i] += 1
                tgt[j] += 1
                res = lag.lagadd([0]*i + [1], [0]*j + [1])
                assert_equal(trim(res), trim(tgt), err_msg=msg)

    # 测试 lagsub 函数的行为
    def test_lagsub(self):
        for i in range(5):
            for j in range(5):
                msg = f"At i={i}, j={j}"
                tgt = np.zeros(max(i, j) + 1)
                tgt[i] += 1
                tgt[j] -= 1
                res = lag.lagsub([0]*i + [1], [0]*j + [1])
                assert_equal(trim(res), trim(tgt), err_msg=msg)

    # 测试 lagmulx 函数的行为
    def test_lagmulx(self):
        assert_equal(lag.lagmulx([0]), [0])
        assert_equal(lag.lagmulx([1]), [1, -1])
        for i in range(1, 5):
            ser = [0]*i + [1]
            tgt = [0]*(i - 1) + [-i, 2*i + 1, -(i + 1)]
            assert_almost_equal(lag.lagmulx(ser), tgt)

    # 测试 lagmul 函数的行为
    def test_lagmul(self):
        # 检查结果的数值
        for i in range(5):
            pol1 = [0]*i + [1]
            val1 = lag.lagval(self.x, pol1)
            for j in range(5):
                msg = f"At i={i}, j={j}"
                pol2 = [0]*j + [1]
                val2 = lag.lagval(self.x, pol2)
                pol3 = lag.lagmul(pol1, pol2)
                val3 = lag.lagval(self.x, pol3)
                assert_(len(pol3) == i + j + 1, msg)
                assert_almost_equal(val3, val1*val2, err_msg=msg)

    # 测试 lagdiv 函数的行为
    def test_lagdiv(self):
        for i in range(5):
            for j in range(5):
                msg = f"At i={i}, j={j}"
                ci = [0]*i + [1]
                cj = [0]*j + [1]
                tgt = lag.lagadd(ci, cj)
                quo, rem = lag.lagdiv(tgt, ci)
                res = lag.lagadd(lag.lagmul(quo, ci), rem)
                assert_almost_equal(trim(res), trim(tgt), err_msg=msg)
    # 定义一个测试方法 test_lagpow,用于测试 lagpow 函数的功能
    def test_lagpow(self):
        # 外层循环控制 i 的取值范围在 [0, 5)
        for i in range(5):
            # 内层循环控制 j 的取值范围在 [0, 5)
            for j in range(5):
                # 生成当前测试消息的字符串,显示当前 i 和 j 的值
                msg = f"At i={i}, j={j}"
                # 创建一个长度为 i+1 的 NumPy 数组 c,包含从 0 到 i 的整数
                c = np.arange(i + 1)
                # 使用 lagmul 函数对 c 数组进行 j 次拉格朗日多项式乘法,初始化为 [1]
                tgt = reduce(lag.lagmul, [c]*j, np.array([1]))
                # 调用 lagpow 函数计算 c 的 j 次幂的拉格朗日多项式
                res = lag.lagpow(c, j) 
                # 使用 assert_equal 函数断言 res 和 tgt 的结果在修剪(trim)后相等,如果不相等,显示错误消息 msg
                assert_equal(trim(res), trim(tgt), err_msg=msg)
class TestEvaluation:
    # 定义一维多项式系数:1 + 2*x + 3*x**2
    c1d = np.array([9., -14., 6.])
    # 使用 Einstein 求和约定创建二维系数数组
    c2d = np.einsum('i,j->ij', c1d, c1d)
    # 使用 Einstein 求和约定创建三维系数数组
    c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)

    # 生成在区间[-1, 1)内的随机值
    x = np.random.random((3, 5))*2 - 1
    # 计算多项式在随机值 x 上的取值
    y = polyval(x, [1., 2., 3.])

    def test_lagval(self):
        # 检查空输入的情况
        assert_equal(lag.lagval([], [1]).size, 0)

        # 检查正常输入的情况
        x = np.linspace(-1, 1)
        y = [polyval(x, c) for c in Llist]
        for i in range(7):
            msg = f"At i={i}"
            tgt = y[i]
            res = lag.lagval(x, [0]*i + [1])
            assert_almost_equal(res, tgt, err_msg=msg)

        # 检查结果形状是否保持不变
        for i in range(3):
            dims = [2]*i
            x = np.zeros(dims)
            assert_equal(lag.lagval(x, [1]).shape, dims)
            assert_equal(lag.lagval(x, [1, 0]).shape, dims)
            assert_equal(lag.lagval(x, [1, 0, 0]).shape, dims)

    def test_lagval2d(self):
        x1, x2, x3 = self.x
        y1, y2, y3 = self.y

        # 测试异常情况
        assert_raises(ValueError, lag.lagval2d, x1, x2[:2], self.c2d)

        # 测试值计算
        tgt = y1*y2
        res = lag.lagval2d(x1, x2, self.c2d)
        assert_almost_equal(res, tgt)

        # 测试结果形状
        z = np.ones((2, 3))
        res = lag.lagval2d(z, z, self.c2d)
        assert_(res.shape == (2, 3))

    def test_lagval3d(self):
        x1, x2, x3 = self.x
        y1, y2, y3 = self.y

        # 测试异常情况
        assert_raises(ValueError, lag.lagval3d, x1, x2, x3[:2], self.c3d)

        # 测试值计算
        tgt = y1*y2*y3
        res = lag.lagval3d(x1, x2, x3, self.c3d)
        assert_almost_equal(res, tgt)

        # 测试结果形状
        z = np.ones((2, 3))
        res = lag.lagval3d(z, z, z, self.c3d)
        assert_(res.shape == (2, 3))

    def test_laggrid2d(self):
        x1, x2, x3 = self.x
        y1, y2, y3 = self.y

        # 测试值计算
        tgt = np.einsum('i,j->ij', y1, y2)
        res = lag.laggrid2d(x1, x2, self.c2d)
        assert_almost_equal(res, tgt)

        # 测试结果形状
        z = np.ones((2, 3))
        res = lag.laggrid2d(z, z, self.c2d)
        assert_(res.shape == (2, 3)*2)

    def test_laggrid3d(self):
        x1, x2, x3 = self.x
        y1, y2, y3 = self.y

        # 测试值计算
        tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
        res = lag.laggrid3d(x1, x2, x3, self.c3d)
        assert_almost_equal(res, tgt)

        # 测试结果形状
        z = np.ones((2, 3))
        res = lag.laggrid3d(z, z, z, self.c3d)
        assert_(res.shape == (2, 3)*3)


class TestIntegral:
    # 定义一个测试函数 `test_lagint_axis`,用于测试 lagint 函数在不同轴向上的表现
    def test_lagint_axis(self):
        # 检查 axis 关键字参数的工作情况

        # 创建一个 3x4 的随机数数组
        c2d = np.random.random((3, 4))

        # 对数组的每一列应用 lag.lagint 函数,并将结果堆叠为一个新的转置后的数组
        tgt = np.vstack([lag.lagint(c) for c in c2d.T]).T
        # 在 axis=0 的情况下调用 lag.lagint 函数
        res = lag.lagint(c2d, axis=0)
        # 断言 res 和 tgt 几乎相等
        assert_almost_equal(res, tgt)

        # 对数组的每一行应用 lag.lagint 函数,并将结果堆叠为一个新的数组
        tgt = np.vstack([lag.lagint(c) for c in c2d])
        # 在 axis=1 的情况下调用 lag.lagint 函数
        res = lag.lagint(c2d, axis=1)
        # 断言 res 和 tgt 几乎相等
        assert_almost_equal(res, tgt)

        # 对数组的每一行应用 lag.lagint 函数,并指定 k=3
        tgt = np.vstack([lag.lagint(c, k=3) for c in c2d])
        # 在 axis=1 的情况下调用 lag.lagint 函数,同时指定 k=3
        res = lag.lagint(c2d, k=3, axis=1)
        # 断言 res 和 tgt 几乎相等
        assert_almost_equal(res, tgt)
class TestDerivative:

    def test_lagder(self):
        # 检查异常情况
        assert_raises(TypeError, lag.lagder, [0], .5)
        assert_raises(ValueError, lag.lagder, [0], -1)

        # 检查零阶导数不做任何操作
        for i in range(5):
            tgt = [0]*i + [1]
            res = lag.lagder(tgt, m=0)
            assert_equal(trim(res), trim(tgt))

        # 检查导数与积分的逆过程
        for i in range(5):
            for j in range(2, 5):
                tgt = [0]*i + [1]
                res = lag.lagder(lag.lagint(tgt, m=j), m=j)
                assert_almost_equal(trim(res), trim(tgt))

        # 检查带有缩放的导数计算
        for i in range(5):
            for j in range(2, 5):
                tgt = [0]*i + [1]
                res = lag.lagder(lag.lagint(tgt, m=j, scl=2), m=j, scl=.5)
                assert_almost_equal(trim(res), trim(tgt))

    def test_lagder_axis(self):
        # 检查轴关键字的工作方式
        c2d = np.random.random((3, 4))

        tgt = np.vstack([lag.lagder(c) for c in c2d.T]).T
        res = lag.lagder(c2d, axis=0)
        assert_almost_equal(res, tgt)

        tgt = np.vstack([lag.lagder(c) for c in c2d])
        res = lag.lagder(c2d, axis=1)
        assert_almost_equal(res, tgt)


class TestVander:
    # 在区间[-1, 1)中生成随机值
    x = np.random.random((3, 5))*2 - 1

    def test_lagvander(self):
        # 检查 1 维 x 的情况
        x = np.arange(3)
        v = lag.lagvander(x, 3)
        assert_(v.shape == (3, 4))
        for i in range(4):
            coef = [0]*i + [1]
            assert_almost_equal(v[..., i], lag.lagval(x, coef))

        # 检查 2 维 x 的情况
        x = np.array([[1, 2], [3, 4], [5, 6]])
        v = lag.lagvander(x, 3)
        assert_(v.shape == (3, 2, 4))
        for i in range(4):
            coef = [0]*i + [1]
            assert_almost_equal(v[..., i], lag.lagval(x, coef))

    def test_lagvander2d(self):
        # 同时测试 lagval2d 对于非方形系数数组的情况
        x1, x2, x3 = self.x
        c = np.random.random((2, 3))
        van = lag.lagvander2d(x1, x2, [1, 2])
        tgt = lag.lagval2d(x1, x2, c)
        res = np.dot(van, c.flat)
        assert_almost_equal(res, tgt)

        # 检查形状
        van = lag.lagvander2d([x1], [x2], [1, 2])
        assert_(van.shape == (1, 5, 6))

    def test_lagvander3d(self):
        # 同时测试 lagval3d 对于非方形系数数组的情况
        x1, x2, x3 = self.x
        c = np.random.random((2, 3, 4))
        van = lag.lagvander3d(x1, x2, x3, [1, 2, 3])
        tgt = lag.lagval3d(x1, x2, x3, c)
        res = np.dot(van, c.flat)
        assert_almost_equal(res, tgt)

        # 检查形状
        van = lag.lagvander3d([x1], [x2], [x3], [1, 2, 3])
        assert_(van.shape == (1, 5, 24))


class TestFitting:
    pass
    def test_lagfit(self):
        # 定义一个测试函数 f(x),计算 x*(x - 1)*(x - 2)
        def f(x):
            return x*(x - 1)*(x - 2)

        # 测试异常情况
        assert_raises(ValueError, lag.lagfit, [1], [1], -1)
        assert_raises(TypeError, lag.lagfit, [[1]], [1], 0)
        assert_raises(TypeError, lag.lagfit, [], [1], 0)
        assert_raises(TypeError, lag.lagfit, [1], [[[1]]], 0)
        assert_raises(TypeError, lag.lagfit, [1, 2], [1], 0)
        assert_raises(TypeError, lag.lagfit, [1], [1, 2], 0)
        assert_raises(TypeError, lag.lagfit, [1], [1], 0, w=[[1]])
        assert_raises(TypeError, lag.lagfit, [1], [1], 0, w=[1, 1])
        assert_raises(ValueError, lag.lagfit, [1], [1], [-1,])
        assert_raises(ValueError, lag.lagfit, [1], [1], [2, -1, 6])
        assert_raises(TypeError, lag.lagfit, [1], [1], [])

        # 测试拟合
        x = np.linspace(0, 2)
        y = f(x)
        # 拟合阶数为 3 的 Lagrange 插值多项式
        coef3 = lag.lagfit(x, y, 3)
        assert_equal(len(coef3), 4)
        assert_almost_equal(lag.lagval(x, coef3), y)
        # 拟合指定节点的 Lagrange 插值多项式
        coef3 = lag.lagfit(x, y, [0, 1, 2, 3])
        assert_equal(len(coef3), 4)
        assert_almost_equal(lag.lagval(x, coef3), y)
        # 拟合阶数为 4 的 Lagrange 插值多项式
        coef4 = lag.lagfit(x, y, 4)
        assert_equal(len(coef4), 5)
        assert_almost_equal(lag.lagval(x, coef4), y)
        # 拟合指定节点的 Lagrange 插值多项式
        coef4 = lag.lagfit(x, y, [0, 1, 2, 3, 4])
        assert_equal(len(coef4), 5)
        assert_almost_equal(lag.lagval(x, coef4), y)
        # 对二维数据进行拟合
        coef2d = lag.lagfit(x, np.array([y, y]).T, 3)
        assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
        coef2d = lag.lagfit(x, np.array([y, y]).T, [0, 1, 2, 3])
        assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
        # 测试加权拟合
        w = np.zeros_like(x)
        yw = y.copy()
        w[1::2] = 1
        y[0::2] = 0
        wcoef3 = lag.lagfit(x, yw, 3, w=w)
        assert_almost_equal(wcoef3, coef3)
        wcoef3 = lag.lagfit(x, yw, [0, 1, 2, 3], w=w)
        assert_almost_equal(wcoef3, coef3)
        # 对二维数据进行加权拟合
        wcoef2d = lag.lagfit(x, np.array([yw, yw]).T, 3, w=w)
        assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
        wcoef2d = lag.lagfit(x, np.array([yw, yw]).T, [0, 1, 2, 3], w=w)
        assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
        # 测试使用复数值进行拟合
        x = [1, 1j, -1, -1j]
        assert_almost_equal(lag.lagfit(x, x, 1), [1, -1])
        assert_almost_equal(lag.lagfit(x, x, [0, 1]), [1, -1])
class TestCompanion:

    def test_raises(self):
        # 检查 lagcompanion 函数在空列表输入时是否引发 ValueError 异常
        assert_raises(ValueError, lag.lagcompanion, [])
        # 检查 lagcompanion 函数在单元素列表输入时是否引发 ValueError 异常
        assert_raises(ValueError, lag.lagcompanion, [1])

    def test_dimensions(self):
        # 测试 lagcompanion 函数生成的伴随矩阵的维度是否正确
        for i in range(1, 5):
            coef = [0]*i + [1]
            assert_(lag.lagcompanion(coef).shape == (i, i))

    def test_linear_root(self):
        # 检查 lagcompanion 函数对 [1, 2] 输入生成的伴随矩阵的第一个元素是否为 1.5
        assert_(lag.lagcompanion([1, 2])[0, 0] == 1.5)


class TestGauss:

    def test_100(self):
        # 获取 Laguerre-Gauss 积分的节点和权重
        x, w = lag.laggauss(100)

        # 测试正交性。需要注意结果需要归一化,否则由于拉盖尔函数等快速增长函数可能导致的巨大值会非常令人困惑。
        v = lag.lagvander(x, 99)
        vv = np.dot(v.T * w, v)
        vd = 1/np.sqrt(vv.diagonal())
        vv = vd[:, None] * vv * vd
        assert_almost_equal(vv, np.eye(100))

        # 检查积分结果是否为 1
        tgt = 1.0
        assert_almost_equal(w.sum(), tgt)


class TestMisc:

    def test_lagfromroots(self):
        # 测试 lagfromroots 函数对空根列表的处理,期望结果为 [1]
        res = lag.lagfromroots([])
        assert_almost_equal(trim(res), [1])

        # 测试 lagfromroots 函数对包含多个根的情况的处理
        for i in range(1, 5):
            roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2])
            pol = lag.lagfromroots(roots)
            res = lag.lagval(roots, pol)
            tgt = 0
            assert_(len(pol) == i + 1)
            assert_almost_equal(lag.lag2poly(pol)[-1], 1)
            assert_almost_equal(res, tgt)

    def test_lagroots(self):
        # 检查 lagroots 函数对不同系数输入的根的计算结果
        assert_almost_equal(lag.lagroots([1]), [])
        assert_almost_equal(lag.lagroots([0, 1]), [1])
        for i in range(2, 5):
            tgt = np.linspace(0, 3, i)
            res = lag.lagroots(lag.lagfromroots(tgt))
            assert_almost_equal(trim(res), trim(tgt))

    def test_lagtrim(self):
        coef = [2, -1, 1, 0]

        # 测试异常情况:lagtrim 函数对负数输入是否引发 ValueError 异常
        assert_raises(ValueError, lag.lagtrim, coef, -1)

        # 测试结果:lagtrim 函数对不同参数的截断效果
        assert_equal(lag.lagtrim(coef), coef[:-1])
        assert_equal(lag.lagtrim(coef, 1), coef[:-3])
        assert_equal(lag.lagtrim(coef, 2), [0])

    def test_lagline(self):
        # 检查 lagline 函数对给定参数的线性多项式的计算结果
        assert_equal(lag.lagline(3, 4), [7, -4])

    def test_lag2poly(self):
        # 检查 lag2poly 函数对不同阶数的拉盖尔多项式的转换结果
        for i in range(7):
            assert_almost_equal(lag.lag2poly([0]*i + [1]), Llist[i])

    def test_poly2lag(self):
        # 检查 poly2lag 函数对不同阶数的多项式的转换结果
        for i in range(7):
            assert_almost_equal(lag.poly2lag(Llist[i]), [0]*i + [1])

    def test_weight(self):
        # 检查 lagweight 函数对给定输入的权重计算结果
        x = np.linspace(0, 10, 11)
        tgt = np.exp(-x)
        res = lag.lagweight(x)
        assert_almost_equal(res, tgt)

.\numpy\numpy\polynomial\tests\test_legendre.py

"""Tests for legendre module.

"""
# 导入所需模块和函数
from functools import reduce

import numpy as np  # 导入 NumPy 库并使用别名 np
import numpy.polynomial.legendre as leg  # 导入 Legendre 多项式相关函数并使用别名 leg
from numpy.polynomial.polynomial import polyval  # 导入多项式求值函数 polyval
from numpy.testing import (
    assert_almost_equal, assert_raises, assert_equal, assert_  # 导入测试断言函数
    )

# 预定义 Legendre 多项式的前十个系数
L0 = np.array([1])
L1 = np.array([0, 1])
L2 = np.array([-1, 0, 3])/2
L3 = np.array([0, -3, 0, 5])/2
L4 = np.array([3, 0, -30, 0, 35])/8
L5 = np.array([0, 15, 0, -70, 0, 63])/8
L6 = np.array([-5, 0, 105, 0, -315, 0, 231])/16
L7 = np.array([0, -35, 0, 315, 0, -693, 0, 429])/16
L8 = np.array([35, 0, -1260, 0, 6930, 0, -12012, 0, 6435])/128
L9 = np.array([0, 315, 0, -4620, 0, 18018, 0, -25740, 0, 12155])/128

# 将 Legendre 多项式系数存入列表
Llist = [L0, L1, L2, L3, L4, L5, L6, L7, L8, L9]

# 定义修剪函数,用于裁剪 Legendre 多项式系数
def trim(x):
    return leg.legtrim(x, tol=1e-6)

# 定义测试类 TestConstants,用于测试 Legendre 多项式的常数定义
class TestConstants:

    def test_legdomain(self):
        assert_equal(leg.legdomain, [-1, 1])  # 检查 Legendre 多项式的定义域

    def test_legzero(self):
        assert_equal(leg.legzero, [0])  # 检查 Legendre 多项式的零多项式

    def test_legone(self):
        assert_equal(leg.legone, [1])  # 检查 Legendre 多项式的单位多项式

    def test_legx(self):
        assert_equal(leg.legx, [0, 1])  # 检查 Legendre 多项式的 x 多项式

# 定义测试类 TestArithmetic,用于测试 Legendre 多项式的算术操作
class TestArithmetic:
    x = np.linspace(-1, 1, 100)  # 在[-1, 1]区间上生成100个均匀分布的点作为测试使用

    def test_legadd(self):
        # 测试 Legendre 多项式加法
        for i in range(5):
            for j in range(5):
                msg = f"At i={i}, j={j}"
                tgt = np.zeros(max(i, j) + 1)
                tgt[i] += 1
                tgt[j] += 1
                res = leg.legadd([0]*i + [1], [0]*j + [1])  # 执行 Legendre 多项式加法
                assert_equal(trim(res), trim(tgt), err_msg=msg)  # 断言结果与目标相等

    def test_legsub(self):
        # 测试 Legendre 多项式减法
        for i in range(5):
            for j in range(5):
                msg = f"At i={i}, j={j}"
                tgt = np.zeros(max(i, j) + 1)
                tgt[i] += 1
                tgt[j] -= 1
                res = leg.legsub([0]*i + [1], [0]*j + [1])  # 执行 Legendre 多项式减法
                assert_equal(trim(res), trim(tgt), err_msg=msg)  # 断言结果与目标相等

    def test_legmulx(self):
        # 测试 Legendre 多项式乘以 x
        assert_equal(leg.legmulx([0]), [0])  # 验证零多项式乘以 x 后为零多项式
        assert_equal(leg.legmulx([1]), [0, 1])  # 验证单位多项式乘以 x 后为 x 多项式
        for i in range(1, 5):
            tmp = 2*i + 1
            ser = [0]*i + [1]
            tgt = [0]*(i - 1) + [i/tmp, 0, (i + 1)/tmp]
            assert_equal(leg.legmulx(ser), tgt)  # 验证乘以 x 的系数计算

    def test_legmul(self):
        # 测试 Legendre 多项式乘法
        for i in range(5):
            pol1 = [0]*i + [1]
            val1 = leg.legval(self.x, pol1)
            for j in range(5):
                msg = f"At i={i}, j={j}"
                pol2 = [0]*j + [1]
                val2 = leg.legval(self.x, pol2)
                pol3 = leg.legmul(pol1, pol2)
                val3 = leg.legval(self.x, pol3)
                assert_(len(pol3) == i + j + 1, msg)  # 验证乘法结果的系数个数
                assert_almost_equal(val3, val1*val2, err_msg=msg)  # 验证乘法结果在测试点上的值与期望值接近
    # 定义一个测试方法,用于测试多项式的除法功能
    def test_legdiv(self):
        # 循环遍历 i 的取值范围 [0, 5)
        for i in range(5):
            # 循环遍历 j 的取值范围 [0, 5)
            for j in range(5):
                # 构造测试信息字符串,显示当前 i 和 j 的取值
                msg = f"At i={i}, j={j}"
                # 创建一个长度为 i+1 的列表,最后一个元素为 1,其余为 0
                ci = [0]*i + [1]
                # 创建一个长度为 j+1 的列表,最后一个元素为 1,其余为 0
                cj = [0]*j + [1]
                # 调用 leg.legadd 函数,计算多项式 ci 和 cj 的加法结果 tgt
                tgt = leg.legadd(ci, cj)
                # 调用 leg.legdiv 函数,计算 tgt 除以 ci 的商 quo 和余数 rem
                quo, rem = leg.legdiv(tgt, ci)
                # 使用 quo 和 rem 计算得到的结果 res
                res = leg.legadd(leg.legmul(quo, ci), rem)
                # 断言 trim(res) 等于 trim(tgt),如果不等则输出错误信息 msg
                assert_equal(trim(res), trim(tgt), err_msg=msg)
    
    # 定义一个测试方法,用于测试多项式的幂运算功能
    def test_legpow(self):
        # 循环遍历 i 的取值范围 [0, 5)
        for i in range(5):
            # 循环遍历 j 的取值范围 [0, 5)
            for j in range(5):
                # 构造测试信息字符串,显示当前 i 和 j 的取值
                msg = f"At i={i}, j={j}"
                # 创建一个长度为 i+1 的 numpy 数组,元素为 0, 1, ..., i
                c = np.arange(i + 1)
                # 使用 reduce 函数,计算多项式 c 的 j 次幂的目标值 tgt
                tgt = reduce(leg.legmul, [c]*j, np.array([1]))
                # 调用 leg.legpow 函数,计算 c 的 j 次幂的结果 res
                res = leg.legpow(c, j) 
                # 断言 trim(res) 等于 trim(tgt),如果不等则输出错误信息 msg
                assert_equal(trim(res), trim(tgt), err_msg=msg)
class TestEvaluation:
    # 定义一维多项式系数为 [2., 2., 2.]
    c1d = np.array([2., 2., 2.])
    # 创建二维数组,每个元素为两个一维数组的乘积
    c2d = np.einsum('i,j->ij', c1d, c1d)
    # 创建三维数组,每个元素为三个一维数组的乘积
    c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)

    # 生成随机数矩阵 x,元素在 [-1, 1) 范围内
    x = np.random.random((3, 5))*2 - 1
    # 计算多项式在 x 上的值 y
    y = polyval(x, [1., 2., 3.])

    def test_legval(self):
        # 检查空输入情况,期望结果的大小为 0
        assert_equal(leg.legval([], [1]).size, 0)

        # 检查正常输入情况
        x = np.linspace(-1, 1)
        y = [polyval(x, c) for c in Llist]
        for i in range(10):
            msg = f"At i={i}"
            tgt = y[i]
            res = leg.legval(x, [0]*i + [1])
            # 断言多项式值 res 与目标值 tgt 接近
            assert_almost_equal(res, tgt, err_msg=msg)

        # 检查形状保持不变
        for i in range(3):
            dims = [2]*i
            x = np.zeros(dims)
            # 断言多项式值的形状与预期维度 dims 相同
            assert_equal(leg.legval(x, [1]).shape, dims)
            assert_equal(leg.legval(x, [1, 0]).shape, dims)
            assert_equal(leg.legval(x, [1, 0, 0]).shape, dims)

    def test_legval2d(self):
        x1, x2, x3 = self.x
        y1, y2, y3 = self.y

        # 测试异常情况,期望引发 ValueError
        assert_raises(ValueError, leg.legval2d, x1, x2[:2], self.c2d)

        # 测试值
        tgt = y1 * y2
        res = leg.legval2d(x1, x2, self.c2d)
        # 断言多项式值 res 与目标值 tgt 接近
        assert_almost_equal(res, tgt)

        # 测试形状
        z = np.ones((2, 3))
        res = leg.legval2d(z, z, self.c2d)
        # 断言 res 的形状为 (2, 3)
        assert_(res.shape == (2, 3))

    def test_legval3d(self):
        x1, x2, x3 = self.x
        y1, y2, y3 = self.y

        # 测试异常情况,期望引发 ValueError
        assert_raises(ValueError, leg.legval3d, x1, x2, x3[:2], self.c3d)

        # 测试值
        tgt = y1 * y2 * y3
        res = leg.legval3d(x1, x2, x3, self.c3d)
        # 断言多项式值 res 与目标值 tgt 接近
        assert_almost_equal(res, tgt)

        # 测试形状
        z = np.ones((2, 3))
        res = leg.legval3d(z, z, z, self.c3d)
        # 断言 res 的形状为 (2, 3)
        assert_(res.shape == (2, 3))

    def test_leggrid2d(self):
        x1, x2, x3 = self.x
        y1, y2, y3 = self.y

        # 测试值
        tgt = np.einsum('i,j->ij', y1, y2)
        res = leg.leggrid2d(x1, x2, self.c2d)
        # 断言多项式值 res 与目标值 tgt 接近
        assert_almost_equal(res, tgt)

        # 测试形状
        z = np.ones((2, 3))
        res = leg.leggrid2d(z, z, self.c2d)
        # 断言 res 的形状为 (2, 3)*2
        assert_(res.shape == (2, 3)*2)

    def test_leggrid3d(self):
        x1, x2, x3 = self.x
        y1, y2, y3 = self.y

        # 测试值
        tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
        res = leg.leggrid3d(x1, x2, x3, self.c3d)
        # 断言多项式值 res 与目标值 tgt 接近
        assert_almost_equal(res, tgt)

        # 测试形状
        z = np.ones((2, 3))
        res = leg.leggrid3d(z, z, z, self.c3d)
        # 断言 res 的形状为 (2, 3)*3
        assert_(res.shape == (2, 3)*3)


class TestIntegral:
    # 这里开始下一个测试类,未完待续...
    # 定义测试方法,用于验证 legint 函数中的 axis 关键字是否正常工作
    def test_legint_axis(self):
        # 创建一个 3x4 的随机数组
        c2d = np.random.random((3, 4))

        # 对 c2d 的转置进行 Legendre 多项式积分,然后再次转置,形成目标数组
        tgt = np.vstack([leg.legint(c) for c in c2d.T]).T
        # 在 axis=0 方向上调用 legint 函数,得到结果 res
        res = leg.legint(c2d, axis=0)
        # 断言 res 与 tgt 的值近似相等
        assert_almost_equal(res, tgt)

        # 对 c2d 按行进行 Legendre 多项式积分,形成目标数组
        tgt = np.vstack([leg.legint(c) for c in c2d])
        # 在 axis=1 方向上调用 legint 函数,得到结果 res
        res = leg.legint(c2d, axis=1)
        # 断言 res 与 tgt 的值近似相等
        assert_almost_equal(res, tgt)

        # 对 c2d 按行进行 Legendre 多项式积分,设置 k=3,形成目标数组
        tgt = np.vstack([leg.legint(c, k=3) for c in c2d])
        # 在 axis=1 方向上调用 legint 函数,设置 k=3,得到结果 res
        res = leg.legint(c2d, k=3, axis=1)
        # 断言 res 与 tgt 的值近似相等
        assert_almost_equal(res, tgt)

    # 定义测试方法,用于验证 legint 函数在指定零阶导数情况下的输出是否正确
    def test_legint_zerointord(self):
        # 断言对于输入 (1, 2, 3) 和零阶导数,legint 函数的输出为 (1, 2, 3)
        assert_equal(leg.legint((1, 2, 3), 0), (1, 2, 3))
class TestDerivative:

    def test_legder(self):
        # 检查异常情况
        assert_raises(TypeError, leg.legder, [0], .5)
        assert_raises(ValueError, leg.legder, [0], -1)

        # 检查零阶导数不产生变化
        for i in range(5):
            tgt = [0]*i + [1]
            res = leg.legder(tgt, m=0)
            assert_equal(trim(res), trim(tgt))

        # 检查导数与积分的反函数关系
        for i in range(5):
            for j in range(2, 5):
                tgt = [0]*i + [1]
                res = leg.legder(leg.legint(tgt, m=j), m=j)
                assert_almost_equal(trim(res), trim(tgt))

        # 检查带有缩放的导数计算
        for i in range(5):
            for j in range(2, 5):
                tgt = [0]*i + [1]
                res = leg.legder(leg.legint(tgt, m=j, scl=2), m=j, scl=.5)
                assert_almost_equal(trim(res), trim(tgt))

    def test_legder_axis(self):
        # 检查 axis 关键字的功能
        c2d = np.random.random((3, 4))

        tgt = np.vstack([leg.legder(c) for c in c2d.T]).T
        res = leg.legder(c2d, axis=0)
        assert_almost_equal(res, tgt)

        tgt = np.vstack([leg.legder(c) for c in c2d])
        res = leg.legder(c2d, axis=1)
        assert_almost_equal(res, tgt)

    def test_legder_orderhigherthancoeff(self):
        c = (1, 2, 3, 4)
        assert_equal(leg.legder(c, 4), [0])

class TestVander:
    # 在 [-1, 1) 内生成一些随机值
    x = np.random.random((3, 5))*2 - 1

    def test_legvander(self):
        # 检查 1 维 x 的情况
        x = np.arange(3)
        v = leg.legvander(x, 3)
        assert_(v.shape == (3, 4))
        for i in range(4):
            coef = [0]*i + [1]
            assert_almost_equal(v[..., i], leg.legval(x, coef))

        # 检查 2 维 x 的情况
        x = np.array([[1, 2], [3, 4], [5, 6]])
        v = leg.legvander(x, 3)
        assert_(v.shape == (3, 2, 4))
        for i in range(4):
            coef = [0]*i + [1]
            assert_almost_equal(v[..., i], leg.legval(x, coef))

    def test_legvander2d(self):
        # 同时测试非方形系数数组的 polyval2d
        x1, x2, x3 = self.x
        c = np.random.random((2, 3))
        van = leg.legvander2d(x1, x2, [1, 2])
        tgt = leg.legval2d(x1, x2, c)
        res = np.dot(van, c.flat)
        assert_almost_equal(res, tgt)

        # 检查形状
        van = leg.legvander2d([x1], [x2], [1, 2])
        assert_(van.shape == (1, 5, 6))

    def test_legvander3d(self):
        # 同时测试非方形系数数组的 polyval3d
        x1, x2, x3 = self.x
        c = np.random.random((2, 3, 4))
        van = leg.legvander3d(x1, x2, x3, [1, 2, 3])
        tgt = leg.legval3d(x1, x2, x3, c)
        res = np.dot(van, c.flat)
        assert_almost_equal(res, tgt)

        # 检查形状
        van = leg.legvander3d([x1], [x2], [x3], [1, 2, 3])
        assert_(van.shape == (1, 5, 24))
    # 定义一个测试函数 `test_legvander_negdeg`,用于测试 `leg.legvander` 函数在负阶数时是否会引发 ValueError 异常
    def test_legvander_negdeg(self):
        # 使用 assert_raises 来断言调用 leg.legvander 函数时,传入参数 (1, 2, 3) 和 -1 会引发 ValueError 异常
        assert_raises(ValueError, leg.legvander, (1, 2, 3), -1)
class TestFitting:
    # 这是一个空的测试类,用于未来扩展和组织测试用例
    pass

class TestCompanion:

    def test_raises(self):
        # 断言 leg.legcompanion([]) 和 leg.legcompanion([1]) 会引发 ValueError 异常
        assert_raises(ValueError, leg.legcompanion, [])
        assert_raises(ValueError, leg.legcompanion, [1])

    def test_dimensions(self):
        # 对于 1 到 4 的范围内的系数 coef,验证 leg.legcompanion(coef) 的形状为 (i, i)
        for i in range(1, 5):
            coef = [0]*i + [1]
            assert_(leg.legcompanion(coef).shape == (i, i))

    def test_linear_root(self):
        # 验证 leg.legcompanion([1, 2]) 的第一个元素 leg.legcompanion([1, 2])[0, 0] 等于 -.5
        assert_(leg.legcompanion([1, 2])[0, 0] == -.5)


class TestGauss:

    def test_100(self):
        # 获得 100 阶 Legendre 多项式的 Gauss 积分点和权重
        x, w = leg.leggauss(100)

        # 测试正交性。注意结果需要归一化,否则由于像 Laguerre 这样的快速增长函数可能产生的大值会非常混乱。
        v = leg.legvander(x, 99)
        vv = np.dot(v.T * w, v)
        vd = 1/np.sqrt(vv.diagonal())
        vv = vd[:, None] * vv * vd
        # 断言 vv 矩阵近似为单位矩阵
        assert_almost_equal(vv, np.eye(100))

        # 检查积分 1 的结果是否正确
        tgt = 2.0
        assert_almost_equal(w.sum(), tgt)


class TestMisc:

    def test_legfromroots(self):
        # 测试 leg.legfromroots([]) 的结果近似为 [1]
        res = leg.legfromroots([])
        assert_almost_equal(trim(res), [1])
        for i in range(1, 5):
            # 对于不同阶数的多项式,生成一组根,然后使用 leg.legfromroots() 生成对应的 Legendre 多项式,
            # 然后验证计算出的多项式在这些根处的值接近于 0
            roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2])
            pol = leg.legfromroots(roots)
            res = leg.legval(roots, pol)
            tgt = 0
            assert_(len(pol) == i + 1)
            assert_almost_equal(leg.leg2poly(pol)[-1], 1)
            assert_almost_equal(res, tgt)

    def test_legroots(self):
        # 验证 leg.legroots([1]) 的结果近似为 []
        assert_almost_equal(leg.legroots([1]), [])
        # 验证 leg.legroots([1, 2]) 的结果近似为 [-.5]
        assert_almost_equal(leg.legroots([1, 2]), [-.5])
        for i in range(2, 5):
            # 对于不同阶数的 Legendre 多项式,生成一组根,然后验证 leg.legroots() 的结果与生成的根接近
            tgt = np.linspace(-1, 1, i)
            res = leg.legroots(leg.legfromroots(tgt))
            assert_almost_equal(trim(res), trim(tgt))

    def test_legtrim(self):
        coef = [2, -1, 1, 0]

        # 测试异常情况,确保 leg.legtrim(coef, -1) 会引发 ValueError 异常
        assert_raises(ValueError, leg.legtrim, coef, -1)

        # 测试结果,验证 leg.legtrim(coef) 和 leg.legtrim(coef, 1) 的正确性
        assert_equal(leg.legtrim(coef), coef[:-1])
        assert_equal(leg.legtrim(coef, 1), coef[:-3])
        assert_equal(leg.legtrim(coef, 2), [0])

    def test_legline(self):
        # 验证 leg.legline(3, 4) 返回 [3, 4]
        assert_equal(leg.legline(3, 4))

    def test_legline_zeroscl(self):
        # 验证 leg.legline(3, 0) 返回 [3]
        assert_equal(leg.legline(3, 0))

    def test_leg2poly(self):
        for i in range(10):
            # 对于 0 到 9 阶的 Legendre 多项式,验证 leg.leg2poly([0]*i + [1]) 的近似正确性
            assert_almost_equal(leg.leg2poly([0]*i + [1]), Llist[i])

    def test_poly2leg(self):
        for i in range(10):
            # 对于 0 到 9 阶的 Legendre 多项式,验证 leg.poly2leg(Llist[i]) 的近似正确性
            assert_almost_equal(leg.poly2leg(Llist[i]), [0]*i + [1])

    def test_weight(self):
        x = np.linspace(-1, 1, 11)
        tgt = 1.
        # 验证 leg.legweight(x) 的结果近似为 1.0
        res = leg.legweight(x)
        assert_almost_equal(res, tgt)

.\numpy\numpy\polynomial\tests\test_polynomial.py

"""Tests for polynomial module.

"""
从 functools 模块导入 reduce 函数,用于多项式操作
从 fractions 模块导入 Fraction 类,处理有理数
导入 numpy 库并将其重命名为 np,用于数值计算
从 numpy.polynomial.polynomial 模块导入 poly 对象,用于多项式操作
导入 pickle 模块,用于序列化和反序列化对象
从 copy 模块导入 deepcopy 函数,用于深拷贝对象
从 numpy.testing 模块导入多个断言函数,用于单元测试断言

定义函数 trim,接受参数 x,调用 poly.polytrim 函数并传入 tol=1e-6 参数,用于修剪多项式的小系数

定义一系列多项式 T0 到 T9,每个多项式都是一个列表,表示多项式的系数

将多项式 T0 到 T9 组成一个列表 Tlist

定义类 TestConstants,用于测试多项式模块中的常数和常量

    定义方法 test_polydomain,断言 poly.polydomain 的值为 [-1, 1]

    定义方法 test_polyzero,断言 poly.polyzero 的值为 [0]

    定义方法 test_polyone,断言 poly.polyone 的值为 [1]

    定义方法 test_polyx,断言 poly.polyx 的值为 [0, 1]

    定义方法 test_copy,创建多项式对象 x,深拷贝 x 并赋值给 y,断言 x 和 y 的值相等

    定义方法 test_pickle,创建多项式对象 x,使用 pickle 序列化和反序列化 x,断言 x 和 y 的值相等

定义类 TestArithmetic,用于测试多项式模块中的算术运算

    定义方法 test_polyadd,使用嵌套的循环遍历范围在 04 的整数 i 和 j,并生成详细的错误消息。
    创建目标数组 tgt,对于每次迭代,调用 poly.polyadd 函数计算两个多项式的和,并使用 trim 函数修剪结果,断言结果等于目标数组 tgt。

    定义方法 test_polysub,使用嵌套的循环遍历范围在 04 的整数 i 和 j,并生成详细的错误消息。
    创建目标数组 tgt,对于每次迭代,调用 poly.polysub 函数计算两个多项式的差,并使用 trim 函数修剪结果,断言结果等于目标数组 tgt。

    定义方法 test_polymulx,断言 poly.polymulx([0]) 的结果为 [0],poly.polymulx([1]) 的结果为 [0, 1]。
    使用循环遍历范围在 14 的整数 i,创建系数数组 ser,创建目标数组 tgt,并断言 poly.polymulx 函数计算结果等于目标数组 tgt。

    定义方法 test_polymul,使用嵌套的循环遍历范围在 04 的整数 i 和 j,并生成详细的错误消息。
    创建目标数组 tgt,对于每次迭代,调用 poly.polymul 函数计算两个多项式的乘积,并使用 trim 函数修剪结果,断言结果等于目标数组 tgt。
    # 定义单元测试函数 test_polydiv
    def test_polydiv(self):
        # 检查零除错误情况
        assert_raises(ZeroDivisionError, poly.polydiv, [1], [0])

        # 检查标量除法
        quo, rem = poly.polydiv([2], [2])
        assert_equal((quo, rem), (1, 0))
        quo, rem = poly.polydiv([2, 2], [2])
        assert_equal((quo, rem), ((1, 1), 0))

        # 循环检查多种情况
        for i in range(5):
            for j in range(5):
                msg = f"At i={i}, j={j}"  # 错误消息标识
                ci = [0]*i + [1, 2]  # 构造多项式 ci
                cj = [0]*j + [1, 2]  # 构造多项式 cj
                tgt = poly.polyadd(ci, cj)  # 计算多项式 ci 和 cj 的和
                quo, rem = poly.polydiv(tgt, ci)  # 对和多项式进行除法,得到商和余数
                res = poly.polyadd(poly.polymul(quo, ci), rem)  # 将商和余数重新相加得到结果
                assert_equal(res, tgt, err_msg=msg)  # 断言结果等于目标值

    # 定义单元测试函数 test_polypow
    def test_polypow(self):
        # 循环检查多种情况
        for i in range(5):
            for j in range(5):
                msg = f"At i={i}, j={j}"  # 错误消息标识
                c = np.arange(i + 1)  # 创建系数数组 c
                tgt = reduce(poly.polymul, [c]*j, np.array([1]))  # 计算多项式的 j 次幂的目标值
                res = poly.polypow(c, j)   # 计算多项式的 j 次幂的结果
                assert_equal(trim(res), trim(tgt), err_msg=msg)  # 断言结果与目标值相等
class TestFraction:
    
    def test_Fraction(self):
        # 创建分数对象 f = 2/3
        f = Fraction(2, 3)
        # 创建分数对象 one = 1/1
        one = Fraction(1, 1)
        # 创建分数对象 zero = 0/1
        zero = Fraction(0, 1)
        # 使用多项式类创建对象 p,其中包含两个 f 作为系数,定义域为 [zero, one],窗口也为 [zero, one]
        p = poly.Polynomial([f, f], domain=[zero, one], window=[zero, one])
        
        # 计算表达式 x = 2 * p + p ** 2
        x = 2 * p + p ** 2
        # 断言 x 的系数为 [16/9, 20/9, 4/9],且数据类型为 object
        assert_equal(x.coef, np.array([Fraction(16, 9), Fraction(20, 9),
                                       Fraction(4, 9)], dtype=object))
        # 断言 p 的定义域为 [zero, one]
        assert_equal(p.domain, [zero, one])
        # 断言 p 的系数的数据类型为 np.dtypes.ObjectDType()
        assert_equal(p.coef.dtype, np.dtypes.ObjectDType())
        # 断言 p(f) 的返回值类型为 Fraction
        assert_(isinstance(p(f), Fraction))
        # 断言 p(f) 的值为 10/9
        assert_equal(p(f), Fraction(10, 9))
        
        # 创建一阶导数对象 p_deriv = 2/3,定义域为 [zero, one],窗口为 [zero, one]
        p_deriv = poly.Polynomial([Fraction(2, 3)], domain=[zero, one],
                                  window=[zero, one])
        # 断言 p 的一阶导数为 p_deriv
        assert_equal(p.deriv(), p_deriv)


class TestEvaluation:
    # 创建系数为 [1., 2., 3.] 的 1D 数组 c1d
    c1d = np.array([1., 2., 3.])
    # 创建 c1d 与自身的外积,形成 2D 数组 c2d
    c2d = np.einsum('i,j->ij', c1d, c1d)
    # 创建 c1d 与自身的外积与自身的外积,形成 3D 数组 c3d
    c3d = np.einsum('i,j,k->ijk', c1d, c1d, c1d)

    # 创建大小为 (3, 5) 的随机数数组 x,元素在 [-1, 1) 范围内
    x = np.random.random((3, 5))*2 - 1
    # 使用 poly.polyval 函数计算多项式在 x 上的值,系数为 [1., 2., 3.]
    y = poly.polyval(x, [1., 2., 3.])

    def test_polyval(self):
        # 检查空输入的情况,预期输出应该是 0
        assert_equal(poly.polyval([], [1]).size, 0)

        # 检查正常输入情况
        x = np.linspace(-1, 1)
        y = [x**i for i in range(5)]
        for i in range(5):
            tgt = y[i]
            res = poly.polyval(x, [0]*i + [1])
            # 断言 poly.polyval 的结果与预期值 tgt 几乎相等
            assert_almost_equal(res, tgt)
        tgt = x*(x**2 - 1)
        res = poly.polyval(x, [0, -1, 0, 1])
        # 断言 poly.polyval 的结果与预期值 tgt 几乎相等
        assert_almost_equal(res, tgt)

        # 检查保持形状不变
        for i in range(3):
            dims = [2]*i
            x = np.zeros(dims)
            # 断言 poly.polyval 的输出形状与输入形状 dims 相同
            assert_equal(poly.polyval(x, [1]).shape, dims)
            assert_equal(poly.polyval(x, [1, 0]).shape, dims)
            assert_equal(poly.polyval(x, [1, 0, 0]).shape, dims)

        # 检查处理掩码数组的情况
        mask = [False, True, False]
        mx = np.ma.array([1, 2, 3], mask=mask)
        res = np.polyval([7, 5, 3], mx)
        # 断言 np.polyval 的结果掩码与输入掩码相同
        assert_array_equal(res.mask, mask)

        # 检查保持 ndarray 的子类型
        class C(np.ndarray):
            pass

        cx = np.array([1, 2, 3]).view(C)
        # 断言 np.polyval 的返回类型与输入类型相同
        assert_equal(type(np.polyval([2, 3, 4], cx)), C)
    def test_polyvalfromroots(self):
        # 检查在根数组上广播 x 值时抛出异常,因为根数组维度太少
        assert_raises(ValueError, poly.polyvalfromroots,
                      [1], [1], tensor=False)

        # 检查空输入
        assert_equal(poly.polyvalfromroots([], [1]).size, 0)
        assert_(poly.polyvalfromroots([], [1]).shape == (0,))

        # 检查空输入 + 多维根数组
        assert_equal(poly.polyvalfromroots([], [[1] * 5]).size, 0)
        assert_(poly.polyvalfromroots([], [[1] * 5]).shape == (5, 0))

        # 检查标量输入
        assert_equal(poly.polyvalfromroots(1, 1), 0)
        assert_(poly.polyvalfromroots(1, np.ones((3, 3))).shape == (3,))

        # 检查正常输入
        x = np.linspace(-1, 1)
        y = [x**i for i in range(5)]
        for i in range(1, 5):
            tgt = y[i]
            res = poly.polyvalfromroots(x, [0]*i)
            assert_almost_equal(res, tgt)
        tgt = x*(x - 1)*(x + 1)
        res = poly.polyvalfromroots(x, [-1, 0, 1])
        assert_almost_equal(res, tgt)

        # 检查形状保持不变
        for i in range(3):
            dims = [2]*i
            x = np.zeros(dims)
            assert_equal(poly.polyvalfromroots(x, [1]).shape, dims)
            assert_equal(poly.polyvalfromroots(x, [1, 0]).shape, dims)
            assert_equal(poly.polyvalfromroots(x, [1, 0, 0]).shape, dims)

        # 检查与因式分解的兼容性
        ptest = [15, 2, -16, -2, 1]
        r = poly.polyroots(ptest)
        x = np.linspace(-1, 1)
        assert_almost_equal(poly.polyval(x, ptest),
                            poly.polyvalfromroots(x, r))

        # 检查多维根数组和值数组
        # 检查 tensor=False
        rshape = (3, 5)
        x = np.arange(-3, 2)
        r = np.random.randint(-5, 5, size=rshape)
        res = poly.polyvalfromroots(x, r, tensor=False)
        tgt = np.empty(r.shape[1:])
        for ii in range(tgt.size):
            tgt[ii] = poly.polyvalfromroots(x[ii], r[:, ii])
        assert_equal(res, tgt)

        # 检查 tensor=True
        x = np.vstack([x, 2*x])
        res = poly.polyvalfromroots(x, r, tensor=True)
        tgt = np.empty(r.shape[1:] + x.shape)
        for ii in range(r.shape[1]):
            for jj in range(x.shape[0]):
                tgt[ii, jj, :] = poly.polyvalfromroots(x[jj], r[:, ii])
        assert_equal(res, tgt)

    def test_polyval2d(self):
        x1, x2, x3 = self.x
        y1, y2, y3 = self.y

        # 测试异常情况
        assert_raises_regex(ValueError, 'incompatible',
                            poly.polyval2d, x1, x2[:2], self.c2d)

        # 测试数值计算
        tgt = y1*y2
        res = poly.polyval2d(x1, x2, self.c2d)
        assert_almost_equal(res, tgt)

        # 测试形状
        z = np.ones((2, 3))
        res = poly.polyval2d(z, z, self.c2d)
        assert_(res.shape == (2, 3))
    # 定义测试多项式三维求值的方法
    def test_polyval3d(self):
        # 从 self.x 中解包得到 x1, x2, x3
        x1, x2, x3 = self.x
        # 从 self.y 中解包得到 y1, y2, y3

        # 测试异常情况,断言抛出 ValueError 异常并包含 'incompatible' 字符串
        assert_raises_regex(ValueError, 'incompatible',
                      poly.polyval3d, x1, x2, x3[:2], self.c3d)

        # 计算目标值 tgt
        tgt = y1 * y2 * y3
        # 使用 poly.polyval3d 计算结果 res
        res = poly.polyval3d(x1, x2, x3, self.c3d)
        # 断言 res 与 tgt 几乎相等
        assert_almost_equal(res, tgt)

        # 测试返回结果的形状
        z = np.ones((2, 3))
        # 使用 poly.polyval3d 计算结果 res
        res = poly.polyval3d(z, z, z, self.c3d)
        # 断言 res 的形状为 (2, 3)
        assert_(res.shape == (2, 3))

    # 定义测试二维多项式网格化的方法
    def test_polygrid2d(self):
        # 从 self.x 中解包得到 x1, x2, x3
        x1, x2, x3 = self.x
        # 从 self.y 中解包得到 y1, y2, y3

        # 计算目标值 tgt
        tgt = np.einsum('i,j->ij', y1, y2)
        # 使用 poly.polygrid2d 计算结果 res
        res = poly.polygrid2d(x1, x2, self.c2d)
        # 断言 res 与 tgt 几乎相等
        assert_almost_equal(res, tgt)

        # 测试返回结果的形状
        z = np.ones((2, 3))
        # 使用 poly.polygrid2d 计算结果 res
        res = poly.polygrid2d(z, z, self.c2d)
        # 断言 res 的形状为 (2, 3, 2)
        assert_(res.shape == (2, 3)*2)

    # 定义测试三维多项式网格化的方法
    def test_polygrid3d(self):
        # 从 self.x 中解包得到 x1, x2, x3
        x1, x2, x3 = self.x
        # 从 self.y 中解包得到 y1, y2, y3

        # 计算目标值 tgt
        tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
        # 使用 poly.polygrid3d 计算结果 res
        res = poly.polygrid3d(x1, x2, x3, self.c3d)
        # 断言 res 与 tgt 几乎相等
        assert_almost_equal(res, tgt)

        # 测试返回结果的形状
        z = np.ones((2, 3))
        # 使用 poly.polygrid3d 计算结果 res
        res = poly.polygrid3d(z, z, z, self.c3d)
        # 断言 res 的形状为 (2, 3, 3)
        assert_(res.shape == (2, 3)*3)
class TestIntegral:

    def test_polyint_axis(self):
        # 检查轴关键字的工作情况
        c2d = np.random.random((3, 4))  # 创建一个 3x4 的随机数组

        # 在轴 0 上进行多项式积分,并将结果垂直堆叠以获得目标数组
        tgt = np.vstack([poly.polyint(c) for c in c2d.T]).T
        res = poly.polyint(c2d, axis=0)
        assert_almost_equal(res, tgt)

        # 在轴 1 上进行多项式积分,并将结果垂直堆叠以获得目标数组
        tgt = np.vstack([poly.polyint(c) for c in c2d])
        res = poly.polyint(c2d, axis=1)
        assert_almost_equal(res, tgt)

        # 在轴 1 上进行多项式积分,同时指定多项式的次数 k=3,并将结果垂直堆叠以获得目标数组
        tgt = np.vstack([poly.polyint(c, k=3) for c in c2d])
        res = poly.polyint(c2d, k=3, axis=1)
        assert_almost_equal(res, tgt)


class TestDerivative:

    def test_polyder(self):
        # 检查异常情况:期望抛出 TypeError 异常
        assert_raises(TypeError, poly.polyder, [0], .5)
        # 检查异常情况:期望抛出 ValueError 异常
        assert_raises(ValueError, poly.polyder, [0], -1)

        # 检查零阶导数不做任何操作
        for i in range(5):
            tgt = [0]*i + [1]
            res = poly.polyder(tgt, m=0)
            assert_equal(trim(res), trim(tgt))

        # 检查导数与积分的反向关系
        for i in range(5):
            for j in range(2, 5):
                tgt = [0]*i + [1]
                # 对多次积分的多项式进行 j 阶导数运算,并断言与原始多项式相等
                res = poly.polyder(poly.polyint(tgt, m=j), m=j)
                assert_almost_equal(trim(res), trim(tgt))

        # 检查带有缩放的导数运算
        for i in range(5):
            for j in range(2, 5):
                tgt = [0]*i + [1]
                # 对多次积分的多项式进行 j 阶导数运算,并指定不同的缩放参数,断言结果与原始多项式相等
                res = poly.polyder(poly.polyint(tgt, m=j, scl=2), m=j, scl=.5)
                assert_almost_equal(trim(res), trim(tgt))

    def test_polyder_axis(self):
        # 检查轴关键字的工作情况
        c2d = np.random.random((3, 4))  # 创建一个 3x4 的随机数组

        # 在轴 0 上进行多项式导数,并将结果垂直堆叠以获得目标数组
        tgt = np.vstack([poly.polyder(c) for c in c2d.T]).T
        res = poly.polyder(c2d, axis=0)
        assert_almost_equal(res, tgt)

        # 在轴 1 上进行多项式导数,并将结果垂直堆叠以获得目标数组
        tgt = np.vstack([poly.polyder(c) for c in c2d])
        res = poly.polyder(c2d, axis=1)
        assert_almost_equal(res, tgt)


class TestVander:
    # 生成在 [-1, 1) 范围内的随机值
    x = np.random.random((3, 5))*2 - 1

    def test_polyvander(self):
        # 检查 1 维 x 的情况
        x = np.arange(3)
        v = poly.polyvander(x, 3)
        assert_(v.shape == (3, 4))
        for i in range(4):
            coef = [0]*i + [1]
            # 断言多项式的 Vandermonde 矩阵乘以系数向量的结果与多项式的值相等
            assert_almost_equal(v[..., i], poly.polyval(x, coef))

        # 检查 2 维 x 的情况
        x = np.array([[1, 2], [3, 4], [5, 6]])
        v = poly.polyvander(x, 3)
        assert_(v.shape == (3, 2, 4))
        for i in range(4):
            coef = [0]*i + [1]
            # 断言多项式的 Vandermonde 矩阵乘以系数向量的结果与多项式的值相等
            assert_almost_equal(v[..., i], poly.polyval(x, coef))

    def test_polyvander2d(self):
        # 同时测试非方形系数数组的 polyval2d
        x1, x2, x3 = self.x
        c = np.random.random((2, 3))
        van = poly.polyvander2d(x1, x2, [1, 2])
        tgt = poly.polyval2d(x1, x2, c)
        res = np.dot(van, c.flat)
        assert_almost_equal(res, tgt)

        # 检查形状
        van = poly.polyvander2d([x1], [x2], [1, 2])
        assert_(van.shape == (1, 5, 6))
    # 定义一个测试方法,用于测试 polyvander3d 函数
    def test_polyvander3d(self):
        # 同时也测试非方形系数数组的 polyval3d 函数
        x1, x2, x3 = self.x
        # 创建一个 2x3x4 的随机数组作为系数 c
        c = np.random.random((2, 3, 4))
        # 使用 polyvander3d 函数生成三维多项式的 Vandermonde 矩阵 van
        van = poly.polyvander3d(x1, x2, x3, [1, 2, 3])
        # 使用 polyval3d 函数计算目标值 tgt
        tgt = poly.polyval3d(x1, x2, x3, c)
        # 将 van 和 c 的扁平版本相乘得到结果 res
        res = np.dot(van, c.flat)
        # 使用 assert_almost_equal 断言 res 与 tgt 几乎相等
        assert_almost_equal(res, tgt)

        # 检查 van 的形状
        van = poly.polyvander3d([x1], [x2], [x3], [1, 2, 3])
        # 使用 assert_ 断言 van 的形状为 (1, 5, 24)
        assert_(van.shape == (1, 5, 24))

    # 定义一个测试方法,用于测试 polyvander 函数处理负阶数的情况
    def test_polyvandernegdeg(self):
        # 创建一个包含 0, 1, 2 的 numpy 数组 x
        x = np.arange(3)
        # 使用 assert_raises 断言 polyvander 函数对于负阶数会引发 ValueError 异常
        assert_raises(ValueError, poly.polyvander, x, -1)
# 定义名为 TestCompanion 的测试类,用于测试 polycompanion 函数的异常情况和维度
class TestCompanion:

    # 测试函数,验证当输入为空列表时是否会引发 ValueError 异常
    def test_raises(self):
        assert_raises(ValueError, poly.polycompanion, [])
        # 验证当输入只包含一个元素时是否会引发 ValueError 异常
        assert_raises(ValueError, poly.polycompanion, [1])

    # 测试函数,验证 polycompanion 函数生成的 companiom 矩阵的维度是否正确
    def test_dimensions(self):
        # 对于范围从 1 到 4 的每一个整数 i
        for i in range(1, 5):
            # 构造一个系数列表,前 i-1 个元素为 0,最后一个元素为 1
            coef = [0]*i + [1]
            # 验证生成的 companiom 矩阵的形状是否为 (i, i)
            assert_(poly.polycompanion(coef).shape == (i, i))

    # 测试函数,验证 polycompanion 函数对线性多项式 [1, 2] 的 companiom 矩阵的第一个元素是否为 -0.5
    def test_linear_root(self):
        assert_(poly.polycompanion([1, 2])[0, 0] == -.5)


# 定义名为 TestMisc 的测试类,用于测试 polyfromroots 和 polyroots 函数的正确性
class TestMisc:

    # 测试函数,验证 polyfromroots 函数对不同情况下生成的多项式系数是否正确
    def test_polyfromroots(self):
        # 对于空根列表,验证生成的多项式系数是否接近于 [1]
        res = poly.polyfromroots([])
        assert_almost_equal(trim(res), [1])
        # 对于范围从 1 到 4 的每一个整数 i
        for i in range(1, 5):
            # 生成 cos 函数值作为根的列表
            roots = np.cos(np.linspace(-np.pi, 0, 2*i + 1)[1::2])
            # 获取目标多项式系数列表
            tgt = Tlist[i]
            # 根据根列表生成多项式,并乘以 2 的 (i-1) 次方
            res = poly.polyfromroots(roots)*2**(i-1)
            # 验证生成的多项式系数是否接近于目标多项式系数列表
            assert_almost_equal(trim(res), trim(tgt))

    # 测试函数,验证 polyroots 函数对不同多项式系数列表的求根结果是否正确
    def test_polyroots(self):
        # 验证对于 [1] 的多项式系数列表,求根结果是否为空列表
        assert_almost_equal(poly.polyroots([1]), [])
        # 验证对于 [1, 2] 的多项式系数列表,求根结果是否接近于 [-0.5]
        assert_almost_equal(poly.polyroots([1, 2]), [-.5])
        # 对于范围从 2 到 4 的每一个整数 i
        for i in range(2, 5):
            # 生成线性等间距分布的目标根列表
            tgt = np.linspace(-1, 1, i)
            # 根据目标根列表生成多项式系数列表,并求其根
            res = poly.polyroots(poly.polyfromroots(tgt))
            # 验证求得的多项式根是否接近于目标根列表
            assert_almost_equal(trim(res), trim(tgt))
    # 定义一个函数 f(x),返回 x*(x - 1)*(x - 2) 的结果
    def f(x):
        return x*(x - 1)*(x - 2)

    # 定义一个函数 f2(x),返回 x**4 + x**2 + 1 的结果
    def f2(x):
        return x**4 + x**2 + 1

    # 测试异常情况
    assert_raises(ValueError, poly.polyfit, [1], [1], -1)  # 检查是否抛出 ValueError 异常
    assert_raises(TypeError, poly.polyfit, [[1]], [1], 0)   # 检查是否抛出 TypeError 异常
    assert_raises(TypeError, poly.polyfit, [], [1], 0)      # 检查是否抛出 TypeError 异常
    assert_raises(TypeError, poly.polyfit, [1], [[[1]]], 0)  # 检查是否抛出 TypeError 异常
    assert_raises(TypeError, poly.polyfit, [1, 2], [1], 0)   # 检查是否抛出 TypeError 异常
    assert_raises(TypeError, poly.polyfit, [1], [1, 2], 0)   # 检查是否抛出 TypeError 异常
    assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[[1]])  # 检查是否抛出 TypeError 异常
    assert_raises(TypeError, poly.polyfit, [1], [1], 0, w=[1, 1])   # 检查是否抛出 TypeError 异常
    assert_raises(ValueError, poly.polyfit, [1], [1], [-1,])  # 检查是否抛出 ValueError 异常
    assert_raises(ValueError, poly.polyfit, [1], [1], [2, -1, 6])  # 检查是否抛出 ValueError 异常
    assert_raises(TypeError, poly.polyfit, [1], [1], [])  # 检查是否抛出 TypeError 异常

    # 测试多项式拟合
    x = np.linspace(0, 2)  # 生成一个从0到2的等间隔数列作为 x 值
    y = f(x)  # 计算函数 f(x) 在 x 值上的结果

    # 拟合三次多项式并验证结果
    coef3 = poly.polyfit(x, y, 3)
    assert_equal(len(coef3), 4)  # 验证多项式系数的长度是否为4
    assert_almost_equal(poly.polyval(x, coef3), y)  # 验证通过多项式计算的值是否接近真实值

    # 通过指定多项式的系数来拟合并验证结果
    coef3 = poly.polyfit(x, y, [0, 1, 2, 3])
    assert_equal(len(coef3), 4)  # 验证多项式系数的长度是否为4
    assert_almost_equal(poly.polyval(x, coef3), y)  # 验证通过多项式计算的值是否接近真实值

    # 拟合四次多项式并验证结果
    coef4 = poly.polyfit(x, y, 4)
    assert_equal(len(coef4), 5)  # 验证多项式系数的长度是否为5
    assert_almost_equal(poly.polyval(x, coef4), y)  # 验证通过多项式计算的值是否接近真实值

    # 通过指定多项式的系数来拟合并验证结果
    coef4 = poly.polyfit(x, y, [0, 1, 2, 3, 4])
    assert_equal(len(coef4), 5)  # 验证多项式系数的长度是否为5
    assert_almost_equal(poly.polyval(x, coef4), y)  # 验证通过多项式计算的值是否接近真实值

    # 拟合二维数据并验证结果
    coef2d = poly.polyfit(x, np.array([y, y]).T, 3)
    assert_almost_equal(coef2d, np.array([coef3, coef3]).T)  # 验证拟合的二维数据是否与预期的系数一致

    # 通过指定多项式的系数来拟合二维数据并验证结果
    coef2d = poly.polyfit(x, np.array([y, y]).T, [0, 1, 2, 3])
    assert_almost_equal(coef2d, np.array([coef3, coef3]).T)  # 验证拟合的二维数据是否与预期的系数一致

    # 测试加权拟合
    w = np.zeros_like(x)  # 创建与 x 形状相同的全零数组作为权重
    yw = y.copy()  # 复制 y 数组作为加权后的 y 值
    w[1::2] = 1  # 设置奇数索引位置的权重为1
    yw[0::2] = 0  # 将偶数索引位置的 y 值置为0,模拟加权效果
    wcoef3 = poly.polyfit(x, yw, 3, w=w)  # 加权拟合三次多项式并验证结果
    assert_almost_equal(wcoef3, coef3)  # 验证加权拟合的结果是否与未加权的结果一致

    # 通过指定多项式的系数来加权拟合并验证结果
    wcoef3 = poly.polyfit(x, yw, [0, 1, 2, 3], w=w)
    assert_almost_equal(wcoef3, coef3)  # 验证加权拟合的结果是否与未加权的结果一致

    # 拟合二维加权数据并验证结果
    wcoef2d = poly.polyfit(x, np.array([yw, yw]).T, 3, w=w)
    assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)  # 验证拟合的二维加权数据是否与预期的系数一致

    # 通过指定多项式的系数来拟合二维加权数据并验证结果
    wcoef2d = poly.polyfit(x, np.array([yw, yw]).T, [0, 1, 2, 3], w=w)
    assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)  # 验证拟合的二维加权数据是否与预期的系数一致

    # 测试使用复数值的情况,其中 x 值的平方和为零
    x = [1, 1j, -1, -1j]
    assert_almost_equal(poly.polyfit(x, x, 1), [0, 1])  # 验证在复数值上拟合一次多项式的结果

    # 通过指定多项式的系数来拟合复数值的情况
    assert_almost_equal(poly.polyfit(x, x, [0, 1]), [0, 1])  # 验证在复数值上拟合一次多项式的结果

    # 测试仅拟合偶数次勒让德多项式的情况
    x = np.linspace(-1, 1)  # 生成一个从-1到1的等间隔数列作为 x 值
    y = f2(x)  # 计算函数 f2(x) 在 x 值上的结果

    # 拟合四次勒让德多项式并验证结果
    coef1 = poly.polyfit(x, y, 4)
    assert_almost_equal(poly.polyval(x, coef1), y)  # 验证通过多项式计算的值是否接近真实值

    # 通过指定多项式的系数来仅拟合偶数次勒让德多项式并验证结果
    coef2 = poly.polyfit(x, y, [0, 2, 4])
    assert_almost_equal(poly.polyval(x, coef2), y)  # 验证通过多项式计算的值是否接近真实值

    assert_almost_equal(coef1, coef2)  # 验证两种方式得到的系数是否一致
    # 定义一个测试方法,用于测试 poly.polytrim 函数
    def test_polytrim(self):
        # 设置一个多项式的系数列表
        coef = [2, -1, 1, 0]

        # 测试异常情况:验证当指定的阶数为负数时,是否引发 ValueError 异常
        assert_raises(ValueError, poly.polytrim, coef, -1)

        # 测试正常情况下的结果:
        # 1. 验证默认情况下,poly.polytrim 函数能够正确地截取掉最高次项系数后的多项式系数列表
        assert_equal(poly.polytrim(coef), coef[:-1])
        # 2. 验证当指定截取的阶数为1时,poly.polytrim 函数是否正确截取掉最高次和次高次项系数
        assert_equal(poly.polytrim(coef, 1), coef[:-3])
        # 3. 验证当指定截取的阶数为2时,poly.polytrim 函数是否返回只有常数项的列表 [0]
        assert_equal(poly.polytrim(coef, 2), [0])

    # 定义一个测试方法,用于测试 poly.polyline 函数
    def test_polyline(self):
        # 验证 poly.polyline 函数是否能正确返回给定参数的列表表示的多项式
        assert_equal(poly.polyline(3, 4), [3, 4])

    # 定义一个测试方法,用于测试 poly.polyline 函数中参数为0的情况
    def test_polyline_zero(self):
        # 验证 poly.polyline 函数当第二个参数为0时,是否正确返回只含有第一个参数的列表
        assert_equal(poly.polyline(3, 0), [3])

.\numpy\numpy\polynomial\tests\test_polyutils.py

"""Tests for polyutils module.

"""
# 导入必要的库和模块
import numpy as np
import numpy.polynomial.polyutils as pu
from numpy.testing import (
    assert_almost_equal, assert_raises, assert_equal, assert_,
    )

# 定义测试类 TestMisc
class TestMisc:

    # 测试函数 test_trimseq
    def test_trimseq(self):
        # 设置目标结果
        tgt = [1]
        # 遍历不同的尾部零个数
        for num_trailing_zeros in range(5):
            # 调用 trimseq 函数并断言结果与目标结果相等
            res = pu.trimseq([1] + [0] * num_trailing_zeros)
            assert_equal(res, tgt)

    # 测试函数 test_trimseq_empty_input
    def test_trimseq_empty_input(self):
        # 遍历空输入序列的不同类型
        for empty_seq in [[], np.array([], dtype=np.int32)]:
            # 调用 trimseq 函数并断言结果与输入序列相等
            assert_equal(pu.trimseq(empty_seq), empty_seq)

    # 测试函数 test_as_series
    def test_as_series(self):
        # 检查异常情况
        assert_raises(ValueError, pu.as_series, [[]])
        assert_raises(ValueError, pu.as_series, [[[1, 2]]])
        assert_raises(ValueError, pu.as_series, [[1], ['a']])
        
        # 检查常见类型
        types = ['i', 'd', 'O']
        for i in range(len(types)):
            for j in range(i):
                ci = np.ones(1, types[i])
                cj = np.ones(1, types[j])
                [resi, resj] = pu.as_series([ci, cj])
                assert_(resi.dtype.char == resj.dtype.char)
                assert_(resj.dtype.char == types[i])

    # 测试函数 test_trimcoef
    def test_trimcoef(self):
        coef = [2, -1, 1, 0]
        # 测试异常情况
        assert_raises(ValueError, pu.trimcoef, coef, -1)
        # 测试结果
        assert_equal(pu.trimcoef(coef), coef[:-1])
        assert_equal(pu.trimcoef(coef, 1), coef[:-3])
        assert_equal(pu.trimcoef(coef, 2), [0])

    # 测试函数 test_vander_nd_exception
    def test_vander_nd_exception(self):
        # n_dims != len(points)
        assert_raises(ValueError, pu._vander_nd, (), (1, 2, 3), [90])
        # n_dims != len(degrees)
        assert_raises(ValueError, pu._vander_nd, (), (), [90.65])
        # n_dims == 0
        assert_raises(ValueError, pu._vander_nd, (), (), [])

    # 测试函数 test_div_zerodiv
    def test_div_zerodiv(self):
        # c2[-1] == 0
        assert_raises(ZeroDivisionError, pu._div, pu._div, (1, 2, 3), [0])

    # 测试函数 test_pow_too_large
    def test_pow_too_large(self):
        # power > maxpower
        assert_raises(ValueError, pu._pow, (), [1, 2, 3], 5, 4)

# 定义测试类 TestDomain
class TestDomain:

    # 测试函数 test_getdomain
    def test_getdomain(self):
        # 测试实数值情况
        x = [1, 10, 3, -1]
        tgt = [-1, 10]
        res = pu.getdomain(x)
        assert_almost_equal(res, tgt)

        # 测试复数值情况
        x = [1 + 1j, 1 - 1j, 0, 2]
        tgt = [-1j, 2 + 1j]
        res = pu.getdomain(x)
        assert_almost_equal(res, tgt)
    # 定义测试方法 test_mapdomain,用于测试 mapdomain 函数的不同情况
    def test_mapdomain(self):
        # 测试实数值情况
        
        # 定义第一个定义域 dom1
        dom1 = [0, 4]
        # 定义第二个定义域 dom2
        dom2 = [1, 3]
        # 定义目标值 tgt 为 dom2
        tgt = dom2
        # 调用 pu.mapdomain 函数,将 dom1 映射到 dom2,并返回结果 res
        res = pu.mapdomain(dom1, dom1, dom2)
        # 断言 res 与目标值 tgt 几乎相等
        assert_almost_equal(res, tgt)

        # 测试复数值情况
        
        # 重新定义 dom1 为复数列表
        dom1 = [0 - 1j, 2 + 1j]
        # 定义第二个定义域 dom2
        dom2 = [-2, 2]
        # 目标值 tgt 为 dom2
        tgt = dom2
        # 定义 x 为 dom1
        x = dom1
        # 调用 pu.mapdomain 函数,将 x 映射到 dom2,并返回结果 res
        res = pu.mapdomain(x, dom1, dom2)
        # 断言 res 与目标值 tgt 几乎相等
        assert_almost_equal(res, tgt)

        # 测试多维数组情况
        
        # 重新定义 dom1 和 dom2 为数组
        dom1 = [0, 4]
        dom2 = [1, 3]
        # 目标值 tgt 为 dom2 组成的 numpy 数组
        tgt = np.array([dom2, dom2])
        # 定义 x 为 dom1 组成的 numpy 数组
        x = np.array([dom1, dom1])
        # 调用 pu.mapdomain 函数,将 x 中的每个元素映射到 dom2,并返回结果 res
        res = pu.mapdomain(x, dom1, dom2)
        # 断言 res 与目标值 tgt 几乎相等
        assert_almost_equal(res, tgt)

        # 测试子类型保持不变的情况
        
        # 定义 MyNDArray 类,继承自 np.ndarray
        class MyNDArray(np.ndarray):
            pass
        
        # 重新定义 dom1 和 dom2
        dom1 = [0, 4]
        dom2 = [1, 3]
        # 定义 x 为 dom1 组成的 numpy 数组,转换为 MyNDArray 类型
        x = np.array([dom1, dom1]).view(MyNDArray)
        # 调用 pu.mapdomain 函数,将 x 映射到 dom2,并返回结果 res
        res = pu.mapdomain(x, dom1, dom2)
        # 断言 res 的类型为 MyNDArray 类型
        assert_(isinstance(res, MyNDArray))

    # 定义测试方法 test_mapparms,用于测试 mapparms 函数的不同情况
    def test_mapparms(self):
        # 测试实数值情况
        
        # 定义第一个定义域 dom1
        dom1 = [0, 4]
        # 定义第二个定义域 dom2
        dom2 = [1, 3]
        # 定义目标值 tgt 为列表 [1, .5]
        tgt = [1, .5]
        # 调用 pu.mapparms 函数,将 dom1 映射到 dom2,并返回结果 res
        res = pu.mapparms(dom1, dom2)
        # 断言 res 与目标值 tgt 几乎相等
        assert_almost_equal(res, tgt)

        # 测试复数值情况
        
        # 重新定义 dom1 为复数列表
        dom1 = [0 - 1j, 2 + 1j]
        # 定义第二个定义域 dom2
        dom2 = [-2, 2]
        # 定义目标值 tgt 为复数列表 [-1 + 1j, 1 - 1j]
        tgt = [-1 + 1j, 1 - 1j]
        # 调用 pu.mapparms 函数,将 dom1 映射到 dom2,并返回结果 res
        res = pu.mapparms(dom1, dom2)
        # 断言 res 与目标值 tgt 几乎相等
        assert_almost_equal(res, tgt)

.\numpy\numpy\polynomial\tests\test_printing.py

# 导入数学模块中的特定常数和函数(NaN和无穷大),用于测试
from math import nan, inf
# 导入 pytest 模块,用于编写和运行测试
import pytest
# 导入 numpy 中的数组、序列和打印选项
from numpy._core import array, arange, printoptions
# 导入 numpy 中的多项式模块
import numpy.polynomial as poly
# 导入 numpy 测试模块中的断言函数
from numpy.testing import assert_equal, assert_

# 用于测试带有对象数组的多项式打印
from fractions import Fraction  # 导入分数运算模块
from decimal import Decimal  # 导入十进制运算模块


class TestStrUnicodeSuperSubscripts:

    @pytest.fixture(scope='class', autouse=True)
    def use_unicode(self):
        # 设置默认的多项式打印风格为 Unicode
        poly.set_default_printstyle('unicode')

    @pytest.mark.parametrize(('inp', 'tgt'), (
        ([1, 2, 3], "1.0 + 2.0·x + 3.0·x²"),  # 参数化测试用例,期望输出为多项式字符串
        ([-1, 0, 3, -1], "-1.0 + 0.0·x + 3.0·x² - 1.0·x³"),
        (arange(12), ("0.0 + 1.0·x + 2.0·x² + 3.0·x³ + 4.0·x⁴ + 5.0·x⁵ + "
                      "6.0·x⁶ + 7.0·x⁷ +\n8.0·x⁸ + 9.0·x⁹ + 10.0·x¹⁰ + "
                      "11.0·x¹¹")),
    ))
    def test_polynomial_str(self, inp, tgt):
        # 创建多项式对象
        p = poly.Polynomial(inp)
        # 获取多项式对象的字符串表示
        res = str(p)
        # 断言字符串表示与目标字符串相等
        assert_equal(res, tgt)

    @pytest.mark.parametrize(('inp', 'tgt'), (
        ([1, 2, 3], "1.0 + 2.0·T₁(x) + 3.0·T₂(x)"),  # 参数化测试用例,期望输出为切比雪夫多项式字符串
        ([-1, 0, 3, -1], "-1.0 + 0.0·T₁(x) + 3.0·T₂(x) - 1.0·T₃(x)"),
        (arange(12), ("0.0 + 1.0·T₁(x) + 2.0·T₂(x) + 3.0·T₃(x) + 4.0·T₄(x) + "
                      "5.0·T₅(x) +\n6.0·T₆(x) + 7.0·T₇(x) + 8.0·T₈(x) + "
                      "9.0·T₉(x) + 10.0·T₁₀(x) + 11.0·T₁₁(x)")),
    ))
    def test_chebyshev_str(self, inp, tgt):
        # 获取切比雪夫多项式的字符串表示
        res = str(poly.Chebyshev(inp))
        # 断言字符串表示与目标字符串相等
        assert_equal(res, tgt)

    @pytest.mark.parametrize(('inp', 'tgt'), (
        ([1, 2, 3], "1.0 + 2.0·P₁(x) + 3.0·P₂(x)"),  # 参数化测试用例,期望输出为勒让德多项式字符串
        ([-1, 0, 3, -1], "-1.0 + 0.0·P₁(x) + 3.0·P₂(x) - 1.0·P₃(x)"),
        (arange(12), ("0.0 + 1.0·P₁(x) + 2.0·P₂(x) + 3.0·P₃(x) + 4.0·P₄(x) + "
                      "5.0·P₅(x) +\n6.0·P₆(x) + 7.0·P₇(x) + 8.0·P₈(x) + "
                      "9.0·P₉(x) + 10.0·P₁₀(x) + 11.0·P₁₁(x)")),
    ))
    def test_legendre_str(self, inp, tgt):
        # 获取勒让德多项式的字符串表示
        res = str(poly.Legendre(inp))
        # 断言字符串表示与目标字符串相等
        assert_equal(res, tgt)

    @pytest.mark.parametrize(('inp', 'tgt'), (
        ([1, 2, 3], "1.0 + 2.0·H₁(x) + 3.0·H₂(x)"),  # 参数化测试用例,期望输出为埃尔米特多项式字符串
        ([-1, 0, 3, -1], "-1.0 + 0.0·H₁(x) + 3.0·H₂(x) - 1.0·H₃(x)"),
        (arange(12), ("0.0 + 1.0·H₁(x) + 2.0·H₂(x) + 3.0·H₃(x) + 4.0·H₄(x) + "
                      "5.0·H₅(x) +\n6.0·H₆(x) + 7.0·H₇(x) + 8.0·H₈(x) + "
                      "9.0·H₉(x) + 10.0·H₁₀(x) + 11.0·H₁₁(x)")),
    ))
    def test_hermite_str(self, inp, tgt):
        # 获取埃尔米特多项式的字符串表示
        res = str(poly.Hermite(inp))
        # 断言字符串表示与目标字符串相等
        assert_equal(res, tgt)

    @pytest.mark.parametrize(('inp', 'tgt'), (
        ([1, 2, 3], "1.0 + 2.0·He₁(x) + 3.0·He₂(x)"),  # 参数化测试用例,期望输出为埃尔米特多项式(第二类)字符串
        ([-1, 0, 3, -1], "-1.0 + 0.0·He₁(x) + 3.0·He₂(x) - 1.0·He₃(x)"),
        (arange(12), ("0.0 + 1.0·He₁(x) + 2.0·He₂(x) + 3.0·He₃(x) + "
                      "4.0·He₄(x) + 5.0·He₅(x) +\n6.0·He₆(x) + 7.0·He₇(x) + "
                      "8.0·He₈(x) + 9.0·He₉(x) + 10.0·He₁₀(x) +\n"
                      "11.0·He₁₁(x)")),
    ))
    def test_hermiteE_str(self, inp, tgt):
        # 获取埃尔米特多项式(第二类)的字符串表示
        res = str(poly.HermiteE(inp))
        # 断言字符串表示与目标字符串相等
        assert_equal(res, tgt)
    # 使用 pytest 模块的装饰器标记参数化测试用例
    @pytest.mark.parametrize(('inp', 'tgt'), (
        # 测试用例1:输入为 [1, 2, 3],期望输出为 "1.0 + 2.0·L₁(x) + 3.0·L₂(x)"
        ([1, 2, 3], "1.0 + 2.0·L₁(x) + 3.0·L₂(x)"),
    
        # 测试用例2:输入为 [-1, 0, 3, -1],期望输出为 "-1.0 + 0.0·L₁(x) + 3.0·L₂(x) - 1.0·L₃(x)"
        ([-1, 0, 3, -1], "-1.0 + 0.0·L₁(x) + 3.0·L₂(x) - 1.0·L₃(x)"),
    
        # 测试用例3:输入为 arange(12),期望输出为较长的多项式表达式字符串
        (arange(12), ("0.0 + 1.0·L₁(x) + 2.0·L₂(x) + 3.0·L₃(x) + 4.0·L₄(x) + "
                      "5.0·L₅(x) +\n6.0·L₆(x) + 7.0·L₇(x) + 8.0·L₈(x) + "
                      "9.0·L₉(x) + 10.0·L₁₀(x) + 11.0·L₁₁(x)")),
    ))
    def test_laguerre_str(self, inp, tgt):
        # 调用 Laguerre 类的 str 方法,将输入转换为字符串
        res = str(poly.Laguerre(inp))
        # 断言测试结果等于期望输出
        assert_equal(res, tgt)
    
    # 定义测试多项式字符串表示中的域
    def test_polynomial_str_domains(self):
        # 测试用例1:多项式 [0, 1] 的字符串表示应为 '0.0 + 1.0·x'
        res = str(poly.Polynomial([0, 1]))
        tgt = '0.0 + 1.0·x'
        assert_equal(res, tgt)
    
        # 测试用例2:在指定域 [1, 2] 内的多项式 [0, 1] 的字符串表示应为 '0.0 + 1.0·(-3.0 + 2.0x)'
        res = str(poly.Polynomial([0, 1], domain=[1, 2]))
        tgt = '0.0 + 1.0·(-3.0 + 2.0x)'
        assert_equal(res, tgt)
# 定义一个测试类 TestStrAscii,用于测试多项式和多种特定函数的字符串表示
class TestStrAscii:

    # 设置一个 pytest 的 fixture,作用域为 class 级别,在整个测试类中自动使用 ASCII 打印风格
    @pytest.fixture(scope='class', autouse=True)
    def use_ascii(self):
        # 调用 poly 模块的 set_default_printstyle 方法,设置默认打印风格为 ASCII
        poly.set_default_printstyle('ascii')

    # 使用 pytest 的 parametrize 装饰器,定义多组参数化测试用例,测试 Polynomial 类的字符串表示
    @pytest.mark.parametrize(('inp', 'tgt'), (
        ([1, 2, 3], "1.0 + 2.0 x + 3.0 x**2"),
        ([-1, 0, 3, -1], "-1.0 + 0.0 x + 3.0 x**2 - 1.0 x**3"),
        (arange(12), ("0.0 + 1.0 x + 2.0 x**2 + 3.0 x**3 + 4.0 x**4 + "
                      "5.0 x**5 + 6.0 x**6 +\n7.0 x**7 + 8.0 x**8 + "
                      "9.0 x**9 + 10.0 x**10 + 11.0 x**11")),
    ))
    # 定义测试方法 test_polynomial_str,参数化测试 Polynomial 类的字符串表示是否与预期相符
    def test_polynomial_str(self, inp, tgt):
        # 创建 Polynomial 对象,并将其转换为字符串表示
        res = str(poly.Polynomial(inp))
        # 使用 assert_equal 断言检查结果是否与目标字符串 tgt 相等
        assert_equal(res, tgt)

    # 使用 pytest 的 parametrize 装饰器,定义多组参数化测试用例,测试 Chebyshev 类的字符串表示
    @pytest.mark.parametrize(('inp', 'tgt'), (
        ([1, 2, 3], "1.0 + 2.0 T_1(x) + 3.0 T_2(x)"),
        ([-1, 0, 3, -1], "-1.0 + 0.0 T_1(x) + 3.0 T_2(x) - 1.0 T_3(x)"),
        (arange(12), ("0.0 + 1.0 T_1(x) + 2.0 T_2(x) + 3.0 T_3(x) + "
                      "4.0 T_4(x) + 5.0 T_5(x) +\n6.0 T_6(x) + 7.0 T_7(x) + "
                      "8.0 T_8(x) + 9.0 T_9(x) + 10.0 T_10(x) +\n"
                      "11.0 T_11(x)")),
    ))
    # 定义测试方法 test_chebyshev_str,参数化测试 Chebyshev 类的字符串表示是否与预期相符
    def test_chebyshev_str(self, inp, tgt):
        # 创建 Chebyshev 对象,并将其转换为字符串表示
        res = str(poly.Chebyshev(inp))
        # 使用 assert_equal 断言检查结果是否与目标字符串 tgt 相等
        assert_equal(res, tgt)

    # 使用 pytest 的 parametrize 装饰器,定义多组参数化测试用例,测试 Legendre 类的字符串表示
    @pytest.mark.parametrize(('inp', 'tgt'), (
        ([1, 2, 3], "1.0 + 2.0 P_1(x) + 3.0 P_2(x)"),
        ([-1, 0, 3, -1], "-1.0 + 0.0 P_1(x) + 3.0 P_2(x) - 1.0 P_3(x)"),
        (arange(12), ("0.0 + 1.0 P_1(x) + 2.0 P_2(x) + 3.0 P_3(x) + "
                      "4.0 P_4(x) + 5.0 P_5(x) +\n6.0 P_6(x) + 7.0 P_7(x) + "
                      "8.0 P_8(x) + 9.0 P_9(x) + 10.0 P_10(x) +\n"
                      "11.0 P_11(x)")),
    ))
    # 定义测试方法 test_legendre_str,参数化测试 Legendre 类的字符串表示是否与预期相符
    def test_legendre_str(self, inp, tgt):
        # 创建 Legendre 对象,并将其转换为字符串表示
        res = str(poly.Legendre(inp))
        # 使用 assert_equal 断言检查结果是否与目标字符串 tgt 相等
        assert_equal(res, tgt)

    # 使用 pytest 的 parametrize 装饰器,定义多组参数化测试用例,测试 Hermite 类的字符串表示
    @pytest.mark.parametrize(('inp', 'tgt'), (
        ([1, 2, 3], "1.0 + 2.0 H_1(x) + 3.0 H_2(x)"),
        ([-1, 0, 3, -1], "-1.0 + 0.0 H_1(x) + 3.0 H_2(x) - 1.0 H_3(x)"),
        (arange(12), ("0.0 + 1.0 H_1(x) + 2.0 H_2(x) + 3.0 H_3(x) + "
                      "4.0 H_4(x) + 5.0 H_5(x) +\n6.0 H_6(x) + 7.0 H_7(x) + "
                      "8.0 H_8(x) + 9.0 H_9(x) + 10.0 H_10(x) +\n"
                      "11.0 H_11(x)")),
    ))
    # 定义测试方法 test_hermite_str,参数化测试 Hermite 类的字符串表示是否与预期相符
    def test_hermite_str(self, inp, tgt):
        # 创建 Hermite 对象,并将其转换为字符串表示
        res = str(poly.Hermite(inp))
        # 使用 assert_equal 断言检查结果是否与目标字符串 tgt 相等
        assert_equal(res, tgt)

    # 使用 pytest 的 parametrize 装饰器,定义多组参数化测试用例,测试 HermiteE 类的字符串表示
    @pytest.mark.parametrize(('inp', 'tgt'), (
        ([1, 2, 3], "1.0 + 2.0 He_1(x) + 3.0 He_2(x)"),
        ([-1, 0, 3, -1], "-1.0 + 0.0 He_1(x) + 3.0 He_2(x) - 1.0 He_3(x)"),
        (arange(12), ("0.0 + 1.0 He_1(x) + 2.0 He_2(x) + 3.0 He_3(x) + "
                      "4.0 He_4(x) +\n5.0 He_5(x) + 6.0 He_6(x) + "
                      "7.0 He_7(x) + 8.0 He_8(x) + 9.0 He_9(x) +\n"
                      "10.0 He_10(x) + 11.0 He_11(x)")),
    ))
    # 定义测试方法 test_hermiteE_str,参数化测试 HermiteE 类的字符串表示是否与预期相符
    def test_hermiteE_str(self, inp, tgt):
        # 创建 HermiteE 对象,并将其转换为字符串表示
        res = str(poly.HermiteE(inp))
        # 使用 assert_equal 断言检查结果是否与目标字符串 tgt 相等
        assert_equal(res, tgt)
    # 使用 pytest 的参数化装饰器来定义多组输入和期望输出
    @pytest.mark.parametrize(('inp', 'tgt'), (
        # 第一组测试参数:输入为 [1, 2, 3],期望输出为 "1.0 + 2.0 L_1(x) + 3.0 L_2(x)"
        ([1, 2, 3], "1.0 + 2.0 L_1(x) + 3.0 L_2(x)"),
        # 第二组测试参数:输入为 [-1, 0, 3, -1],期望输出为 "-1.0 + 0.0 L_1(x) + 3.0 L_2(x) - 1.0 L_3(x)"
        ([-1, 0, 3, -1], "-1.0 + 0.0 L_1(x) + 3.0 L_2(x) - 1.0 L_3(x)"),
        # 第三组测试参数:输入为 arange(12),期望输出为长字符串,表示多项式的展示
        (arange(12), ("0.0 + 1.0 L_1(x) + 2.0 L_2(x) + 3.0 L_3(x) + "
                      "4.0 L_4(x) + 5.0 L_5(x) +\n6.0 L_6(x) + 7.0 L_7(x) + "
                      "8.0 L_8(x) + 9.0 L_9(x) + 10.0 L_10(x) +\n"
                      "11.0 L_11(x)")),
    ))
    # 测试 Laguerre 多项式对象的字符串表示是否正确
    def test_laguerre_str(self, inp, tgt):
        # 计算多项式的字符串表示
        res = str(poly.Laguerre(inp))
        # 断言计算结果与期望输出一致
        assert_equal(res, tgt)

    # 测试 Polynomial 多项式对象的字符串表示是否正确,包括指定域的情况
    def test_polynomial_str_domains(self):
        # 测试未指定域的多项式对象
        res = str(poly.Polynomial([0, 1]))
        tgt = '0.0 + 1.0 x'
        assert_equal(res, tgt)

        # 测试指定域为 [1, 2] 的多项式对象
        res = str(poly.Polynomial([0, 1], domain=[1, 2]))
        tgt = '0.0 + 1.0 (-3.0 + 2.0x)'
        assert_equal(res, tgt)
class TestLinebreaking:

    @pytest.fixture(scope='class', autouse=True)
    def use_ascii(self):
        # 设置默认打印风格为 ASCII
        poly.set_default_printstyle('ascii')

    def test_single_line_one_less(self):
        # 使用 'ascii' 风格时,len(str(p)) 是默认行宽减1(即74)
        p = poly.Polynomial([12345678, 12345678, 12345678, 12345678, 123])
        assert_equal(len(str(p)), 74)
        assert_equal(str(p), (
            '12345678.0 + 12345678.0 x + 12345678.0 x**2 + '
            '12345678.0 x**3 + 123.0 x**4'
        ))

    def test_num_chars_is_linewidth(self):
        # len(str(p)) 等于默认行宽(75)
        p = poly.Polynomial([12345678, 12345678, 12345678, 12345678, 1234])
        assert_equal(len(str(p)), 75)
        assert_equal(str(p), (
            '12345678.0 + 12345678.0 x + 12345678.0 x**2 + '
            '12345678.0 x**3 +\n1234.0 x**4'
        ))

    def test_first_linebreak_multiline_one_less_than_linewidth(self):
        # 多行字符串,其中第一行的长度加上下一个术语的长度等于行宽减1(74)
        p = poly.Polynomial(
                [12345678, 12345678, 12345678, 12345678, 1, 12345678]
            )
        assert_equal(len(str(p).split('\n')[0]), 74)
        assert_equal(str(p), (
            '12345678.0 + 12345678.0 x + 12345678.0 x**2 + '
            '12345678.0 x**3 + 1.0 x**4 +\n12345678.0 x**5'
        ))

    def test_first_linebreak_multiline_on_linewidth(self):
        # 第一行比前一个测试长一个字符
        p = poly.Polynomial(
                [12345678, 12345678, 12345678, 12345678.12, 1, 12345678]
            )
        assert_equal(str(p), (
            '12345678.0 + 12345678.0 x + 12345678.0 x**2 + '
            '12345678.12 x**3 +\n1.0 x**4 + 12345678.0 x**5'
        ))

    @pytest.mark.parametrize(('lw', 'tgt'), (
        (75, ('0.0 + 10.0 x + 200.0 x**2 + 3000.0 x**3 + 40000.0 x**4 + '
              '500000.0 x**5 +\n600000.0 x**6 + 70000.0 x**7 + 8000.0 x**8 + '
              '900.0 x**9')),
        (45, ('0.0 + 10.0 x + 200.0 x**2 + 3000.0 x**3 +\n40000.0 x**4 + '
              '500000.0 x**5 +\n600000.0 x**6 + 70000.0 x**7 + 8000.0 x**8 +\n'
              '900.0 x**9')),
        (132, ('0.0 + 10.0 x + 200.0 x**2 + 3000.0 x**3 + 40000.0 x**4 + '
               '500000.0 x**5 + 600000.0 x**6 + 70000.0 x**7 + 8000.0 x**8 + '
               '900.0 x**9')),
    ))
    def test_linewidth_printoption(self, lw, tgt):
        # 创建多项式对象 p
        p = poly.Polynomial(
            [0, 10, 200, 3000, 40000, 500000, 600000, 70000, 8000, 900]
        )
        # 使用给定的行宽 lw 进行打印设置
        with printoptions(linewidth=lw):
            # 断言多项式的字符串表示符合预期目标 tgt
            assert_equal(str(p), tgt)
            # 检查每行字符串的长度是否小于行宽 lw
            for line in str(p).split('\n'):
                assert_(len(line) < lw)


def test_set_default_printoptions():
    # 创建多项式对象 p 和 Chebyshev 对象 c
    p = poly.Polynomial([1, 2, 3])
    c = poly.Chebyshev([1, 2, 3])
    # 设置默认打印风格为 ASCII,并验证多项式和 Chebyshev 的字符串表示
    poly.set_default_printstyle('ascii')
    assert_equal(str(p), "1.0 + 2.0 x + 3.0 x**2")
    assert_equal(str(c), "1.0 + 2.0 T_1(x) + 3.0 T_2(x)")
    # 恢复默认打印风格为 Unicode
    poly.set_default_printstyle('unicode')
    # 断言:验证多项式对象 p 的字符串表示是否等于指定的格式化字符串
    assert_equal(str(p), "1.0 + 2.0·x + 3.0·x²")
    
    # 断言:验证多项式对象 c 的字符串表示是否等于指定的格式化字符串
    assert_equal(str(c), "1.0 + 2.0·T₁(x) + 3.0·T₂(x)")
    
    # 使用 pytest 运行时上下文,验证设置多项式对象的默认打印样式时是否引发 ValueError 异常
    with pytest.raises(ValueError):
        poly.set_default_printstyle('invalid_input')
def test_complex_coefficients():
    """Test both numpy and built-in complex."""
    # 定义复数系数列表
    coefs = [0+1j, 1+1j, -2+2j, 3+0j]
    # 使用 numpy 创建多项式对象 p1
    p1 = poly.Polynomial(coefs)
    # 使用 Python 内置数组和对象类型创建多项式对象 p2
    p2 = poly.Polynomial(array(coefs, dtype=object))
    # 设置多项式打印格式为 unicode
    poly.set_default_printstyle('unicode')
    # 断言 p1 的字符串表示符合预期
    assert_equal(str(p1), "1j + (1+1j)·x - (2-2j)·x² + (3+0j)·x³")
    # 断言 p2 的字符串表示符合预期
    assert_equal(str(p2), "1j + (1+1j)·x + (-2+2j)·x² + (3+0j)·x³")
    # 设置多项式打印格式为 ascii
    poly.set_default_printstyle('ascii')
    # 再次断言 p1 的字符串表示符合预期
    assert_equal(str(p1), "1j + (1+1j) x - (2-2j) x**2 + (3+0j) x**3")
    # 再次断言 p2 的字符串表示符合预期
    assert_equal(str(p2), "1j + (1+1j) x + (-2+2j) x**2 + (3+0j) x**3")


@pytest.mark.parametrize(('coefs', 'tgt'), (
    # 参数化测试:测试带有分数对象系数的情况
    (array([Fraction(1, 2), Fraction(3, 4)], dtype=object), (
        "1/2 + 3/4·x"
    )),
    # 参数化测试:测试带有分数和整数对象系数的情况
    (array([1, 2, Fraction(5, 7)], dtype=object), (
        "1 + 2·x + 5/7·x²"
    )),
    # 参数化测试:测试带有 Decimal 对象系数的情况
    (array([Decimal('1.00'), Decimal('2.2'), 3], dtype=object), (
        "1.00 + 2.2·x + 3·x²"
    )),
))
def test_numeric_object_coefficients(coefs, tgt):
    # 创建多项式对象 p,并设置打印格式为 unicode
    p = poly.Polynomial(coefs)
    poly.set_default_printstyle('unicode')
    # 断言 p 的字符串表示符合预期
    assert_equal(str(p), tgt)


@pytest.mark.parametrize(('coefs', 'tgt'), (
    # 参数化测试:测试带有字符串对象系数的情况
    (array([1, 2, 'f'], dtype=object), '1 + 2·x + f·x²'),
    # 参数化测试:测试带有列表对象系数的情况
    (array([1, 2, [3, 4]], dtype=object), '1 + 2·x + [3, 4]·x²'),
))
def test_nonnumeric_object_coefficients(coefs, tgt):
    """
    Test coef fallback for object arrays of non-numeric coefficients.
    """
    # 创建多项式对象 p,并设置打印格式为 unicode
    p = poly.Polynomial(coefs)
    poly.set_default_printstyle('unicode')
    # 断言 p 的字符串表示符合预期
    assert_equal(str(p), tgt)


class TestFormat:
    def test_format_unicode(self):
        # 设置多项式打印格式为 ascii
        poly.set_default_printstyle('ascii')
        # 创建多项式对象 p
        p = poly.Polynomial([1, 2, 0, -1])
        # 断言 p 的 unicode 格式字符串表示符合预期
        assert_equal(format(p, 'unicode'), "1.0 + 2.0·x + 0.0·x² - 1.0·x³")

    def test_format_ascii(self):
        # 设置多项式打印格式为 unicode
        poly.set_default_printstyle('unicode')
        # 创建多项式对象 p
        p = poly.Polynomial([1, 2, 0, -1])
        # 断言 p 的 ascii 格式字符串表示符合预期
        assert_equal(
            format(p, 'ascii'), "1.0 + 2.0 x + 0.0 x**2 - 1.0 x**3"
        )

    def test_empty_formatstr(self):
        # 设置多项式打印格式为 ascii
        poly.set_default_printstyle('ascii')
        # 创建多项式对象 p
        p = poly.Polynomial([1, 2, 3])
        # 断言 p 的默认字符串表示符合预期
        assert_equal(format(p), "1.0 + 2.0 x + 3.0 x**2")
        # 使用 f-string 断言 p 的字符串表示符合预期
        assert_equal(f"{p}", "1.0 + 2.0 x + 3.0 x**2")

    def test_bad_formatstr(self):
        # 创建多项式对象 p
        p = poly.Polynomial([1, 2, 0, -1])
        # 断言格式化 p 时引发 ValueError 异常
        with pytest.raises(ValueError):
            format(p, '.2f')


@pytest.mark.parametrize(('poly', 'tgt'), (
    # 参数化测试:测试多项式类的 symbol 字段设置和字符串表示
    (poly.Polynomial, '1.0 + 2.0·z + 3.0·z²'),
    (poly.Chebyshev, '1.0 + 2.0·T₁(z) + 3.0·T₂(z)'),
    (poly.Hermite, '1.0 + 2.0·H₁(z) + 3.0·H₂(z)'),
    (poly.HermiteE, '1.0 + 2.0·He₁(z) + 3.0·He₂(z)'),
    (poly.Laguerre, '1.0 + 2.0·L₁(z) + 3.0·L₂(z)'),
    (poly.Legendre, '1.0 + 2.0·P₁(z) + 3.0·P₂(z)'),
))
def test_symbol(poly, tgt):
    # 使用指定的 symbol 创建多项式对象 p
    p = poly([1, 2, 3], symbol='z')
    # 断言 p 的 unicode 格式字符串表示符合预期
    assert_equal(f"{p:unicode}", tgt)


class TestRepr:
    # 测试 Polynomial 类的 repr 方法
    def test_polynomial_repr(self):
        # 创建 Polynomial 对象并调用其 repr 方法,生成字符串表示
        res = repr(poly.Polynomial([0, 1]))
        # 目标字符串表示,包含数组 [0., 1.],领域 domain=[-1.,  1.],窗口 window=[-1.,  1.],符号 symbol='x'
        tgt = (
            "Polynomial([0., 1.], domain=[-1.,  1.], window=[-1.,  1.], "
            "symbol='x')"
        )
        # 断言结果与目标一致
        assert_equal(res, tgt)
    
    # 测试 Chebyshev 类的 repr 方法
    def test_chebyshev_repr(self):
        # 创建 Chebyshev 对象并调用其 repr 方法,生成字符串表示
        res = repr(poly.Chebyshev([0, 1]))
        # 目标字符串表示,包含数组 [0., 1.],领域 domain=[-1.,  1.],窗口 window=[-1.,  1.],符号 symbol='x'
        tgt = (
            "Chebyshev([0., 1.], domain=[-1.,  1.], window=[-1.,  1.], "
            "symbol='x')"
        )
        # 断言结果与目标一致
        assert_equal(res, tgt)
    
    # 测试 Legendre 类的 repr 方法
    def test_legendre_repr(self):
        # 创建 Legendre 对象并调用其 repr 方法,生成字符串表示
        res = repr(poly.Legendre([0, 1]))
        # 目标字符串表示,包含数组 [0., 1.],领域 domain=[-1.,  1.],窗口 window=[-1.,  1.],符号 symbol='x'
        tgt = (
            "Legendre([0., 1.], domain=[-1.,  1.], window=[-1.,  1.], "
            "symbol='x')"
        )
        # 断言结果与目标一致
        assert_equal(res, tgt)
    
    # 测试 Hermite 类的 repr 方法
    def test_hermite_repr(self):
        # 创建 Hermite 对象并调用其 repr 方法,生成字符串表示
        res = repr(poly.Hermite([0, 1]))
        # 目标字符串表示,包含数组 [0., 1.],领域 domain=[-1.,  1.],窗口 window=[-1.,  1.],符号 symbol='x'
        tgt = (
            "Hermite([0., 1.], domain=[-1.,  1.], window=[-1.,  1.], "
            "symbol='x')"
        )
        # 断言结果与目标一致
        assert_equal(res, tgt)
    
    # 测试 HermiteE 类的 repr 方法
    def test_hermiteE_repr(self):
        # 创建 HermiteE 对象并调用其 repr 方法,生成字符串表示
        res = repr(poly.HermiteE([0, 1]))
        # 目标字符串表示,包含数组 [0., 1.],领域 domain=[-1.,  1.],窗口 window=[-1.,  1.],符号 symbol='x'
        tgt = (
            "HermiteE([0., 1.], domain=[-1.,  1.], window=[-1.,  1.], "
            "symbol='x')"
        )
        # 断言结果与目标一致
        assert_equal(res, tgt)
    
    # 测试 Laguerre 类的 repr 方法
    def test_laguerre_repr(self):
        # 创建 Laguerre 对象并调用其 repr 方法,生成字符串表示
        res = repr(poly.Laguerre([0, 1]))
        # 目标字符串表示,包含数组 [0., 1.],领域 domain=[0., 1.],窗口 window=[0., 1.],符号 symbol='x'
        tgt = (
            "Laguerre([0., 1.], domain=[0., 1.], window=[0., 1.], "
            "symbol='x')"
        )
        # 断言结果与目标一致
        assert_equal(res, tgt)
class TestLatexRepr:
    """Test the latex repr used by Jupyter"""

    @staticmethod
    def as_latex(obj):
        # 定义一个静态方法,用于获取对象的 LaTeX 表示
        # 目前忽略标量的格式化,因为它会使测试结果过于冗长。
        # 理想情况下,标量的格式化应当修复,以确保下面的测试继续通过。
        
        # 临时设置对象的标量 LaTeX 表示为 lambda 函数,将对象转换为字符串。
        obj._repr_latex_scalar = lambda x, parens=False: str(x)
        try:
            # 调用对象的 _repr_latex_ 方法,返回其 LaTeX 表示
            return obj._repr_latex_()
        finally:
            # 删除临时设置的标量 LaTeX 表示
            del obj._repr_latex_scalar

    def test_simple_polynomial(self):
        # 测试简单多项式的 LaTeX 表示
        
        # 默认输入,创建一个多项式对象 p
        p = poly.Polynomial([1, 2, 3])
        # 断言对象 p 的 LaTeX 表示符合预期
        assert_equal(self.as_latex(p),
            r'$x \mapsto 1.0 + 2.0\,x + 3.0\,x^{2}$')

        # 翻译后的输入
        p = poly.Polynomial([1, 2, 3], domain=[-2, 0])
        assert_equal(self.as_latex(p),
            r'$x \mapsto 1.0 + 2.0\,\left(1.0 + x\right) + 3.0\,\left(1.0 + x\right)^{2}$')

        # 缩放后的输入
        p = poly.Polynomial([1, 2, 3], domain=[-0.5, 0.5])
        assert_equal(self.as_latex(p),
            r'$x \mapsto 1.0 + 2.0\,\left(2.0x\right) + 3.0\,\left(2.0x\right)^{2}$')

        # 仿射输入
        p = poly.Polynomial([1, 2, 3], domain=[-1, 0])
        assert_equal(self.as_latex(p),
            r'$x \mapsto 1.0 + 2.0\,\left(1.0 + 2.0x\right) + 3.0\,\left(1.0 + 2.0x\right)^{2}$')

    def test_basis_func(self):
        # 测试基函数的 LaTeX 表示
        p = poly.Chebyshev([1, 2, 3])
        assert_equal(self.as_latex(p),
            r'$x \mapsto 1.0\,{T}_{0}(x) + 2.0\,{T}_{1}(x) + 3.0\,{T}_{2}(x)$')
        
        # 仿射输入 - 检查是否添加了多余的括号
        p = poly.Chebyshev([1, 2, 3], domain=[-1, 0])
        assert_equal(self.as_latex(p),
            r'$x \mapsto 1.0\,{T}_{0}(1.0 + 2.0x) + 2.0\,{T}_{1}(1.0 + 2.0x) + 3.0\,{T}_{2}(1.0 + 2.0x)$')

    def test_multichar_basis_func(self):
        # 测试多字符基函数的 LaTeX 表示
        p = poly.HermiteE([1, 2, 3])
        assert_equal(self.as_latex(p),
            r'$x \mapsto 1.0\,{He}_{0}(x) + 2.0\,{He}_{1}(x) + 3.0\,{He}_{2}(x)$')
    def test_symbol_basic(self):
        # 使用默认输入创建多项式对象,指定符号为 'z'
        p = poly.Polynomial([1, 2, 3], symbol='z')
        # 断言多项式对象转换为 LaTeX 格式的字符串是否正确
        assert_equal(self.as_latex(p),
            r'$z \mapsto 1.0 + 2.0\,z + 3.0\,z^{2}$')

        # 使用翻译后的输入创建多项式对象,指定符号为 'z',定义域为 [-2, 0]
        p = poly.Polynomial([1, 2, 3], domain=[-2, 0], symbol='z')
        # 断言多项式对象转换为 LaTeX 格式的字符串是否正确
        assert_equal(
            self.as_latex(p),
            (
                r'$z \mapsto 1.0 + 2.0\,\left(1.0 + z\right) + 3.0\,'
                r'\left(1.0 + z\right)^{2}$'
            ),
        )

        # 使用缩放后的输入创建多项式对象,指定符号为 'z',定义域为 [-0.5, 0.5]
        p = poly.Polynomial([1, 2, 3], domain=[-0.5, 0.5], symbol='z')
        # 断言多项式对象转换为 LaTeX 格式的字符串是否正确
        assert_equal(
            self.as_latex(p),
            (
                r'$z \mapsto 1.0 + 2.0\,\left(2.0z\right) + 3.0\,'
                r'\left(2.0z\right)^{2}$'
            ),
        )

        # 使用仿射输入创建多项式对象,指定符号为 'z',定义域为 [-1, 0]
        p = poly.Polynomial([1, 2, 3], domain=[-1, 0], symbol='z')
        # 断言多项式对象转换为 LaTeX 格式的字符串是否正确
        assert_equal(
            self.as_latex(p),
            (
                r'$z \mapsto 1.0 + 2.0\,\left(1.0 + 2.0z\right) + 3.0\,'
                r'\left(1.0 + 2.0z\right)^{2}$'
            ),
        )

    def test_numeric_object_coefficients(self):
        # 创建具有分数系数的多项式对象
        coefs = array([Fraction(1, 2), Fraction(1)])
        p = poly.Polynomial(coefs)
        # 断言多项式对象转换为 LaTeX 格式的字符串是否正确
        assert_equal(self.as_latex(p), '$x \\mapsto 1/2 + 1\\,x$')
SWITCH_TO_EXP = (
    '1.0 + (1.0e-01) x + (1.0e-02) x**2',  # 第一个多项式表达式
    '1.2 + (1.2e-01) x + (1.2e-02) x**2',  # 第二个多项式表达式
    '1.23 + 0.12 x + (1.23e-02) x**2 + (1.23e-03) x**3',  # 第三个多项式表达式
    '1.235 + 0.123 x + (1.235e-02) x**2 + (1.235e-03) x**3',  # 第四个多项式表达式
    '1.2346 + 0.1235 x + 0.0123 x**2 + (1.2346e-03) x**3 + (1.2346e-04) x**4',  # 第五个多项式表达式
    '1.23457 + 0.12346 x + 0.01235 x**2 + (1.23457e-03) x**3 + (1.23457e-04) x**4',  # 第六个多项式表达式
    '1.234568 + 0.123457 x + 0.012346 x**2 + 0.001235 x**3 + (1.234568e-04) x**4 + (1.234568e-05) x**5',  # 第七个多项式表达式
    '1.2345679 + 0.1234568 x + 0.0123457 x**2 + 0.0012346 x**3 + (1.2345679e-04) x**4 + (1.2345679e-05) x**5'  # 第八个多项式表达式
)

class TestPrintOptions:
    """
    测试通过printoptions正确配置输出选项。
    当值过小或过大时,自动启用指数表示法。
    """

    @pytest.fixture(scope='class', autouse=True)
    def use_ascii(self):
        poly.set_default_printstyle('ascii')  # 设置默认的多项式打印风格为ASCII码风格

    def test_str(self):
        p = poly.Polynomial([1/2, 1/7, 1/7*10**8, 1/7*10**9])
        assert_equal(str(p), '0.5 + 0.14285714 x + 14285714.28571429 x**2 '
                             '+ (1.42857143e+08) x**3')  # 验证多项式的字符串表示格式

        with printoptions(precision=3):
            assert_equal(str(p), '0.5 + 0.143 x + 14285714.286 x**2 '
                                 '+ (1.429e+08) x**3')  # 在指定精度下验证多项式的字符串表示格式

    def test_latex(self):
        p = poly.Polynomial([1/2, 1/7, 1/7*10**8, 1/7*10**9])
        assert_equal(p._repr_latex_(),
            r'$x \mapsto \text{0.5} + \text{0.14285714}\,x + '
            r'\text{14285714.28571429}\,x^{2} + '
            r'\text{(1.42857143e+08)}\,x^{3}$')  # 验证多项式的LaTeX表示格式
        
        with printoptions(precision=3):
            assert_equal(p._repr_latex_(),
                r'$x \mapsto \text{0.5} + \text{0.143}\,x + '
                r'\text{14285714.286}\,x^{2} + \text{(1.429e+08)}\,x^{3}$')  # 在指定精度下验证多项式的LaTeX表示格式

    def test_fixed(self):
        p = poly.Polynomial([1/2])
        assert_equal(str(p), '0.5')  # 验证固定小数位数模式下的多项式字符串表示
        
        with printoptions(floatmode='fixed'):
            assert_equal(str(p), '0.50000000')  # 在固定小数位数模式下验证多项式的字符串表示
        
        with printoptions(floatmode='fixed', precision=4):
            assert_equal(str(p), '0.5000')  # 在固定小数位数和指定精度下验证多项式的字符串表示

    def test_switch_to_exp(self):
        for i, s in enumerate(SWITCH_TO_EXP):
            with printoptions(precision=i):
                p = poly.Polynomial([1.23456789*10**-i 
                                     for i in range(i//2+3)])
                assert str(p).replace('\n', ' ') == s  # 在指定精度下验证多项式转换为指数表示的字符串格式
    
    def test_non_finite(self):
        p = poly.Polynomial([nan, inf])
        assert str(p) == 'nan + inf x'  # 验证包含非有限数的多项式的字符串表示
        assert p._repr_latex_() == r'$x \mapsto \text{nan} + \text{inf}\,x$'  # 验证包含非有限数的多项式的LaTeX表示
        
        with printoptions(nanstr='NAN', infstr='INF'):
            assert str(p) == 'NAN + INF x'  # 在指定NaN和Inf字符串的情况下验证多项式的字符串表示
            assert p._repr_latex_() == \
                r'$x \mapsto \text{NAN} + \text{INF}\,x$'  # 在指定NaN和Inf字符串的情况下验证多项式的LaTeX表示

.\numpy\numpy\polynomial\tests\test_symbol.py

"""
Tests related to the ``symbol`` attribute of the ABCPolyBase class.
"""

import pytest  # 导入 pytest 测试框架
import numpy.polynomial as poly  # 导入 numpy.polynomial 模块
from numpy._core import array  # 导入 numpy 数组模块
from numpy.testing import assert_equal, assert_raises, assert_  # 导入断言函数


class TestInit:
    """
    Test polynomial creation with symbol kwarg.
    """
    c = [1, 2, 3]  # 定义多项式系数列表

    def test_default_symbol(self):
        p = poly.Polynomial(self.c)  # 创建多项式对象
        assert_equal(p.symbol, 'x')  # 断言多项式的默认符号为 'x'

    @pytest.mark.parametrize(('bad_input', 'exception'), (
        ('', ValueError),  # 空字符串引发 ValueError 异常
        ('3', ValueError),  # 字符串 '3' 引发 ValueError 异常
        (None, TypeError),   # None 引发 TypeError 异常
        (1, TypeError),      # 数字 1 引发 TypeError 异常
    ))
    def test_symbol_bad_input(self, bad_input, exception):
        with pytest.raises(exception):
            p = poly.Polynomial(self.c, symbol=bad_input)  # 使用不良输入创建多项式对象

    @pytest.mark.parametrize('symbol', (
        'x',
        'x_1',
        'A',
        'xyz',
        'β',
    ))
    def test_valid_symbols(self, symbol):
        """
        Values for symbol that should pass input validation.
        """
        p = poly.Polynomial(self.c, symbol=symbol)  # 使用有效符号创建多项式对象
        assert_equal(p.symbol, symbol)  # 断言多项式的符号与预期符号相同

    def test_property(self):
        """
        'symbol' attribute is read only.
        """
        p = poly.Polynomial(self.c, symbol='x')  # 创建多项式对象
        with pytest.raises(AttributeError):
            p.symbol = 'z'  # 尝试更改多项式对象的符号,预期引发 AttributeError 异常

    def test_change_symbol(self):
        p = poly.Polynomial(self.c, symbol='y')  # 创建多项式对象
        # Create new polynomial from p with different symbol
        pt = poly.Polynomial(p.coef, symbol='t')  # 使用不同符号创建新的多项式对象
        assert_equal(pt.symbol, 't')  # 断言新多项式对象的符号为 't'


class TestUnaryOperators:
    p = poly.Polynomial([1, 2, 3], symbol='z')  # 创建带有符号 'z' 的多项式对象

    def test_neg(self):
        n = -self.p  # 对多项式取负
        assert_equal(n.symbol, 'z')  # 断言结果多项式的符号保持为 'z'

    def test_scalarmul(self):
        out = self.p * 10  # 多项式与标量相乘
        assert_equal(out.symbol, 'z')  # 断言结果多项式的符号保持为 'z'

    def test_rscalarmul(self):
        out = 10 * self.p  # 标量与多项式相乘
        assert_equal(out.symbol, 'z')  # 断言结果多项式的符号保持为 'z'

    def test_pow(self):
        out = self.p ** 3  # 多项式的幂运算
        assert_equal(out.symbol, 'z')  # 断言结果多项式的符号保持为 'z'


@pytest.mark.parametrize(
    'rhs',
    (
        poly.Polynomial([4, 5, 6], symbol='z'),  # 右操作数为符号为 'z' 的多项式对象
        array([4, 5, 6]),  # 右操作数为 numpy 数组
    ),
)
class TestBinaryOperatorsSameSymbol:
    """
    Ensure symbol is preserved for numeric operations on polynomials with
    the same symbol
    """
    p = poly.Polynomial([1, 2, 3], symbol='z')  # 创建带有符号 'z' 的多项式对象

    def test_add(self, rhs):
        out = self.p + rhs  # 多项式加法操作
        assert_equal(out.symbol, 'z')  # 断言结果多项式的符号保持为 'z'

    def test_sub(self, rhs):
        out = self.p - rhs  # 多项式减法操作
        assert_equal(out.symbol, 'z')  # 断言结果多项式的符号保持为 'z'

    def test_polymul(self, rhs):
        out = self.p * rhs  # 多项式乘法操作
        assert_equal(out.symbol, 'z')  # 断言结果多项式的符号保持为 'z'

    def test_divmod(self, rhs):
        for out in divmod(self.p, rhs):  # 多项式除法操作
            assert_equal(out.symbol, 'z')  # 断言结果多项式的符号保持为 'z'

    def test_radd(self, rhs):
        out = rhs + self.p  # 反向多项式加法操作
        assert_equal(out.symbol, 'z')  # 断言结果多项式的符号保持为 'z'

    def test_rsub(self, rhs):
        out = rhs - self.p  # 反向多项式减法操作
        assert_equal(out.symbol, 'z')  # 断言结果多项式的符号保持为 'z'

    def test_rmul(self, rhs):
        out = rhs * self.p  # 反向多项式乘法操作
        assert_equal(out.symbol, 'z')  # 断言结果多项式的符号保持为 'z'
    # 定义一个测试方法 test_rdivmod,该方法用于测试除法和取模操作
    def test_rdivmod(self, rhs):
        # 对于每一个 divmod(rhs, self.p) 的结果,执行断言操作
        for out in divmod(rhs, self.p):
            # 断言输出对象的符号属性为 'z'
            assert_equal(out.symbol, 'z')
class TestBinaryOperatorsDifferentSymbol:
    # 创建一个多项式对象 p,使用 'x' 作为符号,系数为 [1, 2, 3]
    p = poly.Polynomial([1, 2, 3], symbol='x')
    # 创建另一个多项式对象 other,使用 'y' 作为符号,系数为 [4, 5, 6]
    other = poly.Polynomial([4, 5, 6], symbol='y')
    # 定义包含 p 不同二元操作方法的元组 ops
    ops = (p.__add__, p.__sub__, p.__mul__, p.__floordiv__, p.__mod__)

    @pytest.mark.parametrize('f', ops)
    # 测试各个二元操作方法是否会引发 ValueError 异常
    def test_binops_fails(self, f):
        assert_raises(ValueError, f, self.other)


class TestEquality:
    # 创建一个多项式对象 p,使用 'x' 作为符号,系数为 [1, 2, 3]
    p = poly.Polynomial([1, 2, 3], symbol='x')

    def test_eq(self):
        # 创建另一个与 p 相同的多项式对象 other,使用 'x' 作为符号,系数为 [1, 2, 3]
        other = poly.Polynomial([1, 2, 3], symbol='x')
        # 断言 p 与 other 相等
        assert_(self.p == other)

    def test_neq(self):
        # 创建另一个与 p 不同的多项式对象 other,使用 'y' 作为符号,系数为 [1, 2, 3]
        other = poly.Polynomial([1, 2, 3], symbol='y')
        # 断言 p 与 other 不相等
        assert_(not self.p == other)


class TestExtraMethods:
    """
    Test other methods for manipulating/creating polynomial objects.
    """
    # 创建一个多项式对象 p,使用 'z' 作为符号,系数为 [1, 2, 3, 0]
    p = poly.Polynomial([1, 2, 3, 0], symbol='z')

    def test_copy(self):
        # 复制当前多项式对象 p 得到 other
        other = self.p.copy()
        # 断言 other 的符号为 'z'
        assert_equal(other.symbol, 'z')

    def test_trim(self):
        # 对当前多项式对象 p 进行修剪操作得到 other
        other = self.p.trim()
        # 断言 other 的符号为 'z'
        assert_equal(other.symbol, 'z')

    def test_truncate(self):
        # 对当前多项式对象 p 进行截断操作得到 other
        other = self.p.truncate(2)
        # 断言 other 的符号为 'z'
        assert_equal(other.symbol, 'z')

    @pytest.mark.parametrize('kwarg', (
        {'domain': [-10, 10]},
        {'window': [-10, 10]},
        {'kind': poly.Chebyshev},
    ))
    # 测试多项式对象 p 的转换方法,接受不同的关键字参数 kwarg
    def test_convert(self, kwarg):
        other = self.p.convert(**kwarg)
        # 断言 other 的符号为 'z'
        assert_equal(other.symbol, 'z')

    def test_integ(self):
        # 对当前多项式对象 p 进行积分操作得到 other
        other = self.p.integ()
        # 断言 other 的符号为 'z'
        assert_equal(other.symbol, 'z')

    def test_deriv(self):
        # 对当前多项式对象 p 进行求导操作得到 other
        other = self.p.deriv()
        # 断言 other 的符号为 'z'
        assert_equal(other.symbol, 'z')


def test_composition():
    # 创建一个多项式对象 p,使用 "t" 作为符号,系数为 [3, 2, 1]
    p = poly.Polynomial([3, 2, 1], symbol="t")
    # 创建一个多项式对象 q,使用 "λ_1" 作为符号,系数为 [5, 1, 0, -1]
    q = poly.Polynomial([5, 1, 0, -1], symbol="λ_1")
    # 对多项式对象 p 和 q 进行组合操作得到 r
    r = p(q)
    # 断言 r 的符号为 "λ_1"
    assert r.symbol == "λ_1"


#
# Class methods that result in new polynomial class instances
#


def test_fit():
    # 创建一个多项式对象 p,使用 'z' 作为符号,通过拟合得到
    x, y = (range(10),)*2
    p = poly.Polynomial.fit(x, y, deg=1, symbol='z')
    # 断言 p 的符号为 'z'
    assert_equal(p.symbol, 'z')


def test_froomroots():
    # 从给定的根列表创建一个多项式对象 p,使用 'z' 作为符号
    roots = [-2, 2]
    p = poly.Polynomial.fromroots(roots, symbol='z')
    # 断言 p 的符号为 'z'
    assert_equal(p.symbol, 'z')


def test_identity():
    # 创建一个恒等多项式对象 p,使用 'z' 作为符号,指定定义域和窗口
    p = poly.Polynomial.identity(domain=[-1, 1], window=[5, 20], symbol='z')
    # 断言 p 的符号为 'z'
    assert_equal(p.symbol, 'z')


def test_basis():
    # 创建一个多项式对象 p,使用 'z' 作为符号,表示基函数
    p = poly.Polynomial.basis(3, symbol='z')
    # 断言 p 的符号为 'z'
    assert_equal(p.symbol, 'z')

.\numpy\numpy\polynomial\tests\__init__.py

# 导入Python内置的json模块,用于处理JSON格式数据
import json

# 定义一个名为process_data的函数,接收一个名为data的参数
def process_data(data):
    # 将传入的数据参数转换为JSON格式的字符串,并存储在变量json_data中
    json_data = json.dumps(data)
    # 将JSON格式的字符串json_data解析为Python的数据结构(通常是字典或列表),并存储在变量parsed_data中
    parsed_data = json.loads(json_data)
    # 返回解析后的数据结构parsed_data
    return parsed_data

.\numpy\numpy\polynomial\_polybase.py

"""
Abstract base class for the various polynomial Classes.

The ABCPolyBase class provides the methods needed to implement the common API
for the various polynomial classes. It operates as a mixin, but uses the
abc module from the stdlib, hence it is only available for Python >= 2.6.

"""
import os  # 导入标准库中的 os 模块
import abc  # 导入标准库中的 abc 模块
import numbers  # 导入标准库中的 numbers 模块
from typing import Callable  # 从 typing 模块中导入 Callable 类型

import numpy as np  # 导入 NumPy 库,并使用 np 别名
from . import polyutils as pu  # 从当前包中导入 polyutils 模块,并使用 pu 别名

__all__ = ['ABCPolyBase']  # 定义当前模块中导出的符号列表

class ABCPolyBase(abc.ABC):
    """An abstract base class for immutable series classes.

    ABCPolyBase provides the standard Python numerical methods
    '+', '-', '*', '//', '%', 'divmod', '**', and '()' along with the
    methods listed below.

    .. versionadded:: 1.9.0

    Parameters
    ----------
    coef : array_like
        Series coefficients in order of increasing degree, i.e.,
        ``(1, 2, 3)`` gives ``1*P_0(x) + 2*P_1(x) + 3*P_2(x)``, where
        ``P_i`` is the basis polynomials of degree ``i``.
    domain : (2,) array_like, optional
        Domain to use. The interval ``[domain[0], domain[1]]`` is mapped
        to the interval ``[window[0], window[1]]`` by shifting and scaling.
        The default value is the derived class domain.
    window : (2,) array_like, optional
        Window, see domain for its use. The default value is the
        derived class window.
    symbol : str, optional
        Symbol used to represent the independent variable in string 
        representations of the polynomial expression, e.g. for printing.
        The symbol must be a valid Python identifier. Default value is 'x'.

        .. versionadded:: 1.24

    Attributes
    ----------
    coef : (N,) ndarray
        Series coefficients in order of increasing degree.
    domain : (2,) ndarray
        Domain that is mapped to window.
    window : (2,) ndarray
        Window that domain is mapped to.
    symbol : str
        Symbol representing the independent variable.

    Class Attributes
    ----------------
    maxpower : int
        Maximum power allowed, i.e., the largest number ``n`` such that
        ``p(x)**n`` is allowed. This is to limit runaway polynomial size.
    domain : (2,) ndarray
        Default domain of the class.
    window : (2,) ndarray
        Default window of the class.

    """

    # Not hashable
    __hash__ = None  # 禁用对象的哈希特性

    # Opt out of numpy ufuncs and Python ops with ndarray subclasses.
    __array_ufunc__ = None  # 禁用 ndarray 子类的 NumPy 和 Python 操作

    # Limit runaway size. T_n^m has degree n*m
    maxpower = 100  # 定义类属性 maxpower,限制多项式的最大次数

    # Unicode character mappings for improved __str__
    _superscript_mapping = str.maketrans({
        "0": "⁰",
        "1": "¹",
        "2": "²",
        "3": "³",
        "4": "⁴",
        "5": "⁵",
        "6": "⁶",
        "7": "⁷",
        "8": "⁸",
        "9": "⁹"
    })  # 定义将数字字符转换为上标 Unicode 字符的映射表

    _subscript_mapping = str.maketrans({
        "0": "₀",
        "1": "₁",
        "2": "₂",
        "3": "₃",
        "4": "₄",
        "5": "₅",
        "6": "₆",
        "7": "₇",
        "8": "₈",
        "9": "₉"
    })  # 定义将数字字符转换为下标 Unicode 字符的映射表
    # 某些字体不支持完整的 Unicode 字符范围,这对于包括 Windows shell/终端中常见的默认字体在内的一些字体来说是必需的,因此在 Windows 平台上默认只打印 ASCII 字符。
    _use_unicode = not os.name == 'nt'

    @property
    def symbol(self):
        # 返回属性 _symbol 的值
        return self._symbol

    @property
    @abc.abstractmethod
    def domain(self):
        # 抽象方法,子类需要实现,返回对象的 domain 属性

    @property
    @abc.abstractmethod
    def window(self):
        # 抽象方法,子类需要实现,返回对象的 window 属性

    @property
    @abc.abstractmethod
    def basis_name(self):
        # 抽象方法,子类需要实现,返回对象的 basis_name 属性

    @staticmethod
    @abc.abstractmethod
    def _add(c1, c2):
        # 抽象静态方法,子类需要实现,用于执行加法操作

    @staticmethod
    @abc.abstractmethod
    def _sub(c1, c2):
        # 抽象静态方法,子类需要实现,用于执行减法操作

    @staticmethod
    @abc.abstractmethod
    def _mul(c1, c2):
        # 抽象静态方法,子类需要实现,用于执行乘法操作

    @staticmethod
    @abc.abstractmethod
    def _div(c1, c2):
        # 抽象静态方法,子类需要实现,用于执行除法操作

    @staticmethod
    @abc.abstractmethod
    def _pow(c, pow, maxpower=None):
        # 抽象静态方法,子类需要实现,用于执行幂运算

    @staticmethod
    @abc.abstractmethod
    def _val(x, c):
        # 抽象静态方法,子类需要实现,用于计算特定值

    @staticmethod
    @abc.abstractmethod
    def _int(c, m, k, lbnd, scl):
        # 抽象静态方法,子类需要实现,用于计算积分

    @staticmethod
    @abc.abstractmethod
    def _der(c, m, scl):
        # 抽象静态方法,子类需要实现,用于计算导数

    @staticmethod
    @abc.abstractmethod
    def _fit(x, y, deg, rcond, full):
        # 抽象静态方法,子类需要实现,用于拟合数据

    @staticmethod
    @abc.abstractmethod
    def _line(off, scl):
        # 抽象静态方法,子类需要实现,用于创建线性对象

    @staticmethod
    @abc.abstractmethod
    def _roots(c):
        # 抽象静态方法,子类需要实现,用于计算根

    @staticmethod
    @abc.abstractmethod
    def _fromroots(r):
        # 抽象静态方法,子类需要实现,用于根据给定的根创建对象

    def has_samecoef(self, other):
        """Check if coefficients match.

        .. versionadded:: 1.6.0

        Parameters
        ----------
        other : class instance
            The other class must have the ``coef`` attribute.

        Returns
        -------
        bool : boolean
            True if the coefficients are the same, False otherwise.

        """
        # 检查两个对象的 coef 属性长度是否相等,如果不相等返回 False;否则比较它们的值是否完全相同,相同则返回 True,否则返回 False
        if len(self.coef) != len(other.coef):
            return False
        elif not np.all(self.coef == other.coef):
            return False
        else:
            return True

    def has_samedomain(self, other):
        """Check if domains match.

        .. versionadded:: 1.6.0

        Parameters
        ----------
        other : class instance
            The other class must have the ``domain`` attribute.

        Returns
        -------
        bool : boolean
            True if the domains are the same, False otherwise.

        """
        # 检查两个对象的 domain 属性是否完全相同,使用 NumPy 的 all 函数比较
        return np.all(self.domain == other.domain)

    def has_samewindow(self, other):
        """Check if windows match.

        .. versionadded:: 1.6.0

        Parameters
        ----------
        other : class instance
            The other class must have the ``window`` attribute.

        Returns
        -------
        bool : boolean
            True if the windows are the same, False otherwise.

        """
        # 检查两个对象的 window 属性是否完全相同,使用 NumPy 的 all 函数比较
        return np.all(self.window == other.window)
    def has_sametype(self, other):
        """
        Check if types match.

        .. versionadded:: 1.7.0

        Parameters
        ----------
        other : object
            Class instance.

        Returns
        -------
        bool : boolean
            True if `other` is of the same class as `self`.

        """
        return isinstance(other, self.__class__)

    def _get_coefficients(self, other):
        """
        Interpret `other` as polynomial coefficients.

        The `other` argument is checked to see if it is of the same
        class as `self` with identical domain and window. If so,
        return its coefficients, otherwise return `other`.

        .. versionadded:: 1.9.0

        Parameters
        ----------
        other : anything
            Object to be checked.

        Returns
        -------
        coef
            The coefficients of `other` if it is a compatible instance
            of ABCPolyBase, otherwise `other`.

        Raises
        ------
        TypeError
            When `other` is an incompatible instance of ABCPolyBase.

        """
        if isinstance(other, ABCPolyBase):
            if not isinstance(other, self.__class__):
                raise TypeError("Polynomial types differ")
            elif not np.all(self.domain == other.domain):
                raise TypeError("Domains differ")
            elif not np.all(self.window == other.window):
                raise TypeError("Windows differ")
            elif self.symbol != other.symbol:
                raise ValueError("Polynomial symbols differ")
            return other.coef
        return other

    def __init__(self, coef, domain=None, window=None, symbol='x'):
        """
        Initialize a polynomial object with coefficients, domain, window, and symbol.

        Parameters
        ----------
        coef : array_like
            Coefficients of the polynomial.
        domain : array_like or None, optional
            Domain of the polynomial.
        window : array_like or None, optional
            Window of the polynomial.
        symbol : str, optional
            Symbol representing the polynomial variable.

        Raises
        ------
        ValueError
            If domain or window has incorrect number of elements,
            or if symbol is not a valid Python identifier.
        TypeError
            If symbol is not a string.

        """
        [coef] = pu.as_series([coef], trim=False)
        self.coef = coef

        if domain is not None:
            [domain] = pu.as_series([domain], trim=False)
            if len(domain) != 2:
                raise ValueError("Domain has wrong number of elements.")
            self.domain = domain

        if window is not None:
            [window] = pu.as_series([window], trim=False)
            if len(window) != 2:
                raise ValueError("Window has wrong number of elements.")
            self.window = window

        # Validation for symbol
        try:
            if not symbol.isidentifier():
                raise ValueError(
                    "Symbol string must be a valid Python identifier"
                )
        except AttributeError:
            raise TypeError("Symbol must be a non-empty string")

        self._symbol = symbol
    # 定义对象的字符串表示形式,返回一个描述对象的字符串
    def __repr__(self):
        # 将系数转换为字符串表示,并去除开头和结尾的多余字符
        coef = repr(self.coef)[6:-1]
        # 将定义域转换为字符串表示,并去除开头和结尾的多余字符
        domain = repr(self.domain)[6:-1]
        # 将窗口大小转换为字符串表示,并去除开头和结尾的多余字符
        window = repr(self.window)[6:-1]
        # 获取对象的类名
        name = self.__class__.__name__
        # 返回格式化后的字符串表示,包括类名、系数、定义域、窗口大小和符号
        return (f"{name}({coef}, domain={domain}, window={window}, "
                f"symbol='{self.symbol}')")

    # 格式化对象的表示形式,支持 'ascii' 和 'unicode' 两种格式
    def __format__(self, fmt_str):
        # 如果格式字符串为空,则返回对象的字符串表示
        if fmt_str == '':
            return self.__str__()
        # 如果格式字符串不是 'ascii' 或 'unicode',抛出值错误异常
        if fmt_str not in ('ascii', 'unicode'):
            raise ValueError(
                f"Unsupported format string '{fmt_str}' passed to "
                f"{self.__class__}.__format__. Valid options are "
                f"'ascii' and 'unicode'"
            )
        # 根据格式字符串调用相应的方法生成对应格式的字符串表示
        if fmt_str == 'ascii':
            return self._generate_string(self._str_term_ascii)
        return self._generate_string(self._str_term_unicode)

    # 返回对象的字符串表示,默认为 unicode 格式
    def __str__(self):
        # 如果使用 unicode 表示,则生成 unicode 格式的字符串表示
        if self._use_unicode:
            return self._generate_string(self._str_term_unicode)
        # 否则生成 ascii 格式的字符串表示
        return self._generate_string(self._str_term_ascii)

    # 根据给定的方法生成多项式的完整字符串表示
    def _generate_string(self, term_method):
        """
        Generate the full string representation of the polynomial, using
        ``term_method`` to generate each polynomial term.
        """
        # 获取打印选项中的行宽设置
        linewidth = np.get_printoptions().get('linewidth', 75)
        # 如果行宽小于 1,则将其设置为 1
        if linewidth < 1:
            linewidth = 1
        # 初始化输出字符串,将第一个系数转换为字符串后添加到输出中
        out = pu.format_float(self.coef[0])

        # 获取映射参数的偏移量和比例
        off, scale = self.mapparms()

        # 根据给定的方法和参数格式化项,获取缩放后的符号和是否需要括号
        scaled_symbol, needs_parens = self._format_term(pu.format_float,
                                                        off, scale)
        # 如果需要括号,则在符号周围添加括号
        if needs_parens:
            scaled_symbol = '(' + scaled_symbol + ')'

        # 遍历多项式的每个系数和幂次
        for i, coef in enumerate(self.coef[1:]):
            out += " "
            power = str(i + 1)
            # 处理多项式系数,如果系数为正则添加 '+',否则添加 '-'
            try:
                if coef >= 0:
                    next_term = "+ " + pu.format_float(coef, parens=True)
                else:
                    next_term = "- " + pu.format_float(-coef, parens=True)
            except TypeError:
                next_term = f"+ {coef}"
            # 生成多项式的每一项,并使用给定方法生成术语
            next_term += term_method(power, scaled_symbol)
            # 计算添加下一项后当前行的长度
            line_len = len(out.split('\n')[-1]) + len(next_term)
            # 如果不是多项式的最后一项,则由于符号的存在,长度增加 2
            if i < len(self.coef[1:]) - 1:
                line_len += 2
            # 处理行长度超过设定的情况,进行换行处理
            if line_len >= linewidth:
                next_term = next_term.replace(" ", "\n", 1)
            out += next_term
        # 返回生成的多项式字符串表示
        return out
    def _str_term_unicode(cls, i, arg_str):
        """
        使用 Unicode 字符表示单个多项式项的字符串形式,包括上标和下标。
        """
        if cls.basis_name is None:
            raise NotImplementedError(
                "Subclasses must define either a basis_name, or override "
                "_str_term_unicode(cls, i, arg_str)"
            )
        返回格式化的多项式项字符串,包括基函数名称和下标的 Unicode 表示
        return (f"·{cls.basis_name}{i.translate(cls._subscript_mapping)}"
                f"({arg_str})")

    @classmethod
    def _str_term_ascii(cls, i, arg_str):
        """
        使用 ** 和 _ 表示上标和下标,生成单个多项式项的 ASCII 字符串表示。
        """
        if cls.basis_name is None:
            raise NotImplementedError(
                "Subclasses must define either a basis_name, or override "
                "_str_term_ascii(cls, i, arg_str)"
            )
        返回格式化的多项式项字符串,包括基函数名称和下标的 ASCII 表示
        return f" {cls.basis_name}_{i}({arg_str})"

    @classmethod
    def _repr_latex_term(cls, i, arg_str, needs_parens):
        """
        生成单个多项式项的 LaTeX 字符串表示。
        """
        if cls.basis_name is None:
            raise NotImplementedError(
                "Subclasses must define either a basis name, or override "
                "_repr_latex_term(i, arg_str, needs_parens)")
        # 因为我们总是添加括号,所以不需要关心表达式是否需要括号
        return f"{{{cls.basis_name}}}_{{{i}}}({arg_str})"

    @staticmethod
    def _repr_latex_scalar(x, parens=False):
        """
        生成 LaTeX 表示的标量值。
        TODO: 在这个函数处理指数之前,我们禁用数学格式化。
        """
        return r'\text{{{}}}'.format(pu.format_float(x, parens=parens))

    def _format_term(self, scalar_format: Callable, off: float, scale: float):
        """
        格式化展开中的单个项。
        """
        if off == 0 and scale == 1:
            term = self.symbol
            needs_parens = False
        elif scale == 1:
            term = f"{scalar_format(off)} + {self.symbol}"
            needs_parens = True
        elif off == 0:
            term = f"{scalar_format(scale)}{self.symbol}"
            needs_parens = True
        else:
            term = (
                f"{scalar_format(off)} + "
                f"{scalar_format(scale)}{self.symbol}"
            )
            needs_parens = True
        return term, needs_parens
    # 定义用于生成 LaTeX 表示的方法
    def _repr_latex_(self):
        # 获取基函数的偏移和缩放参数
        off, scale = self.mapparms()
        # 格式化表示基函数的项
        term, needs_parens = self._format_term(self._repr_latex_scalar,
                                               off, scale)

        # 静音模式,将文本用浅灰色显示
        mute = r"\color{{LightGray}}{{{}}}".format

        parts = []
        # 遍历系数列表
        for i, c in enumerate(self.coef):
            # 防止+和-符号重复出现
            if i == 0:
                coef_str = f"{self._repr_latex_scalar(c)}"
            elif not isinstance(c, numbers.Real):
                coef_str = f" + ({self._repr_latex_scalar(c)})"
            elif c >= 0:
                coef_str = f" + {self._repr_latex_scalar(c, parens=True)}"
            else:
                coef_str = f" - {self._repr_latex_scalar(-c, parens=True)}"

            # 生成项的字符串表示
            term_str = self._repr_latex_term(i, term, needs_parens)
            if term_str == '1':
                part = coef_str
            else:
                part = rf"{coef_str}\,{term_str}"

            # 如果系数为0,则使用静音模式
            if c == 0:
                part = mute(part)

            parts.append(part)

        # 如果存在部件,则将它们连接成字符串
        if parts:
            body = ''.join(parts)
        else:
            # 如果系数全为0,则返回'0'
            body = '0'

        # 返回 LaTeX 格式的表达式
        return rf"${self.symbol} \mapsto {body}$"



    # Pickle 和 copy

    def __getstate__(self):
        # 复制对象的字典表示
        ret = self.__dict__.copy()
        # 复制系数列表
        ret['coef'] = self.coef.copy()
        # 复制定义域
        ret['domain'] = self.domain.copy()
        # 复制窗口
        ret['window'] = self.window.copy()
        # 复制符号
        ret['symbol'] = self.symbol
        return ret

    def __setstate__(self, dict):
        # 恢复对象状态
        self.__dict__ = dict

    # 调用对象

    def __call__(self, arg):
        # 将参数映射到定义域和窗口
        arg = pu.mapdomain(arg, self.domain, self.window)
        # 计算对象在参数处的值
        return self._val(arg, self.coef)

    def __iter__(self):
        # 返回系数列表的迭代器
        return iter(self.coef)

    def __len__(self):
        # 返回系数列表的长度
        return len(self.coef)

    # 数值属性

    def __neg__(self):
        # 返回对象的负值
        return self.__class__(
            -self.coef, self.domain, self.window, self.symbol
        )

    def __pos__(self):
        # 返回对象本身
        return self

    def __add__(self, other):
        # 获取另一个对象的系数
        othercoef = self._get_coefficients(other)
        try:
            # 尝试执行加法操作
            coef = self._add(self.coef, othercoef)
        except Exception:
            # 如果出现异常,则返回NotImplemented
            return NotImplemented
        # 返回新对象,带有相加后的系数
        return self.__class__(coef, self.domain, self.window, self.symbol)

    def __sub__(self, other):
        # 获取另一个对象的系数
        othercoef = self._get_coefficients(other)
        try:
            # 尝试执行减法操作
            coef = self._sub(self.coef, othercoef)
        except Exception:
            # 如果出现异常,则返回NotImplemented
            return NotImplemented
        # 返回新对象,带有相减后的系数
        return self.__class__(coef, self.domain, self.window, self.symbol)

    def __mul__(self, other):
        # 获取另一个对象的系数
        othercoef = self._get_coefficients(other)
        try:
            # 尝试执行乘法操作
            coef = self._mul(self.coef, othercoef)
        except Exception:
            # 如果出现异常,则返回NotImplemented
            return NotImplemented
        # 返回新对象,带有相乘后的系数
        return self.__class__(coef, self.domain, self.window, self.symbol)
    # 实现真除法的特殊方法,处理除数不是数字或布尔类型的情况,抛出TypeError异常
    def __truediv__(self, other):
        if not isinstance(other, numbers.Number) or isinstance(other, bool):
            raise TypeError(
                f"unsupported types for true division: "
                f"'{type(self)}', '{type(other)}'"
            )
        # 调用整除的特殊方法处理
        return self.__floordiv__(other)

    # 实现整除的特殊方法,调用__divmod__方法获得结果
    def __floordiv__(self, other):
        res = self.__divmod__(other)
        if res is NotImplemented:
            return res
        return res[0]

    # 实现取模的特殊方法,调用__divmod__方法获得结果
    def __mod__(self, other):
        res = self.__divmod__(other)
        if res is NotImplemented:
            return res
        return res[1]

    # 实现divmod的特殊方法,进行多项式除法计算,处理ZeroDivisionError和其他异常
    def __divmod__(self, other):
        # 获取其他操作数的系数
        othercoef = self._get_coefficients(other)
        try:
            # 调用内部方法执行多项式除法
            quo, rem = self._div(self.coef, othercoef)
        except ZeroDivisionError:
            raise
        except Exception:
            return NotImplemented
        # 创建新的多项式实例表示商和余数
        quo = self.__class__(quo, self.domain, self.window, self.symbol)
        rem = self.__class__(rem, self.domain, self.window, self.symbol)
        return quo, rem

    # 实现幂运算的特殊方法,调用内部方法计算多项式的幂
    def __pow__(self, other):
        coef = self._pow(self.coef, other, maxpower=self.maxpower)
        res = self.__class__(coef, self.domain, self.window, self.symbol)
        return res

    # 实现右加法的特殊方法,调用内部方法执行多项式加法
    def __radd__(self, other):
        try:
            coef = self._add(other, self.coef)
        except Exception:
            return NotImplemented
        return self.__class__(coef, self.domain, self.window, self.symbol)

    # 实现右减法的特殊方法,调用内部方法执行多项式减法
    def __rsub__(self, other):
        try:
            coef = self._sub(other, self.coef)
        except Exception:
            return NotImplemented
        return self.__class__(coef, self.domain, self.window, self.symbol)

    # 实现右乘法的特殊方法,调用内部方法执行多项式乘法
    def __rmul__(self, other):
        try:
            coef = self._mul(other, self.coef)
        except Exception:
            return NotImplemented
        return self.__class__(coef, self.domain, self.window, self.symbol)

    # 实现右真除法的特殊方法,委托给__rfloordiv__方法处理
    def __rdiv__(self, other):
        return self.__rfloordiv__(other)

    # 实现右真除法的特殊方法,返回NotImplemented表示不支持
    def __rtruediv__(self, other):
        return NotImplemented

    # 实现右整除的特殊方法,调用__rdivmod__方法获得结果
    def __rfloordiv__(self, other):
        res = self.__rdivmod__(other)
        if res is NotImplemented:
            return res
        return res[0]

    # 实现右取模的特殊方法,调用__rdivmod__方法获得结果
    def __rmod__(self, other):
        res = self.__rdivmod__(other)
        if res is NotImplemented:
            return res
        return res[1]
    def __rdivmod__(self, other):
        try:
            # 调用自定义的 _div 方法进行除法运算
            quo, rem = self._div(other, self.coef)
        except ZeroDivisionError:
            # 如果除数为零,则抛出 ZeroDivisionError 异常
            raise
        except Exception:
            # 捕获所有其他异常,返回 NotImplemented 表示不支持该操作
            return NotImplemented
        # 根据结果创建新的实例并返回
        quo = self.__class__(quo, self.domain, self.window, self.symbol)
        rem = self.__class__(rem, self.domain, self.window, self.symbol)
        return quo, rem

    def __eq__(self, other):
        # 检查是否与另一个对象相等的方法
        res = (isinstance(other, self.__class__) and  # 检查类型是否相同
               np.all(self.domain == other.domain) and  # 比较 domain 属性是否相等
               np.all(self.window == other.window) and  # 比较 window 属性是否相等
               (self.coef.shape == other.coef.shape) and  # 比较 coef 的形状是否相等
               np.all(self.coef == other.coef) and  # 比较 coef 的值是否相等
               (self.symbol == other.symbol))  # 比较 symbol 属性是否相等
        return res

    def __ne__(self, other):
        # 检查是否与另一个对象不相等的方法,通过调用 __eq__ 方法的结果取反得到
        return not self.__eq__(other)

    #
    # Extra methods.
    #

    def copy(self):
        """Return a copy.

        Returns
        -------
        new_series : series
            Copy of self.

        """
        # 返回当前对象的一个副本
        return self.__class__(self.coef, self.domain, self.window, self.symbol)

    def degree(self):
        """The degree of the series.

        .. versionadded:: 1.5.0

        Returns
        -------
        degree : int
            Degree of the series, one less than the number of coefficients.

        Examples
        --------

        Create a polynomial object for ``1 + 7*x + 4*x**2``:

        >>> poly = np.polynomial.Polynomial([1, 7, 4])
        >>> print(poly)
        1.0 + 7.0·x + 4.0·x²
        >>> poly.degree()
        2

        Note that this method does not check for non-zero coefficients.
        You must trim the polynomial to remove any trailing zeroes:

        >>> poly = np.polynomial.Polynomial([1, 7, 0])
        >>> print(poly)
        1.0 + 7.0·x + 0.0·x²
        >>> poly.degree()
        2
        >>> poly.trim().degree()
        1

        """
        # 返回当前系列的阶数,即系数数量减一
        return len(self) - 1

    def cutdeg(self, deg):
        """Truncate series to the given degree.

        Reduce the degree of the series to `deg` by discarding the
        high order terms. If `deg` is greater than the current degree a
        copy of the current series is returned. This can be useful in least
        squares where the coefficients of the high degree terms may be very
        small.

        .. versionadded:: 1.5.0

        Parameters
        ----------
        deg : non-negative int
            The series is reduced to degree `deg` by discarding the high
            order terms. The value of `deg` must be a non-negative integer.

        Returns
        -------
        new_series : series
            New instance of series with reduced degree.

        """
        # 调用 truncate 方法将当前系列截断至给定的阶数 deg+1
        return self.truncate(deg + 1)
    # 修剪级数,移除尾部系数直到找到一个绝对值大于 `tol` 的系数或者到达系列的开头
    # 如果所有系数都被移除,则将系列设置为 `[0]`。返回一个新的系列实例,保持当前实例不变。
    def trim(self, tol=0):
        """Remove trailing coefficients

        Remove trailing coefficients until a coefficient is reached whose
        absolute value greater than `tol` or the beginning of the series is
        reached. If all the coefficients would be removed the series is set
        to ``[0]``. A new series instance is returned with the new
        coefficients.  The current instance remains unchanged.

        Parameters
        ----------
        tol : non-negative number.
            All trailing coefficients less than `tol` will be removed.

        Returns
        -------
        new_series : series
            New instance of series with trimmed coefficients.

        """
        # 调用外部函数 pu.trimcoef() 对当前系列的系数进行修剪
        coef = pu.trimcoef(self.coef, tol)
        # 返回一个新的系列实例,使用修剪后的系数以及当前实例的其它属性
        return self.__class__(coef, self.domain, self.window, self.symbol)

    # 将系列截断至指定长度 `size`
    def truncate(self, size):
        """Truncate series to length `size`.

        Reduce the series to length `size` by discarding the high
        degree terms. The value of `size` must be a positive integer. This
        can be useful in least squares where the coefficients of the
        high degree terms may be very small.

        Parameters
        ----------
        size : positive int
            The series is reduced to length `size` by discarding the high
            degree terms. The value of `size` must be a positive integer.

        Returns
        -------
        new_series : series
            New instance of series with truncated coefficients.

        """
        # 将 size 转换为整数
        isize = int(size)
        # 如果转换后的大小与原始大小不同或者小于 1,则引发 ValueError
        if isize != size or isize < 1:
            raise ValueError("size must be a positive integer")
        # 如果要截断的长度大于等于当前系列长度,则保持系数不变
        if isize >= len(self.coef):
            coef = self.coef
        else:
            # 否则,截取前 isize 个系数
            coef = self.coef[:isize]
        # 返回一个新的系列实例,使用截断后的系数以及当前实例的其它属性
        return self.__class__(coef, self.domain, self.window, self.symbol)
    # 将系列转换为不同种类和/或域和/或窗口。

    # Parameters
    # ----------
    # domain : array_like, optional
    #     转换后系列的域。如果值为None,则使用`kind`的默认域。
    # kind : class, optional
    #     要转换为的多项式系列类型类。如果kind为None,则使用当前实例的类。
    # window : array_like, optional
    #     转换后系列的窗口。如果值为None,则使用`kind`的默认窗口。

    # Returns
    # -------
    # new_series : series
    #     返回的类可以与当前实例的类型不同,也可以具有不同的域和/或不同的窗口。

    # Notes
    # -----
    # 在域和类类型之间的转换可能导致数值上不稳定的系列。

    def convert(self, domain=None, kind=None, window=None):
        if kind is None:
            kind = self.__class__
        if domain is None:
            domain = kind.domain
        if window is None:
            window = kind.window
        return self(kind.identity(domain, window=window, symbol=self.symbol))

    # 返回映射参数。

    # 返回的值定义了应用于系列评估之前的输入参数的线性映射``off + scl*x``。
    # 映射取决于``domain``和``window``;如果当前``domain``等于``window``,则结果映射为恒等映射。
    # 如果系列实例的系数在类外部独立使用,则必须将线性函数替换为标准基多项式表示中的``x``。

    # Returns
    # -------
    # off, scl : float or complex
    #     映射函数由``off + scl*x``定义。

    # Notes
    # -----
    # 如果当前域是区间``[l1, r1]``,窗口是``[l2, r2]``,则线性映射函数``L``由以下方程定义:
    # 
    #     L(l1) = l2
    #     L(r1) = r2
    def mapparms(self):
        return pu.mapparms(self.domain, self.window)
    def integ(self, m=1, k=[], lbnd=None):
        """
        Integrate.

        Return a series instance that is the definite integral of the
        current series.

        Parameters
        ----------
        m : non-negative int
            The number of integrations to perform.
        k : array_like
            Integration constants. The first constant is applied to the
            first integration, the second to the second, and so on. The
            list of values must less than or equal to `m` in length and any
            missing values are set to zero.
        lbnd : Scalar
            The lower bound of the definite integral.

        Returns
        -------
        new_series : series
            A new series representing the integral. The domain is the same
            as the domain of the integrated series.
        """
        # Extract offset and scale parameters from the series
        off, scl = self.mapparms()

        # Set default lower bound for integration if not provided
        if lbnd is None:
            lbnd = 0
        else:
            lbnd = off + scl * lbnd  # Adjust lower bound based on series parameters

        # Perform the integration on the coefficient array
        coef = self._int(self.coef, m, k, lbnd, 1. / scl)

        # Return a new series instance representing the integral
        return self.__class__(coef, self.domain, self.window, self.symbol)


    def deriv(self, m=1):
        """
        Differentiate.

        Return a series instance that is the derivative of the current
        series.

        Parameters
        ----------
        m : non-negative int
            Find the derivative of order `m`.

        Returns
        -------
        new_series : series
            A new series representing the derivative. The domain is the same
            as the domain of the differentiated series.
        """
        # Extract offset and scale parameters from the series
        off, scl = self.mapparms()

        # Compute the derivative of the coefficient array
        coef = self._der(self.coef, m, scl)

        # Return a new series instance representing the derivative
        return self.__class__(coef, self.domain, self.window, self.symbol)


    def roots(self):
        """
        Return the roots of the series polynomial.

        Compute the roots for the series. Note that the accuracy of the
        roots decreases the further outside the `domain` they lie.

        Returns
        -------
        roots : ndarray
            Array containing the roots of the series.
        """
        # Compute the roots of the polynomial represented by the coefficient array
        roots = self._roots(self.coef)

        # Map the computed roots to the correct domain using mapdomain function
        return pu.mapdomain(roots, self.window, self.domain)
    def linspace(self, n=100, domain=None):
        """Return x, y values at equally spaced points in domain.

        Returns the x, y values at `n` linearly spaced points across the
        domain.  Here y is the value of the polynomial at the points x. By
        default the domain is the same as that of the series instance.
        This method is intended mostly as a plotting aid.

        .. versionadded:: 1.5.0

        Parameters
        ----------
        n : int, optional
            Number of point pairs to return. The default value is 100.
        domain : {None, array_like}, optional
            If not None, the specified domain is used instead of that of
            the calling instance. It should be of the form ``[beg,end]``.
            The default is None which case the class domain is used.

        Returns
        -------
        x, y : ndarray
            x is equal to linspace(self.domain[0], self.domain[1], n) and
            y is the series evaluated at element of x.

        """
        if domain is None:
            domain = self.domain  # 如果 domain 参数为 None,则使用当前实例的 domain 属性
        x = np.linspace(domain[0], domain[1], n)  # 生成一个在指定 domain 区间内的 n 个等间距点的数组
        y = self(x)  # 计算这些 x 点上多项式的值
        return x, y

    @classmethod
    @classmethod
    def fromroots(cls, roots, domain=[], window=None, symbol='x'):
        """Return series instance that has the specified roots.

        Returns a series representing the product
        ``(x - r[0])*(x - r[1])*...*(x - r[n-1])``, where ``r`` is a
        list of roots.

        Parameters
        ----------
        roots : array_like
            List of roots.
        domain : {[], None, array_like}, optional
            Domain for the resulting series. If None the domain is the
            interval from the smallest root to the largest. If [] the
            domain is the class domain. The default is [].
        window : {None, array_like}, optional
            Window for the returned series. If None the class window is
            used. The default is None.
        symbol : str, optional
            Symbol representing the independent variable. Default is 'x'.

        Returns
        -------
        new_series : series
            Series with the specified roots.

        """
        [roots] = pu.as_series([roots], trim=False)  # 将输入的 roots 转换为 series 格式
        if domain is None:
            domain = pu.getdomain(roots)  # 如果 domain 参数为 None,则根据 roots 计算 domain
        elif type(domain) is list and len(domain) == 0:
            domain = cls.domain  # 如果 domain 是空列表,则使用类的 domain 属性

        if window is None:
            window = cls.window  # 如果 window 参数为 None,则使用类的 window 属性

        deg = len(roots)  # 计算 roots 的个数
        off, scl = pu.mapparms(domain, window)  # 计算 domain 和 window 的映射参数
        rnew = off + scl * roots  # 对 roots 进行线性映射
        coef = cls._fromroots(rnew) / scl**deg  # 计算系数
        return cls(coef, domain=domain, window=window, symbol=symbol)  # 返回新的 series 实例
    @classmethod
    def identity(cls, domain=None, window=None, symbol='x'):
        """Identity function.

        If ``p`` is the returned series, then ``p(x) == x`` for all
        values of x.

        Parameters
        ----------
        domain : {None, array_like}, optional
            If given, the array must be of the form ``[beg, end]``, where
            ``beg`` and ``end`` are the endpoints of the domain. If None is
            given then the class domain is used. The default is None.
        window : {None, array_like}, optional
            If given, the resulting array must be if the form
            ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
            the window. If None is given then the class window is used. The
            default is None.
        symbol : str, optional
            Symbol representing the independent variable. Default is 'x'.

        Returns
        -------
        new_series : series
             Series of representing the identity.

        """
        # 如果未指定 domain,则使用类属性中的 domain
        if domain is None:
            domain = cls.domain
        # 如果未指定 window,则使用类属性中的 window
        if window is None:
            window = cls.window
        # 根据给定的 window 和 domain 计算偏移量和缩放因子
        off, scl = pu.mapparms(window, domain)
        # 使用计算得到的偏移量和缩放因子生成系数
        coef = cls._line(off, scl)
        # 返回一个新的系列对象,表示恒等函数
        return cls(coef, domain, window, symbol)

    @classmethod
    def basis(cls, deg, domain=None, window=None, symbol='x'):
        """Series basis polynomial of degree `deg`.

        Returns the series representing the basis polynomial of degree `deg`.

        .. versionadded:: 1.7.0

        Parameters
        ----------
        deg : int
            Degree of the basis polynomial for the series. Must be >= 0.
        domain : {None, array_like}, optional
            If given, the array must be of the form ``[beg, end]``, where
            ``beg`` and ``end`` are the endpoints of the domain. If None is
            given then the class domain is used. The default is None.
        window : {None, array_like}, optional
            If given, the resulting array must be if the form
            ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
            the window. If None is given then the class window is used. The
            default is None.
        symbol : str, optional
            Symbol representing the independent variable. Default is 'x'.

        Returns
        -------
        new_series : series
            A series with the coefficient of the `deg` term set to one and
            all others zero.

        """
        # 如果未指定 domain,则使用类属性中的 domain
        if domain is None:
            domain = cls.domain
        # 如果未指定 window,则使用类属性中的 window
        if window is None:
            window = cls.window
        # 将 deg 转换为整数类型
        ideg = int(deg)

        # 如果 ideg 不等于 deg 或者 ideg 小于 0,则抛出数值错误
        if ideg != deg or ideg < 0:
            raise ValueError("deg must be non-negative integer")
        # 返回一个新的系列对象,表示指定阶数的基础多项式
        return cls([0]*ideg + [1], domain, window, symbol)
    def cast(cls, series, domain=None, window=None):
        """Convert series to series of this class.

        The `series` is expected to be an instance of some polynomial
        series of one of the types supported by by the numpy.polynomial
        module, but could be some other class that supports the convert
        method.

        .. versionadded:: 1.7.0

        Parameters
        ----------
        series : series
            The series instance to be converted.
        domain : {None, array_like}, optional
            If given, the array must be of the form ``[beg, end]``, where
            ``beg`` and ``end`` are the endpoints of the domain. If None is
            given then the class domain is used. The default is None.
        window : {None, array_like}, optional
            If given, the resulting array must be if the form
            ``[beg, end]``, where ``beg`` and ``end`` are the endpoints of
            the window. If None is given then the class window is used. The
            default is None.

        Returns
        -------
        new_series : series
            A series of the same kind as the calling class and equal to
            `series` when evaluated.

        See Also
        --------
        convert : similar instance method

        """
        # 如果未提供特定的 domain,则使用类的默认 domain
        if domain is None:
            domain = cls.domain
        # 如果未提供特定的 window,则使用类的默认 window
        if window is None:
            window = cls.window
        # 调用 series 对象的 convert 方法,将其转换为当前类的实例
        return series.convert(domain, cls, window)

.\numpy\numpy\polynomial\_polybase.pyi

# 导入 abc 模块,用于定义抽象基类
import abc
# 导入 Any 和 ClassVar 类型提示
from typing import Any, ClassVar

# 定义模块级别变量 __all__,用于控制模块导出的内容
__all__: list[str]

# 定义抽象基类 ABCPolyBase,继承自 abc.ABC
class ABCPolyBase(abc.ABC):
    # 类变量 __hash__,标识为不可赋值类型,用于禁止赋值类型检查
    __hash__: ClassVar[None]  # type: ignore[assignment]
    # 类变量 __array_ufunc__
    __array_ufunc__: ClassVar[None]
    # 类变量 maxpower,表示最大的幂次
    maxpower: ClassVar[int]
    # 实例变量 coef,表示多项式的系数
    coef: Any

    # 属性方法 symbol,返回多项式的符号表示
    @property
    def symbol(self) -> str: ...

    # 抽象属性方法 domain,表示多项式的定义域
    @property
    @abc.abstractmethod
    def domain(self): ...

    # 抽象属性方法 window,表示多项式的窗口
    @property
    @abc.abstractmethod
    def window(self): ...

    # 抽象属性方法 basis_name,表示多项式的基函数名称
    @property
    @abc.abstractmethod
    def basis_name(self): ...

    # 实例方法 has_samecoef,用于比较两个多项式是否具有相同的系数
    def has_samecoef(self, other): ...

    # 实例方法 has_samedomain,用于比较两个多项式是否具有相同的定义域
    def has_samedomain(self, other): ...

    # 实例方法 has_samewindow,用于比较两个多项式是否具有相同的窗口
    def has_samewindow(self, other): ...

    # 实例方法 has_sametype,用于比较两个多项式是否具有相同的类型
    def has_sametype(self, other): ...

    # 初始化方法,接受系数 coef,可选参数 domain、window、symbol
    def __init__(self, coef, domain=..., window=..., symbol: str = ...) -> None: ...

    # 格式化方法,定义多项式的格式化输出方式
    def __format__(self, fmt_str): ...

    # 调用方法,使多项式实例能够像函数一样被调用
    def __call__(self, arg): ...

    # 迭代方法,使多项式实例能够被迭代
    def __iter__(self): ...

    # 返回多项式的长度,通常指其维度或长度
    def __len__(self): ...

    # 负号运算方法,定义多项式的负号运算
    def __neg__(self): ...

    # 正号运算方法,定义多项式的正号运算
    def __pos__(self): ...

    # 加法运算方法,定义多项式的加法运算
    def __add__(self, other): ...

    # 减法运算方法,定义多项式的减法运算
    def __sub__(self, other): ...

    # 乘法运算方法,定义多项式的乘法运算
    def __mul__(self, other): ...

    # 真除法运算方法,定义多项式的真除法运算
    def __truediv__(self, other): ...

    # 向下整除运算方法,定义多项式的向下整除运算
    def __floordiv__(self, other): ...

    # 取模运算方法,定义多项式的取模运算
    def __mod__(self, other): ...

    # 除法和取模运算的组合方法,定义多项式的除法和取模运算
    def __divmod__(self, other): ...

    # 幂运算方法,定义多项式的幂运算
    def __pow__(self, other): ...

    # 右加法运算方法,定义多项式的右加法运算
    def __radd__(self, other): ...

    # 右减法运算方法,定义多项式的右减法运算
    def __rsub__(self, other): ...

    # 右乘法运算方法,定义多项式的右乘法运算
    def __rmul__(self, other): ...

    # 右除法运算方法,定义多项式的右除法运算
    def __rdiv__(self, other): ...

    # 右真除法运算方法,定义多项式的右真除法运算
    def __rtruediv__(self, other): ...

    # 右向下整除运算方法,定义多项式的右向下整除运算
    def __rfloordiv__(self, other): ...

    # 右取模运算方法,定义多项式的右取模运算
    def __rmod__(self, other): ...

    # 右除法和取模运算的组合方法,定义多项式的右除法和取模运算
    def __rdivmod__(self, other): ...

    # 等于运算方法,定义多项式的等于比较运算
    def __eq__(self, other): ...

    # 不等于运算方法,定义多项式的不等于比较运算
    def __ne__(self, other): ...

    # 复制方法,返回多项式的副本
    def copy(self): ...

    # 返回多项式的次数(或阶数)
    def degree(self): ...

    # 截取多项式的次数,返回次数不超过给定值的多项式
    def cutdeg(self, deg): ...

    # 修剪多项式,移除系数绝对值小于给定容差的项
    def trim(self, tol=...): ...

    # 截断多项式,返回前定长的多项式
    def truncate(self, size): ...

    # 转换多项式的定义域、类型和窗口
    def convert(self, domain=..., kind=..., window=...): ...

    # 映射多项式的参数
    def mapparms(self): ...

    # 积分方法,计算多项式的积分
    def integ(self, m=..., k = ..., lbnd=...): ...

    # 导数方法,计算多项式的导数
    def deriv(self, m=...): ...

    # 计算多项式的根
    def roots(self): ...

    # 在给定域内生成多项式的线性间隔
    def linspace(self, n=..., domain=...): ...

    # 类方法,拟合方法,用于拟合多项式到给定数据
    @classmethod
    def fit(cls, x, y, deg, domain=..., rcond=..., full=..., w=..., window=...): ...

    # 类方法,根据根生成多项式
    @classmethod
    def fromroots(cls, roots, domain = ..., window=...): ...

    # 类方法,返回单位多项式
    @classmethod
    def identity(cls, domain=..., window=...): ...

    # 类方法,返回给定阶数的基函数多项式
    @classmethod
    def basis(cls, deg, domain=..., window=...): ...

    # 类方法,将序列转换为多项式
    @classmethod
    def cast(cls, series, domain=..., window=...): ...