[ create a new paste ] login | about

Link: http://codepad.org/1gypn5pb    [ raw code | output | fork ]

johannes - Haskell, pasted on Mar 1:
module Main where
 
data Pnomial = Pnomial [Int] deriving Show
 
----------------------------------------------------------------
 
degree :: Pnomial -> Int
degree (Pnomial cs) = pred $ length cs
 
----------------------------------------------------------------
 
differentiate :: Pnomial -> Pnomial
differentiate (Pnomial cs) = let n = pred $ length cs
                         in Pnomial [y * (cs !! y) |
                                     y <- take n $ enumFrom 1]
 
----------------------------------------------------------------
 
eval :: Pnomial -> Float -> Float
eval (Pnomial p) = fn p 0
    where fn (c:cs) acc at | cs == []   = acc+x
                           | otherwise = fn cs (acc+x) at
                             where n = length cs
                                   d = degree $ Pnomial p
                                   x = fromIntegral
                                       c * at ^ (d - n)
 
----------------------------------------------------------------
 
newton :: Pnomial -> Float -> Float
newton p x = x - p `eval` x / differentiate p `eval` x
 
newtonSeq = iterate . newton
 
----------------------------------------------------------------
 
newtonMethod :: Int -> Pnomial -> Float -> Float
newtonMethod n poly = last . take n . newtonSeq poly
 
----------------------------------------------------------------
 
main = do print (sqrt 5, newtonMethod 4 (Pnomial [-5, 0, 1]) 2)


Output:
1
(2.23606797749979,2.236068)


Create a new paste based on this one


Comments: