Lesson goal: Finding derivatives

Previous: Find the factorial | Home | Next: Advice on quadratic equations

You remember learning about derivatives in Calculus, right? It's fun how sites like WolframAlpha know how to do them. Let's write some Prolog code to compute derivatives.

There are two math related elements to realize about taking derivative by hand: 1) you're really just recognizing patterns and 2) you then apply a "derivative rule" to the pattern you recognized.

Here's an example. If you see $y=x^4$, you recognize the pattern of the exponent and know to use the "power law" rule: "the exponent goes in front, and then subtract 1 from the exponent to form a new exponent." So you get $y'=4x^3$. See a $\sin$? The answer will have a $\cos$. A constant? Always zero.

It turns out Prolog is really good at finding patterns and applying rules. Seeing a computer do derivatives feels "AI-ish," both in how it's coded up and seeing the results; it feels "human like." Here's a few examples of telling it about derivatives, that you'll find in the code below:

  • deriv(X,X,1).: The derivative of any thing X with respect to X is $1$. And X cab be anything, $x$, $y$, $z$, etc.
  • deriv(C,_,0) :- number(C).: The derivative of an item C with respect to anything (_) is $0$, as long as C is a number (a constant).
The code below includes these definitions and some more, which we're sure you'll recognize.

Now you try. Change the goal to differentiate something you like. Remember the format is deriv(expression,with-respect-to,Result).

Type your code here:


See your results here: