[Edu-sig] a segue from discrete math to calculus using Python

Kirby Urner kurner at oreillyschool.com
Mon Feb 3 21:05:39 CET 2014


"""
Discrete math approach to Calculus

This is what I imagine as a segue from discrete math to
calc, using Python.  We're using a tiny delta_x = h to
compute values discretely, and then comparing those
computed series with functions "at the limit" such as
calculus would give us.  It's the same segue we typically
encounter using Sigma notation to introduce Riemann Sum
notation in Algebra 2 today.  All the assumptions are
deliberately simplified:  continuous functions in one
variable.

(c) MIT License, K. Urner, 4D Solutions, 2014

"""

from math import log

h = delta_x = 1e-2  # tiny delta

class Integral:

    def __init__(self, func):
        self.func = func

    def __call__(self, a, b):
        if not a<=b:
            raise ValueError
        area = 0.0
        x = a
        while x <= b:
            area += self.func(x) * delta_x
            x += delta_x
        return area

class Derivative:

    def __init__(self, func):
        self.func = func

    def __call__(self, x):
        f = self.func
        return (f(x+h) - f(x-h)) / (2*h)


def parabola(x):
    """Parabola"""
    return x * x  # parabola

def int_parabola(x):
    """Parabola"""
    return (x ** 3)/3  # integral of parabola

def deriv_parabola(x):
    """Derivative of Parabolic function"""
    return 2*x  # parabola

def reciprocal(x):
    """Reciprocal"""
    return 1/x

def int_reciprocal(x):
    """Integral of Reciprocal"""
    return log(x)   # integral is Ln(x)

def deriv_reciprocal(x):
    """Derivative of Reciprocal"""
    return -x**-2

def report(f, domain, limint, limderiv, C=0):
    integral_f = Integral(f)
    derivative_f = Derivative(f)
    print("=" * 30)
    print(f.__doc__, [(x,f(x)) for x in domain])
    print()
    print("Approx Integral  : ", ["({}, {:>5.2f})".format(x,
integral_f(a=domain[0], b=x) + C) for x in domain])
    print("Limit Integral   : ", ["({}, {:>5.2f})".format(x, limint(x)) for
x in domain])
    print()
    print("Approx Derivative: ", ["({}, {:>5.2f})".format(x,
derivative_f(x)) for x in domain])
    print("Limit Derivative : ", ["({}, {:>5.2f})".format(x, limderiv(x))
for x in domain])

report(parabola, range(-10, 11), limint = int_parabola, limderiv =
deriv_parabola, C = -334) # C = constant offset
report(reciprocal, range(1, 11), limint = int_reciprocal, limderiv =
deriv_reciprocal)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edu-sig/attachments/20140203/03a8e7d6/attachment.html>


More information about the Edu-sig mailing list