我有一个函数(eval
)来评估多项式。
eval coeffs value = .......
coeffs
是系数列表。
例)计算
3x ^ 2 + 2x + 1,x = 20 当我输入如上所示的系数时,它会像 程序像这样工作,最后一部分是错误的(多项式的值):
这是我的代码 如何用系数和x值来评估多项式?value
适用于数学中的 x
coeffs
以反向顺序存储。 [1,2,3]
getCoeff 0 ls = do return ls
getCoeff n ls = do putStr "What is the x^"
putStr (show(n-1))
putStr " coefficient: "
v <- getLine
w <- getCoeff (n-1) ((read v :: Float):ls)
return w
evalpoly = do putStr "What is the degree of polynomial: "
v <- getLine
l <- (getCoeff ((read v :: Int)+1) [])
putStr "What value do you want to evaluate at: "
x <- getLine
putStr "The value of the polynomial is: "
putStr (show (polyEvaluate (l) (read x :: Float)))
putStr "\n"
eval [] x = 0.0
eval (l) x =
What is the degree of polynomial: 2
What is the x^2 coefficient: 3
What is the x^1 coefficient: 2
What is the x^0 coefficient: 1
What value do you want to evaluate at: 20
The value of the polynomial is 1241.0
答案 0 :(得分:3)
一些提示......
你可以轻松写出一系列权力
powers n = iterate (*n) 1
> take 10 $ powers 2
[1,2,4,8,16,32,64,128,256,512]
并将其与系数
结合起来> zip [1,2,3] $ powers 20
[(1,1),(2,20),(3,400)]
您必须考虑如何将其更改为对的乘积之和(使用zipWith)