[Haskell-beginners] Automatic Differentiation

Animesh Saxena animeshsaxena at icloud.com
Sat Mar 28 04:10:02 UTC 2015


I was implementing automatic differentiation in haskell and was able to code the calculation part, but I wanted to extend it to show the symbols instead of just the final value.
Let me explain and copy/paste the code…

3  data ADif a = ADif a a deriving (Eq)

10 instance Floating x => Floating (ADif x) where
11           pi = ADif pi 0
12           exp    (ADif x x') = ADif (exp    x) (x' * exp x)
13           log    (ADif x x') = ADif (log    x) (x' / x)
14           sqrt   (ADif x x') = ADif (sqrt   x) (x' / (2 * sqrt x))
15           sin    (ADif x x') = ADif (sin    x) (x' * cos x)
16           cos    (ADif x x') = ADif (cos    x) (x' * (- sin x))
….And so on all the functions


27 instance Num x => Num (ADif x) where
28         ADif x x' + ADif y y' = ADif (x+y) (x'+y')
29         ADif x x' * ADif y y' = ADif (x*y) (y'*x + x'*y)
30         fromInteger x = fromInteger x

let myfunction x = exp (log (sin x))
*Main> myfunction (ADif 2 1)
-0.4161468365471424

I verified that this is the correct solution by hand! (& well mathematica too!)

Anyway now I was hoping to print the actual symbols, so I was googling around for extending “Show” typeclass for floating and Num, kinda similar pattern. Is this the right approach? Or I need to rethink the problem?
Basically my aim is to do something like mathematica where if I specify D[f[x],x] then I get the answer in symbols. 

-Animesh


More information about the Beginners mailing list