• C

c to lisp(square root)

//This is the c program. I want you to convert it to lisp program. Please help me.

void main( void )
    double f, g, N;

    puts( "Square Root Program" );
    printf( "Please enter a number: " );
    scanf( "%lg", &N );
    f = N/2;            // The initial approximation.

    for (;;) {
        g = N/f;  
        if ( g*g == N ) break;
        f = (f + g) / 2;  // Next guess is average of prior pair.
    printf( "The square root of %g is %g\n", N, g );
Who is Participating?

Improve company productivity with a Business Account.Sign Up

fridomConnect With a Mentor CEO/ProgrammerCommented:
Emacs Lisp is surely a list but I have the feeling that is not the Lisp he wants to have. But I found that a nice idea and have thought, let's hack a bit ;-)

So how about:
(defun my-square (from)
  (interactive "nGive me a number: ")
  (let ((val (/ from 2.0)))
    (loop for estimate = (/ from val) then (/ from val)
      until (floating-eq (* estimate estimate) from 0.001)
      do (setf val (/ (+ val estimate) 2))
      finally return estimate)))
(defun floating-eq (val-1 val-2 epsilon)
  (<= (abs (- val-1 val-2)) epsilon))

(format "The sqare root of %.4f = %.4f" 2 (my-square 2))
"The sqare root of 2.0000 = 1.4142"

Well easier would be of course using the built-in functions....

Have  nice weekend
Install Emacs
http://www.gnu.org/software/emacs/windows/faq2.html (if you are on windows, if you are on unix/linux I'm sure you know where to get it :)

Use it to make your program in Lisp
Hmm was thinking about something recursive - cool to come back to Emacs fun :)
Function root: (alt-x root) enter the number to be rooted, and the max number of recursive loops

(defun approx (N f loops)
  (let ((g (/ N f)))
    (if (or (= (* g g) N)
          (< loops 1))
      (approx N (/ (+ f g) 2) (- loops 1)))))

(defun root (N loops)
  (interactive "nNumber to root: \nnMax loops: ")
  (message "Root of %f approximated to %f" N (approx N 2.0 loops)))
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.