2 条题解

  • 0
    @ 2026-3-26 17:44:19

    NUMPY047 题解:计算柯西矩阵

    题目

    给定两个数组 X 和 Y,构建柯西矩阵 C(Cij = 1/(xi - yj))。

    解题思路

    使用 np.subtract.outer() 计算外积形式的差值。

    代码

    import numpy as np
    X = np.arange(8)
    Y = X + 0.5
    C = 1.0 / np.subtract.outer(X, Y)
    print(np.linalg.det(C))
    

    代码详解

    柯西矩阵定义

    Cij=1xiyjC_{ij} = \frac{1}{x_i - y_j}

    np.subtract.outer

    X = [0, 1, 2]
    Y = [0.5, 1.5, 2.5]
    
    # outer 差值
    diff = np.subtract.outer(X, Y)
    # [[-0.5, -1.5, -2.5],
    #  [ 0.5, -0.5, -1.5],
    #  [ 1.5,  0.5, -0.5]]
    

    柯西矩阵

    C[i,j] = 1 / (X[i] - Y[j])
    
    C = [[-2.        , -0.66666667, -0.4       ],
         [ 2.        , -2.        , -0.66666667],
         [ 0.66666667,  2.        , -2.        ]]
    

    核心知识点

    1. np.subtract.outer() —— 外积减法
    2. 柯西矩阵 —— 特殊的数学矩阵
    3. np.linalg.det() —— 行列式
    • 0
      @ 2026-3-25 15:38:47

      NumPy047 题解

      参考代码

      import numpy as np
      import time
      n = int(input())
      t1 = time.perf_counter()
      A = np.random.rand(n, n)
      B = np.random.rand(n, n)
      C = np.matmul(A, B)
      t2 = time.perf_counter()
      print(f'{(t2-t1)*1000:.2f}')
      
      • 1

      信息

      ID
      98
      时间
      1000ms
      内存
      256MiB
      难度
      (无)
      标签
      (无)
      递交数
      0
      已通过
      0
      上传者