Partial derivatives in Haskell

While another friend wanted to help with a program that could solve for the roots of functions using the Newton method, and, of course, for this I needed to somehow calculate the derivative of the function numerically, and this is what I came up with:

deriv f x = (f (x+h) - f x) / h where h = 0.00001

Newton's method was a fairly simple task, and it works pretty well. But now I started to wonder: is it possible to somehow use this function to partially calculate partial derivatives, or is it something that will require a full CAS? I would post my attempts, but I do not know what else to do.

Please keep in mind that I am new to Haskell. Thanks!

+7
source share
2 answers

, , , , . , , :

deriv :: (Double -> Double) -> Double -> Double

, , , , .

type ℝ = Double

, ..

deriv :: (ℝ -> ℝ) -> ℝ -> ℝ

, , , ℝ²

grad :: ((ℝ,ℝ) -> ℝ) -> (ℝ,ℝ) -> (ℝ,ℝ)
grad f (x,y) = ((f (x+h,y) - f (x,y)) / h, (f (x,y+h) - f (x,y)) / h)
 where h = 0.00001

, . :

import Data.VectorSpace
import Data.Basis

grad :: (HasBasis v, Scalar v ~ ℝ) => (v -> ℝ) -> v -> v
grad f x = recompose [ (e, (f (x ^+^ h*^basisValue b) - f x) ^/ h)
                     | (e,_) <- decompose x ]
 where h = 0.00001

, , .

+9
+3

All Articles