numpy.arange生成支持点时出现额外末尾值问题求助
问题描述
我正尝试实现一个计算已知函数样条插值的函数,第一步需生成数量动态的支持点。当设置间隔数n=15(对应16个支持点)时,numpy.arange返回了17个值,末尾出现预期外的5.66666667;但测试其他n值(如6、9、100)时,能得到预期的末尾值5。
代码如下:
import numpy as np # Parameter n = 15 x0 = -5 xend = 5 def f(x): # 原问题中未给出函数实现,此处用示例占位 return x**2 def xy_support(n,x0,xend) : x_support = np.arange(x0,xend+((xend-x0)/n),((xend-x0)/n)) y_support = f(x_support) return x_support,y_support x,y = xy_support(n,x0,xend) print(x) print(y)
输出x:
[-5. -4.33333333 -3.66666667 -3. -2.33333333 -1.66666667 -1. -0.33333333 0.33333333 1. 1.66666667 2.33333333 3. 3.66666667 4.33333333 5. 5.66666667]
问题原因
这是浮点数精度误差导致的问题:
- 当
n=15时,步长(xend-x0)/n = 10/15 = 2/3 ≈0.6666666666666666,属于无法用二进制浮点数精确表示的分数。 numpy.arange的逻辑是从起始值开始,不断累加步长,直到生成的数值小于终止值(你代码中终止值是xend + 步长 ≈5.666666666666667)。- 由于浮点数累加的精度偏差,第17个值
-5 + 16*(2/3) ≈5.666666666666666,这个值略小于终止值5.666666666666667,因此被错误地包含进去。 - 其他
n值(如6、9、100)的步长累加后,最后一个预期值5之后的下一个值刚好等于或超过终止值,因此不会出现多余元素。
解决方案
不要用np.arange生成指定数量的等距点,改用np.linspace——它直接指定要生成的点数,从起始值到终止值均匀分布,完全避免步长累加的精度问题:
修改后的代码:
import numpy as np # Parameter n = 15 x0 = -5 xend = 5 def f(x): return x**2 def xy_support(n,x0,xend) : # 生成n+1个从x0到xend的等距点(间隔数n对应n+1个支持点) x_support = np.linspace(x0, xend, num=n+1) y_support = f(x_support) return x_support,y_support x,y = xy_support(n,x0,xend) print(x) print(y)
输出x将准确得到16个点:
[-5. -4.33333333 -3.66666667 -3. -2.33333333 -1.66666667 -1. -0.33333333 0.33333333 1. 1.66666667 2.33333333 3. 3.66666667 4.33333333 5. ]
内容的提问来源于stack exchange,提问作者MarcNu
相关产品推荐
相关产品推荐

