Complex numbers and multiple answers

Started by axtens, April 30, 2009, 09:46:33 PM

Previous topic - Next topic

axtens

G'day everyone



W.r.t. complex numbers, how easy would it be to have

  (sqrt -1)

return

  (0.0 1.0)



and on the question of multiple answers, there are two correct answers to the square root of 4

  (sqrt 4)

-->

  (2 -2)



Could there be a way in future newLISPs to be able to do complexes and also some system setting that would return both answers from things like (sqrt)?



Kind regards,

Bruce.

Lutz

#1
Here is an application defining e complex number class using FOOP:



http://www.newlisp.org/complex.cgi">http://www.newlisp.org/complex.cgi

Kazimir Majorinc

#2
Or this code:


(set '*. mul '/. div '+. add '-. sub)
(set 'old-sqrt sqrt)
(set 'pi (*. 2 (acos 0)))

(set 'ro (lambda(z)
            (old-sqrt (+. (*. (nth 0 z) (nth 0 z))
                          (*. (nth 1 z) (nth 1 z))))))
                           
(set 'phi (lambda(z)
            (cond ((= (nth 1 z) 0)(if (>= (nth 0 z) 0)
                                      0
                                      pi))
                 
                  ((= (nth 0 z) 0)(if (> (nth 1 z) 0)
                                      (/. pi 2)
                                      (*. 3 (/. pi 2))))
                                     
                  (true (atan (/. (nth 1 z) (nth 0 z)))))))
                 
(set 'new-sqrt
    (lambda(z)
       (unless (list? z)
               (set 'z (list z 0)))
       (list (list (*. (old-sqrt (ro z)) (cos (/. (phi z) 2)))
                   (*. (old-sqrt (ro z)) (sin (/. (phi z) 2))))
             (list (*. (old-sqrt (ro z)) (cos (+. (/. (phi z) 2) pi)))
                   (*. (old-sqrt (ro z)) (sin (+. (/. (phi z) 2) pi)))))))

(set 'sqr (lambda (z)
           (list (-. (*. (z 0)(z 0)) (*. (z 1)(z 1)))
                 (*. 2 (z 0)(z 1)))))

;test


(dolist (z '((0 0) (0 4) (9 0) (3 4)))
  (println z "-> new-sqrt -> map sqr -> " (map sqr (new-sqrt z))))


; If you want not new-sqrt but sqrt (watch dynamic scope)

(constant 'sqrt new-sqrt)

(println)
(dolist (z '((0 0) (0 4) (9 0) (3 4)))
  (println z "-> sqrt -> map sqr -> " (map sqr (sqrt z))))
 
(exit)
http://kazimirmajorinc.com/\">WWW site; http://kazimirmajorinc.blogspot.com\">blog.

cormullion

#3
Also, there are some useful maths routines over at (the much neglected) newlisp-on-noodles: http://newlisp-on-noodles.org/wiki/index.php/Math">//http://newlisp-on-noodles.org/wiki/index.php/Math



The advantage of not having things built in is that you have all the fun of building them in and doing it your way! :)