# notes12 - • Let We write a function that returns a...

This preview shows page 1. Sign up to view the full content.

This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: • Let. We write a function that returns a sentence containing the two roots of the quadratic equation ax 2 + bx + c = 0 using the formula x = − b ± √ b 2 − 4 ac 2 a (We assume, to simplify this presentation, that the equation has two real roots; a more serious program would check this.) ;;;;; In file cs61a/lectures/1.3/roots.scm (define (roots a b c) (se (/ (+ (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a)) (/ (- (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2 a)) )) This works fine, but it’s inefficient that we have to compute the square root twice. We’d like to avoid that by computing it once, giving it a name, and using that name twice in figuring out the two solutions. We know how to give something a name by using it as an argument to a function: ;;;;; In file cs61a/lectures/1.3/roots.scm (define (roots a b c) (define (roots1 d) (se (/ (+ (- b) d) (* 2 a)) (/ (- (- b) d) (* 2 a)) )) (roots1 (sqrt (- (* b b) (* 4 a c)))) ) Roots1 is an internal helper function that takes the value of the square root in the formula as its argument...
View Full Document

{[ snackBarMessage ]}

Ask a homework question - tutors are online