I'm trying to do the following exercise:
Define a recursive function inteDef that approximates the definite integral of a function f on the interval [a,b] using the composite trapezoidal rule. The function will take eps as a parameter, which marks the maximum length of the subintervals into which the interval [a,b] will be divided. Thus, if the length of [a,b] is less than or equal to eps, the function will return the area of the corresponding trapezoid. Otherwise, it will divide the interval [a,b] into two subintervals of the same length (half of the original interval) and it will recursively approximate the integral of both intervals and return their sum.
My solution attempt is:
def inteDef(f: Double => Double, x: Double, y: Double, eps: Double): Double = {
if (abs(y - x) <= eps)
(y - x) * (f(x) f(y)) / 2.0
else
inteDef(f, x, (y-x)/2.0, eps) inteDef(f, (y-x)/2.0, y, eps)
}
It works when eps is greater than or equal to abs(y - x), but gives a stack overflow error otherwise.
CodePudding user response:
(y - x) / 2.0
is not in the middle between x
and y
.
(x y) / 2.0
is.