Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Scheme code to solve a quadratic equation?

I wrote this scheme code to compute one solution of the quadratic equation ax2 + bx + c = 0

(define (solve-quadratic-equation a b c) (define disc (sqrt (- (* b b) (* 4.0 a c)))) (/ (+ (- b) disc) (* 2.0 a)))

However, someone told me that this procedure is hard to understand. Why?

What would a cleaned up version of this procedure look like? Please let me know why the new procedure would be easier to understand.

Thanks

like image 947
dave Avatar asked Oct 30 '25 02:10

dave


2 Answers

Well, one reason is that it's all on one line. You can make it more readable using something called pretty-printing, where you break it up into multiple lines and use whitespace:

(define (solve-quadratic-equation a b c)
  (define disc (sqrt (- (* b b)
                        (* 4.0 a c))))
  (/ (+ (- b) disc)
     (* 2.0 a)))

This way you can more clearly see the structure of the expressions.

And here's a quote from SICP:

There is no limit (in principle) to the depth of such nesting and to the overall complexity of the expressions that the Lisp interpreter can evaluate. It is we humans who get confused by still relatively simple expressions such as

(+ (* 3 (+ (* 2 4) (+ 3 5))) (+ (- 10 7) 6))

which the interpreter would readily evaluate to be 57. We can help ourselves by writing such an expression in the form

(+ (* 3
      (+ (* 2 4)
         (+ 3 5)))
   (+ (- 10 7)
      6))

following a formatting convention known as pretty-printing, in which each long combination is written so that the operands are aligned vertically. The resulting indentations display clearly the structure of the expression.

like image 145
Paige Ruten Avatar answered Nov 02 '25 13:11

Paige Ruten


Isn't scheme all about developing a language to solve a problem? I admit I don't know much scheme, but I would add some indentation and add a square definelike so.

 (define (solve-quadratic-equation a b c)
     (define square (x) (* x x) 
     (define disc (sqrt (- (square b) (* 4.0 a c)))) 
                        (/ (+ (- b) disc) (* 2.0 a))))
like image 32
Nick Stinemates Avatar answered Nov 02 '25 13:11

Nick Stinemates



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!