You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用for循环构造Vandermonde矩阵时出现数值计算错误求助

问题分析与解决方案

问题原因

你遇到的是整数溢出问题:

  • np.arange(2010, 2022) 默认生成的是 int32 类型数组(32位有符号整数的最大值为 2^31-1 = 2147483647)
  • 2010^3 = 8120601000 远大于这个最大值,导致int32类型的数值计算时溢出,出现负数结果
  • 单独在Python中计算2010**3时用的是Python原生的任意精度整数,所以不会溢出,结果正常

解决方案

方案1:显式指定矩阵的 dtype

创建vandermonde矩阵时,指定为64位浮点或整数类型,避免溢出:

import numpy as np

x = np.arange(2010, 2022, 1) 
y = np.array([143335, 141079, 136607, 132865, 129394, 125637, 122645, 121102, 116426, 110234, 97208, 96123])
# 指定dtype为float64或int64
vandermonde = np.zeros((12, 12), dtype=np.float64)
for i in range(12):
    for j in range(12):
        vandermonde[i,j] = x[i]**j
# 验证结果
print(vandermonde[0,3])  # 输出8120601000.0

方案2:转换x的类型为int64

把x转换成64位整数类型,计算时就不会溢出:

import numpy as np

x = np.arange(2010, 2022, 1, dtype=np.int64) 
y = np.array([143335, 141079, 136607, 132865, 129394, 125637, 122645, 121102, 116426, 110234, 97208, 96123])
vandermonde = np.zeros((12, 12))
for i in range(12):
    for j in range(12):
        vandermonde[i,j] = x[i]**j
print(vandermonde[0,3])  # 输出8120601000.0

方案3:使用numpy内置函数np.vander(推荐)

numpy已经提供了构造Vandermonde矩阵的函数,无需手动写循环,更高效且避免错误:

import numpy as np

x = np.arange(2010, 2022, 1)
# np.vander默认是列从高次到低次,设置increasing=True可以让列从0次到11次,和你的循环逻辑一致
vandermonde = np.vander(x, N=12, increasing=True)
print(vandermonde[0,3])  # 输出8120601000.0

内容的提问来源于stack exchange,提问作者Yoshihiro G Yagi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 01:05:21