Skip to main content
5 of 5
edited tags
Jamal
  • 35.2k
  • 13
  • 134
  • 238

Riemann Sum Class (with variable endpoint behavior)

Here is my class for calculating a Riemann Sum. I did a cursory google search for a built-in function with these specifications but didn't find anything (I'm sure I just missed it or didn't look hard enough, but this is good practice).

Your input is welcome and appreciated. I'd like to not have to assign a lambda function to a variable but it works for me. I just worry that someone using this code may get confused.

from numpy import arange


class RiemannSum(object):

    def __init__(self, index, upper, rectangles, func, endpoints='mid'):
        """
        Constructor for base class for Riemann Sums.
        Will be subclassed for left, right, or mid-points for rectangles.

        :param index: Where to begin 'n' value. [n = index]
        :param upper: Upper bound of sum.  Max 'n' value.  [Number above sigma notation]
        :param rectangles: The number of rectangles to be used in the calculation.
        :param func: pass series function here; suggest assigning lambda function to variable and passing here
        :param endpoints: default to 'mid'. Valid values are 'mid', 'left', 'right' as strings
        """
        self.total = 0
        self.index = index
        self.upper = upper
        self.delta = (upper - index) / rectangles
        self.function = func

        if endpoints.lower() == 'left':  # left endpoints
            self.points = arange(self.index, self.upper, self.delta)
        elif endpoints.lower() == 'right':  # right endpoints
            self.points = arange(self.index + self.delta, self.upper + self.delta, self.delta)
        else:  # mid endpoints, usually most accurate
            diff = self.delta / 2
            self.points = [i for i in arange((self.index + diff),
                                         (self.upper + diff), self.delta)]

    def sum(self):
        outputs = [i for i in map(self.function, self.points)]
        self.total = sum(outputs)
        return self.delta * self.total

Here is an example of the code in use:

from math import sqrt
series = sqrt(x) - 2
num = RiemannSum(1,6,5,series,'mid').sum()
print(num)
Hanzy
  • 257
  • 1
  • 2
  • 10