在 R 中硬编码双 Reimann 和

问题描述

我正在尝试在 R 中为函数 f(x,y) = x^5 * y^2 编码一个双 Reimann 和,其中 0

a <- 0 # lower bound for x
b <- 2 # upper bound for x
c <- 4 # lower bound for y
d <- 6 # upper bound for y
xsize <- (b-a)/1000 # step size in x-direction
ysize <- (d-c)/1000 # step size in y-direction
x <- seq(a + (xsize/2),b - (xsize/2),xsize)
y <- seq(c + (ysize/2),d - (ysize/2),ysize)

f <- x^5 * y^2

ans <- sum(f*xsize*ysize)
ans

解决方法

f <- outer(x,y,function(x,y) x^5 * y^2)
ans <- sum(f)*xsize*ysize
ans
#> [1] 540.4438

虽然显然在这种情况下您可以独立地计算 x 和 y 的总和,而不必计算外积。