【发布时间】:2017-12-01 03:42:07
【问题描述】:
我目前被一个隐藏在某个地方的非常简单的错误所困,希望有人能对此有所了解。
我正在尝试将一组数据与常规方法进行数值整合,并获得我不太期望的结果。
然后我回到第一原则并生成了以下代码。由于某种原因,我无法生成 y3 或 y4 来匹配 y2。
import numpy as np
import matplotlib.pyplot as plt
import math
f1 = 'x**2 - 1' # Starting function
start, stop, step = -2, 2, 21
x = np.linspace(start, stop, step)
xdash = []
xDoubleDash = []
y1 = eval(f1)
y2 = [] # integrated function
y3 = [] # box rule
y4 = [] # trapezium rule
y5 = [] # numerical differentialtion of integrated function
for i in range(0,len(x)-1):
xdashElement = (x[i] + x[i+1])/2
y2.append((math.pow(xdashElement,3)/3) - xdashElement) # Integrated Function: (x**3)/3 - x
xdash.append(xdashElement)
y3.append((y1[i]+y1[i+1])/2 * abs(((x[i] - x[i+1])))) # box rule
y4.append(((y1[i]+y1[i+1]) * abs(x[i] - x[i+1]))/2) # trapezium rule
for i in range(0,len(y2)-1):
xDoubleDashElement = (xdash[i] + xdash[i+1])/2
xDoubleDash.append(xDoubleDashElement)
y5.append((y2[i+1]-y2[i])/(xdash[i+1] - xdash[i]))
plt.plot(x, y1, 'b-')
plt.plot(xdash, y2, 'r-')
plt.plot(xdash, y3, 'g-')
plt.plot(xdash, y4, 'm-')
plt.plot(xDoubleDash, y5, 'c-')
plt.grid()
plt.show()
提前致谢。
编辑:我添加了 y5,y2 的数值微分作为健全性检查。
【问题讨论】:
-
你得到了什么结果,你期望什么,为什么你期望什么?
-
您的 y2 似乎不是与 y3 和 y4 相同起点的定积分。它看起来像是一个从 0 开始的定积分,或者一个 C 天真地设置为 0 的不定积分。
-
实际上,您的 y3 和 y4 甚至都不是定积分;它们是您在数值定积分中求和的各个位。
-
离题,但是:
f1 = 'x**2 - 1'; y1 = eval(f1)-- 请不要这样做。写个函数或者干脆写y1 = x**2 - 1 -
我添加了 y5,一个 y2 的数值微分作为健全性检查。我知道 y2 是 y1 的不定积分,y3 和 y4 都是沿该范围计算的定积分。我期望 y3 和 y4 的值与 y2 的值非常相似,并且根据积分的理论定义,如果增量 x[i+1] - x[i] 变得无限小,理论上会匹配
标签: python integration numerical-methods numerical-integration