List Comprehension and Patterns in Higher Derivatives
In this example, we demonstrate how to use Python to quickly find several derivatives of a function, then determine any patterns in the result. Suppose we want to find a pattern to come up with a formula for the nth derivative of f(x) = 1/x. The general strategy is to just keep taking derivatives (diff) until we notice a pattern. We could take the derivatives one at a time, but we are doing the same thing every time (taking a derivative), remember that Python has a tool called list comprehension which allows us to do several computations at once. So we first define x as symbolic, then define f = 1/x. Now let’s take the first six derivatives-ALL IN ONE LINE OF CODE! We create a variable we will call fderivs, which will be a list of derivatives, so we put square brackets around it. Next, we ask Python to take the ith derivative of f, where i is from 1 to 6. The range(a,b) command creates a list of integers from a INCLUSIVE to b EXCLUSIVE. So the command I am typing says literally that fderivs is a list of the ith derivative of f for i values from 1 to 6 (technically, 1 up to, but not including 7). Now we print the list and observe patterns-which means we have to think (REMEMBER: when you turn Python ON, don’t turn your brain OFF!). We notice that the exponent in the denominator is one more than the derivative we took, so the nth derivative will have x^(n+1) in the denominator. We also notice that the signs alternate, which can be expressed as either (-1)^n or (-1)^(n+1). For n=1, the sign is negative, so a quick check shows us the (-1)^n is correct. Finally, you may recognize the factorial numbers in the numerator-if not-doing this by hand and not simplifying will help you recognize it-and in fact, the numerator of the nth derivative would be n!. So we can now print our statement that the formula for the nth derivative of f(x) = 1/x is (-1)^n*n!/x^(n+1). So notice how we used Python to quickly compute several derivatives, allowing us to think about the results, find the patterns, and generalize them.