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:
Note! This code takes derivatives but does not simplify the results. Look at the answers carefully, and you'll see they're correct, just not simplified.
Take out the deriv(Z^2,X,2*Z*DZ) :- deriv(Z,X,DZ). line then do a derivative of $x^2$. See if you can figure out what this rule helps with.
Share your code
Show a friend, family member, or teacher what you've done!