Created
May 31, 2017 15:23
-
-
Save aruneko/8b57144c1f4298473eedcc1b9dea119d to your computer and use it in GitHub Desktop.
Haskellで自動微分
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 参考: 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