使用SciPy在矩形网格上整合2D样本 [英] integrating 2D samples on a rectangular grid using SciPy

查看:52
本文介绍了使用SciPy在矩形网格上整合2D样本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SciPy有三种方法可以对样本进行一维积分(trapz,simps和romb),而一种方法可以对函数进行二维积分(dblquad),但似乎没有方法可以进行二维积分.样本过多-甚至是矩形网格上的样本.

SciPy has three methods for doing 1D integrals over samples (trapz, simps, and romb) and one way to do a 2D integral over a function (dblquad), but it doesn't seem to have methods for doing a 2D integral over samples -- even ones on a rectangular grid.

我看到的最接近的东西是scipy.interpolate.RectBivariateSpline.integral-您可以根据矩形网格上的数据创建RectBivariateSpline,然后将其集成.但是,这并不是很快.

The closest thing I see is scipy.interpolate.RectBivariateSpline.integral -- you can create a RectBivariateSpline from data on a rectangular grid and then integrate it. However, that isn't terribly fast.

我想要比矩形方法更准确的东西(即,将所有内容加起来).我可以说,使用2D Simpson规则,制作一个具有正确权重的数组,然后将其乘以我要积分的数组,然后对结果求和.

I want something more accurate than the rectangle method (i.e. just summing everything up). I could, say, use a 2D Simpson's rule by making an array with the correct weights, multiplying that by the array I want to integrate, and then summing up the result.

但是,如果已经有了更好的东西,我不想重新发明轮子.有吗?

However, I don't want to reinvent the wheel if there's already something better out there. Is there?

推荐答案

使用两次1D规则.

>>> from scipy.integrate import simps
>>> import numpy as np
>>> x = np.linspace(0, 1, 20)
>>> y = np.linspace(0, 1, 30)
>>> z = np.cos(x[:,None])**4 + np.sin(y)**2
>>> simps(simps(z, y), x)
0.85134099743259539
>>> import sympy
>>> xx, yy = sympy.symbols('x y')
>>> sympy.integrate(sympy.cos(xx)**4 + sympy.sin(yy)**2, (xx, 0, 1), (yy, 0, 1)).evalf()
0.851349922021627

这篇关于使用SciPy在矩形网格上整合2D样本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆