[Tutor] Python for Grade 12 Calculus

Steven D'Aprano steve at pearwood.info
Fri Feb 12 04:48:17 EST 2016


On Thu, Feb 11, 2016 at 05:56:00PM -0500, Nicholas Tomasic wrote:
> Hi,
> 
> I'm a 12th grade Calculus teacher at a school in Toronto, Ontario, and I'm
> thinking about incorporating Python into an Independent Study Project for
> two of my students. Both are passionate about coding with Python and I'm
> thinking of asking them to produce something that can either a) calculate
> derivatives of simple functions or b) assign 1 student the product rule,
> one the quotient rule, and have them write a program that can tackle
> derivatives in those forms.

I've been thinking more about this, and Python does make it very easy. 
Here's a function which will differentiate a polynomial. You pass as 
argument a list of the coefficients, so:

5x^3 + x^2 - 7x + 5

gets passed as the list [5, 1, -7, 5].

def differentiate(coeffs):
    new_coeffs = []
    for coeff, power in zip(coeffs, range(len(coeffs) - 1, -1, -1)):
        print("term = {}*x^{}".format(coeff, power))
        new_coeff = coeff * power
        if power == 0:
            print("derivative of this term = {}".format(new_coeff))
        else:
            print("derivative of this term = {}*x^{}".format(new_coeff, power-1))
        new_coeffs.append(new_coeff)
    if new_coeffs[-1] != 0:
        msg = "expected derivative of constant term to be zero, but got {}"
        raise RuntimeError(msg.format(new_coeffs[-1]))
    return new_coeffs[0:-1]




And here is the output:

py> differentiate([5, 1, -7, 5])
term = 5*x^3
derivative of this term = 15*x^2
term = 1*x^2
derivative of this term = 2*x^1
term = -7*x^1
derivative of this term = -7*x^0
term = 5*x^0
derivative of this term = 0
[15, 2, -7]


And here is how we would use Sympy to do the same sort of thing:

py> import sympy
py> x = sympy.var("x")
py> f = 5*x**3 + x**2 - 7*x + 5
py> print f
5*x**3 + x**2 - 7*x + 5
py> sympy.diff(f, x)
15*x**2 + 2*x - 7



You will notice that Python uses * for multiplication and ** for powers, 
but in my "differentiate" function I used ^ in the output to represent 
powers. 


Sympy has many display options. For example:

py> sympy.pprint(f, use_unicode=False)
   3    2
5*x  + x  - 7*x + 5
py> sympy.pprint(f, use_unicode=True)
   3    2
5⋅x  + x  - 7⋅x + 5


More here:

http://docs.sympy.org/latest/tutorial/printing.html




-- 
Steve


More information about the Tutor mailing list