Skip to content

Instantly share code, notes, and snippets.

@games647
Created November 23, 2016 14:07
Show Gist options
  • Save games647/a98722b597a922c32836738c7f4699df to your computer and use it in GitHub Desktop.
Save games647/a98722b597a922c32836738c7f4699df to your computer and use it in GitHub Desktop.
Newton method in racket
;; The first three lines of this file were inserted by DrRacket. They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname newton-method) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
;; newton-method: (X -> Y) (X -> Z) number number -> number
;;
;; Makes use of the newton method to calculate the f(x) = 0
;;
;; Example:
(define (newton-method fct fct-abl x delta)
(local [
(define x1 (- x (/ (fct x) (fct-abl x))))
(define difference (- x x1))]
(cond
[(<= difference delta) x1]
[else (newton-method fct fct-abl x1 delta)])))
;; Tests
(check-expect (newton-method (lambda (x) (sqr x)) (lambda (x) (* 2 x)) 2 2) 1)
(check-expect (newton-method (lambda (x) (sqr x)) (lambda (x) (* 2 x)) 2 1) 1)
(check-expect (newton-method (lambda (x) (sqr x)) (lambda (x) (* 2 x)) 2 0.5) 0.5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment