Skip to content

Instantly share code, notes, and snippets.

@aruneko
Created May 31, 2017 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aruneko/8b57144c1f4298473eedcc1b9dea119d to your computer and use it in GitHub Desktop.
Save aruneko/8b57144c1f4298473eedcc1b9dea119d to your computer and use it in GitHub Desktop.
Haskellで自動微分
-- 参考: http://www.mathgram.xyz/entry/rust/ad/forward
data Dual = Dual { x :: Double
, dx :: Double
} deriving Show
instance Num Dual where
(Dual x1 dx1) + (Dual x2 dx2) = Dual { x = x1 + x2, dx = dx1 + dx2 }
(Dual x1 dx1) * (Dual x2 dx2) = Dual { x = x1 * x2, dx = dx1 * x2 + x1 * dx2 }
instance Fractional Dual
instance Floating Dual where
sin (Dual x dx) = Dual { x = sin x, dx = dx * cos x }
cos (Dual x dx) = Dual { x = cos x, dx = - dx * sin x }
exp (Dual x dx) = Dual { x = exp x, dx = dx * exp x }
f :: Dual -> Dual
f x = x * x + x
g :: Dual -> Dual
g x = sin x + x * exp x
main :: IO ()
main = do
let a = Dual { x = 2, dx = 1 } -- Dual {x = 6.0, dx = 5.0}
print $ f a
let b = Dual { x = 0, dx = 1 } -- Dual {x = 0.0, dx = 2.0}
print $ g b
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment