Skip to content

Instantly share code, notes, and snippets.

@insaneyilin
Created August 12, 2019 16:24
Show Gist options
  • Save insaneyilin/4edc21503bcb30822bbd04b8f79f82eb to your computer and use it in GitHub Desktop.
Save insaneyilin/4edc21503bcb30822bbd04b8f79f82eb to your computer and use it in GitHub Desktop.
Find square-root using Newton method in Scheme
(define (average x y)
(* (+ x y) 0.5))
(define (good_enough? guess x)
(< (abs (- x (* guess guess))) 0.001))
(define (improve guess x)
(average guess (/ x guess)))
(define (sqrt_itr guess x)
(if (good_enough? guess x)
guess
(sqrt_itr (improve guess x) x)))
(define (newton_sqrt x)
(sqrt_itr 1.0 x))
; use MIT-Scheme to test codes above
; $ scheme
; > (cf "newton_sqrt")
; > (load "newton_sqrt.scm")
; > (newton_sqrt 4.0)
; ;Value: 2.0000000929222947
; > (newton_sqrt 1000.0)
; ;Value: 31.622782450701045
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment