I have to compute a polynomial like this --
f(x) = x^4 - 2.274x^3 + 1.8x^2 - 0.576x + 1.0
with this lisp function --
(defun polynomial (x)
(+ (+ (+ (+ (expt x 4) (* -2.274 * (expt x 3)))
(* 1.8 (* x x))) (* -0.576 x)) 0.1))
when I call (polynomial 0.5) the result is different at different evaluations, like this --
CL-USER> (polynomial 0.5)
-1.9495
CL-USER> (polynomial 0.5)
0.8786454
CL-USER> (polynomial 0.5)
0.07474504
CL-USER> (polynomial 0.5)
0.3032537
CL-USER> (polynomial 0.5)
0.23830011
CL-USER>
what is going on ? I am using the latest sbcl.
*
in argument position evaluates to the very last result you had in the REPL. In your code you do (* -2.274 * (expt x 3))
where *
is -1.9495
perhaps after the first run. (You'd get an error when running it the first time if the last result was not a number.)
You can have multiple arguments to both *
and +
and all LISPs has polish prefix notation so your function might look better like this:
;; f(x) = x^4 - 2.274x^3 + 1.8x^2 - 0.576x + 1.0
(defun polynomial (x)
(+ (expt x 4)
(* -2.274 (expt x 3))
(* 1.8 x x)
(* -0.576 x)
1.0)) ;; this was originally 0.1
(polynomial 0.5) ; ==> 0.94025004
Basically x + y + z
in infix becomes (+ x y z)
in prefix.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With