Search code examples
pythonfunction

How do I write code to calculate the integral of a set of numbers using the trapezoidal rule in Python?


I can't seem to figure out how to get the right value for my integral. I'm not getting an error and when I test the separate elements of my function it seems to give me back all the right values but when I put it all together it gives me a bad result.

So far this is what I have

def trap_rule(y_values, x_values):
    delta = (x_values[-1] - x_values[0])/(len(x_values))
    int_ = 0.0
    for i in range(0, len(y_values)):
        int_ += (y_values[i-1] + y_values[i]) / 2
        int_ = int_ * delta
        
    return int_

mydata_sund= pd.read_csv("sund1.csv")
sund_time = list(mydata_sund["time [hr]"])
sund_power = list(mydata_sund["power [kW]"])

intergral = trap_rule(sund_power, sund_time)

The output I get is 3.5005 which I incorrect... I think It does give me two lists with the right data in it so I'm 90% sure it's not a problem with importing the files. And when I calculate my delta_x for my function it also returns the correct value

I have been trying to find answers on here, but I can't seem to find anything related to using a list and not just having the values already given.

Sorry In advance if this is formatted wrong, this is my first time using StackOverflow


Solution

  • There are a couple of problems here:

    1. Your function has 2 instances of errors created by the fencepost problem. The function takes len(x_values) points but it needs to add the areas of len(x_values)-1 trapezoids.
    2. By calculating a single delta up front and applying it to all the trapezoids, you're assuming that x_values is spaced evenly. This might be true for the specific dataset you're using, but it's not generally true. Better to compute it for each trapezoid.

    Here's a revised version:

    def trap_rule(y_values, x_values):
        area = 0.0
        for i in range(0, len(y_values)-1):
            area += (y_values[i] + y_values[i+1]) * (x_values[i+1] - x_values[i]) / 2
            
        return area