Skip to content

Instantly share code, notes, and snippets.

@5outh
Last active December 16, 2015 20:10
Show Gist options
  • Save 5outh/5490857 to your computer and use it in GitHub Desktop.
Save 5outh/5490857 to your computer and use it in GitHub Desktop.
taylor series representation of a function
taylor :: (Floating a, Eq a) => Expr a -> [Expr a]
taylor expr = fmap fullSimplify (fmap series exprs)
where indices = fmap fromIntegral [1..]
derivs = fmap (changeVars 'a') (ddxs expr)
where changeVars c = mapVar (\_ -> Var c)
facts = fmap Const $ scanl1 (*) indices
exprs = zip (zipWith (:/:) derivs facts) indices -- f^(n)(a)/n!
series (expr, n) =
expr :*: ((Var 'x' :+: (negate' $ Var 'a')) :^: Const n) -- f^(n)(a)/n! * (x - a)^n
maclaurin = fmap (fullSimplify . plugIn 'a' 0) . taylor
evalTaylorWithPrecision a x prec =
sum . map (evalExpr' . plugIn 'x' x . plugIn 'a' a) . take prec . taylor
evalTaylor a x = evalTaylorWithPrecision a x 100
evalMaclaurin = evalTaylor 0
evalMacLaurinWithPrecision = evalTaylorWithPrecision 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment