Gustavo Aryel
Gustavo Aryel

Reputation: 13

lisp quadratic equation imaginary and real parts

I'm learning lisp and I can not understand this problem

Modify the function that returns the roots of a quadratic equation so that it returns the real and imaginary parts of the roots, in the case of they are complex. Suppose the coefficients are real.

;;;gnu clisp 2.49

(defun root(a b c)
  (let ((root1 (/ (+ (* -1 b) (sqrt (- (expt b 2) (* 4 a c )))) (* 2 a)))
        (root2 (/ (- (* -1 b) (sqrt (- (expt b 2) (* 4 a c )))) (* 2 a))))
    (format t "x1=~,2f" root1)
    (format t ", x2=~,2f~%" root2)))

(root 1 -3 -4)
(root 1 0 -4)
(root 6 11 -35)
(root 1 -7 0)
(root 5 3 5)

I would like to return the real and imaginary parts in the form x + yi

Upvotes: 1

Views: 1096

Answers (1)

sds
sds

Reputation: 60014

You need to print your complex numbers in the format you like. E.g.:

(defun number2string (num)
  (if (complexp num)
      (format nil "~,2f + ~,2fi" (realpart num) (imagpart num))
      (format nil "~,2f" num)))

(defun quadratic-roots (a b c)
  (let* ((root1 (/ (+ b (sqrt (- (* b b) (* 4 a c )))) (* -2 a)))
         (root2 (- (- b) root1)))
    (format t "x1=~a, x2=~a" (number2string root1) (number2string root2))
    (values root1 root2)))

Upvotes: 4

Related Questions