to evaluate polynomial in Haskell -
i have function(eval
) evaluate polynomial.
eval coeffs value = .......
coeffs
list of coefficents.
value
x in math
ex) calculate 3x^2 + 2x + 1 x=20
coeffs
stored reverse order.
when type coefficient above, stored [1,2,3]
program working , last part wrong (the value of polynomial): here code
getcoeff 0 ls = return ls getcoeff n ls = putstr "what x^" putstr (show(n-1)) putstr " coefficient: " v <- getline w <- getcoeff (n-1) ((read v :: float):ls) return w evalpoly = putstr "what degree of polynomial: " v <- getline l <- (getcoeff ((read v :: int)+1) []) putstr "what value want evaluate at: " x <- getline putstr "the value of polynomial is: " putstr (show (polyevaluate (l) (read x :: float))) putstr "\n" eval [] x = 0.0 eval (l) x =
what degree of polynomial: 2 x^2 coefficient: 3 x^1 coefficient: 2 x^0 coefficient: 1 value want evaluate at: 20 value of polynomial 1241.0
how can evaluate polynomial coefficient , x value?
some hints...
you can write series of powers easily
powers n = iterate (*n) 1 > take 10 $ powers 2 [1,2,4,8,16,32,64,128,256,512]
and combine coefficients
> zip [1,2,3] $ powers 20 [(1,1),(2,20),(3,400)]
you have think change sum of product of pairs (use zipwith)
Comments
Post a Comment