Skip to content

Instantly share code, notes, and snippets.

@ColCarroll
Created November 26, 2013 21:06
Show Gist options
  • Save ColCarroll/7666266 to your computer and use it in GitHub Desktop.
Save ColCarroll/7666266 to your computer and use it in GitHub Desktop.
A class for playing with numerical integrals and derivatives.
class Cfunction:
"""
A class for numeric calculus experiments
"""
def __init__(self, fcn, eps=0.001):
self.fcn = fcn
self.__eps = eps
self.integral = lambda x: self.integrate(0, x) # Indefinite integral
self.derivative = self._derivative() # f'(x)
def __call__(self, x):
return self.fcn(x)
def _integral(self):
"""
Indefinite integral. Calculated using midpoint.
"""
return lambda x: self.__eps * (self.fcn(x) + self.fcn(x + self.__eps)) / 2.
def _derivative(self):
"""
Numeric derivative, calculated using rightward step.
"""
return lambda x: (self.fcn(x + self.__eps) - self.fcn(x)) / self.__eps
def integrate(self, lower, upper):
"""
Definite integral
"""
steps = int((upper - lower) / self.__eps)
return sum(self._integral()(lower + self.__eps * x) for x in range(steps))
def example():
"""
How to use the above code
"""
f = Cfunction(lambda x: x * x)
print(f.integral(2)) # f.integral should be (x^3)/3, so ~8/3 is good
print(f.derivative(2)) # f.derivative should be 2x, so ~4 is good
print(f.integrate(-1, 1)) # (1/3) - (-1/3) = 2/3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment