[英]Calculating the area under a curve given a set of coordinates, without knowing the function
我有一个 100 个数字的列表作为 Y 轴的高度和 X 轴的长度:1 到 100,恒定步长为 5。我需要计算它包含在 (x,y) 曲线中的面积点和 X 轴,使用矩形和 Scipy。 我必须找到这条曲线的 function 吗? 或不? ...我读过的几乎所有示例都是关于 Y 轴的特定方程。 就我而言,没有方程式,只有列表中的数据。 经典的解决方案是按步长 X 距离添加或 Y 点和倍数...使用 Scipy 知道吗?
请,任何人都可以推荐任何专注于数值(有限基本)方法的书,使用 Scipy 和 Numpy? ...
numpy 和 scipy 库包括复合梯形 ( numpy.trapz ) 和辛普森 ( scipy.integrate.simps ) 规则。
这是一个简单的例子。 在trapz
和simps
,参数dx=5
表示数据沿 x 轴的间距为 5 个单位。
from __future__ import print_function
import numpy as np
from scipy.integrate import simps
from numpy import trapz
# The y values. A numpy array is used here,
# but a python list could also be used.
y = np.array([5, 20, 4, 18, 19, 18, 7, 4])
# Compute the area using the composite trapezoidal rule.
area = trapz(y, dx=5)
print("area =", area)
# Compute the area using the composite Simpson's rule.
area = simps(y, dx=5)
print("area =", area)
输出:
area = 452.5
area = 460.0
您可以使用Simpsons 规则或梯形规则来计算给定一个定期间隔 y 值表的图形下的面积。
计算辛普森一家规则的 Python 脚本:
def integrate(y_vals, h):
i = 1
total = y_vals[0] + y_vals[-1]
for y in y_vals[1:-1]:
if i % 2 == 0:
total += 2 * y
else:
total += 4 * y
i += 1
return total * (h / 3.0)
h
是 y 值之间的偏移量(或间隙),而y_vals
是一个很好的 y 值数组。
示例(在与上述函数相同的文件中):
y_values = [13, 45.3, 12, 1, 476, 0]
interval = 1.2
area = integrate(y_values, interval)
print("The area is", area)
如果您安装了 sklearn,一个简单的替代方法是使用 sklearn.metrics.auc
这使用给定任意 x 和 y 数组的梯形规则计算曲线下的面积
import numpy as np
from sklearn.metrics import auc
dx = 5
xx = np.arange(1,100,dx)
yy = np.arange(1,100,dx)
print('computed AUC using sklearn.metrics.auc: {}'.format(auc(xx,yy)))
print('computed AUC using np.trapz: {}'.format(np.trapz(yy, dx = dx)))
两者输出相同的区域:4607.5
sklearn.metrics.auc 的优点是它可以接受任意间隔的 'x' 数组,只要确保它是升序的,否则结果将不正确
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.