War*_*ser 57
numpy和scipy库包括复合梯形(numpy.trapz)和Simpson(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)
Run Code Online (Sandbox Code Playgroud)
输出:
area = 452.5
area = 460.0
Run Code Online (Sandbox Code Playgroud)
Wil*_*son 18
您可以使用" 辛普森一家"规则或" 梯形"规则来计算图表下的区域,该图表给定了一个定期间隔的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)
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
如果您错失了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)))
Run Code Online (Sandbox Code Playgroud)
两者输出的面积相同:4607.5
sklearn.metrics.auc的优点是它可以接受任意间隔的“ x”数组,只需确保它升序,否则结果将不正确
归档时间: |
|
查看次数: |
78513 次 |
最近记录: |