Jump to content

Roots of a function: Difference between revisions

added Haskell
(→‎{{header|Java}}: A correct, and more java-like, version)
(added Haskell)
Line 358:
END DO</lang>
 
=={{header|Haskell}}==
<lang haskell>f x = x^3-3*x^2+2*x
 
findRoots start stop step eps = doRoots start where
doRoots x | x > stop = []
| abs r < eps = x : doRoots (x+step)
| otherwise = doRoots (x+step)
where r = f x</lang>
Executed in GHCi:
<lang haskell>*Main> findRoots (-1.0) 3.0 0.0001 0.000000001
[-9.381755897326649e-14,0.9999999999998124,1.9999999999997022]</lang>
 
Or using package [http://hackage.haskell.org/package/hmatrix hmatrix] from HackageDB.
<lang haskell>import Numeric.GSL.Polynomials
import Data.Complex
 
*Main> mapM_ print $ polySolve [0,2,-3,1]
(-5.421010862427522e-20) :+ 0.0
2.000000000000001 :+ 0.0
0.9999999999999996 :+ 0.0</lang>
No complex roots, so:
<lang haskell>*Main> mapM_ (print.realPart) $ polySolve [0,2,-3,1]
-5.421010862427522e-20
2.000000000000001
0.9999999999999996</lang>
 
=={{header|J}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.