Skip to content
DeepForgeby svx
All problems
EasyCalculusca-003

Trapezoidal Integration

Problem

Approximate the definite integral using the trapezoidal rule given evenly-spaced samples.

f_samples is a list of y-values at x positions from x_start to x_end (inclusive).

integral ≈ (dx/2) * (f[0] + 2*f[1] + ... + 2*f[n-1] + f[n])

where dx = (x_end - x_start) / (len(f_samples) - 1).

Hint

First and last samples have weight 1/2, all interior samples have weight 1, then multiply by dx.

Test cases

case 1
in: [[1,1,1,1,1,1,1,1,1,1,1],0,1]
expected: 1
case 2
in: [[0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1],0,1]
expected: 0.5
case 3
in: [[0,1,4,9,16],0,2]
expected: 11
Starter codePython
def trapezoidal_integral(f_samples, x_start, x_end):
    # Your code here
    pass

3 test cases · run your code against them in the editor