[英]Correctly calculate the area beneath curve using trapz and simpson in python
I used np.trapz and scipy simps to calculate an area below a curve and noticed that I might not be doing it correctly. 我使用np.trapz和scipy simps来计算曲线下方的面积,并注意到我可能做得不正确。 As an example below
举例如下
import numpy as np
from scipy.integrate import simps
y = np.array([1,2,3,4,5])
y1= np.array([5,5,5,5,5])
print np.trapz(y,dx=1)
print simps(y,dx=1)
print np.trapz(y1,dx=1)
print simps(y1,dx=1)
These yield 这些产量
12.0
12.0
20.0
20.0
But shouldn't they yeild 15 and 25 respectively? 但是他们不应该分别获得15和25吗? It seems like it between to small limits?
好像介于两者之间?
You have implicitly that x = [0, 1, 2, 3, 4]
, remember that in programming almost everywhere and everything starts with 0
. 您已经隐式地认为
x = [0, 1, 2, 3, 4]
,请记住在几乎所有地方编程时,一切都从0
开始。 Also, usually, upper limits are not inclusive. 而且,通常上限不包括在内。
For y
that means a rectangle with vertices (0,0), (0,1), (4,0), and (4,1) plus a triangle with vertices (0,1), (4,5), and (4,1). 对于
y
,这意味着矩形的顶点为(0,0),(0,1),(4,0)和(4,1)以及三角形为顶点(0,1),(4,5)和(4,1)。 The rectangle has an area of 4*1=4 and the triangle 4*4/2=8 totaling an area of 12. 矩形的面积为4 * 1 = 4,三角形的面积为4 * 4/2 = 8,总面积为12。
For y1
you have a rectangle with vertices (0,0), (0,5), (4,0), and (4,5), thus giving you and area of 20. 对于
y1
您有一个矩形,其顶点为(0,0),(0,5),(4,0)和(4,5),因此面积为20。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.