3

我一直在尝试为双积分实现梯形规则。我尝试了很多方法,但我无法让它正常工作。

static double f(double x) {
    return Math.exp(- x * x / 2);
}

// trapezoid rule
static double trapezoid(double a, double b, int N) {
    double h = (b - a) / N;
    double sum = 0.5 *  h * (f(a) + f(b));
    for (int k = 1; k < N; k++)
        sum = sum + h * f(a + h*k);
    return sum;
}

我了解单变量积分的方法,但我不知道如何为 2D 积分做到这一点,例如:x + (y*y)。有人可以简要解释一下吗?

4

3 回答 3

3

如果您打算使用梯形规则,那么您可以这样做:

// The example function you provided.
public double f(double x, double y) {
    return x + y * y;
}

/**
 * Finds the volume under the surface described by the function f(x, y) for a <= x <= b, c <= y <= d.
 * Using xSegs number of segments across the x axis and ySegs number of segments across the y axis. 
 * @param a The lower bound of x.
 * @param b The upper bound of x.
 * @param c The lower bound of y.
 * @param d The upper bound of y.
 * @param xSegs The number of segments in the x axis.
 * @param ySegs The number of segments in the y axis.
 * @return The volume under f(x, y).
 */
public double trapezoidRule(double a, double b, double c, double d, int xSegs, int ySegs) {
    double xSegSize = (b - a) / xSegs; // length of an x segment.
    double ySegSize = (d - c) / ySegs; // length of a y segment.
    double volume = 0; // volume under the surface.

    for (int i = 0; i < xSegs; i++) {
        for (int j = 0; j < ySegs; j++) {
            double height = f(a + (xSegSize * i), c + (ySegSize * j));
            height += f(a + (xSegSize * (i + 1)), c + (ySegSize * j));
            height += f(a + (xSegSize * (i + 1)), c + (ySegSize * (j + 1)));
            height += f(a + (xSegSize * i), c + (ySegSize * (j + 1)));
            height /= 4;

            // height is the average value of the corners of the current segment.
            // We can use the average value since a box of this height has the same volume as the original segment shape.

            // Add the volume of the box to the volume.
            volume += xSegSize * ySegSize * height;
        }
    }

    return volume;
}

希望这可以帮助。随意询问您对我的代码可能有的任何问题(警告:代码未经测试)。

于 2012-04-12T16:14:08.797 回答
0

有很多方法可以做到。

如果您已经知道 1d 的内容,则可以这样:

  1. 编写一个函数 g(x),计算 f(x,y) 上的一维积分x
  2. 然后在 g(x) 上积分一维积分
  3. 成功 :)

这样,您基本上可以拥有任意数量的维度。虽然它的扩展性很差。对于较大的问题,可能需要使用monte carlo 积分

于 2012-04-12T08:51:35.157 回答
0

考虑使用DataMelt Java 程序jhplot.F2D中的类。您可以集成和可视化 2D 函数,执行以下操作:

f1=F2D("x*y",-1,1,-1,1) # define in a range
print f1.integral()
于 2015-08-04T01:27:13.780 回答