Complex numbers and multiple answers

Pondering the philosophy behind the language
Locked
axtens
Posts: 28
Joined: Mon Apr 06, 2009 12:23 pm
Location: Perth, WA Australia
Contact:

Complex numbers and multiple answers

Post by 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
Posts: 5289
Joined: Thu Sep 26, 2002 4:45 pm
Location: Pasadena, California
Contact:

Post by Lutz »

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

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

Kazimir Majorinc
Posts: 388
Joined: Thu May 08, 2008 1:24 am
Location: Croatia
Contact:

Post by Kazimir Majorinc »

Or this code:

Code: Select all

(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)

cormullion
Posts: 2038
Joined: Tue Nov 29, 2005 8:28 pm
Location: latiitude 50N longitude 3W
Contact:

Post by cormullion »

Also, there are some useful maths routines over at (the much neglected) newlisp-on-noodles: 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! :)

Locked