1

According to Newton-Raphson's:

Xn+1 = Xn - f(Xn) / f'(Xn)

(newtonRhap x f fx)

(newtonRhap 0.1 sin cos) => 0

(newtonRhap 2.0 
            (lambda (x) (- (* x x) x 6))             ; f
            (lambda (x) (- (* 2 x) 1  )) ) => 3      ; f'

How can I implement this function?

The routine will stop iteration when the change in solution is less than pre-set tolerance.

I use a global variable for it, (define TOL 1e-6):

#lang racket
(define TOL 1e-6)
(define (func f x) (f x))
(define (f x) (- (* x x) x 6))
(define (fx x) (- (* 2 x) 1))
(define x 2.0)
(define (newtonRhap x ff ffx)  
    ( (> (- x (/ ff ffx)) TOL)
      (newtonRhap (- x (/ ff ffx)) ff ffx)  
      (list x) ) )

(display (newtonRhap x (f x) (fx x)) )
Will Ness
  • 70,110
  • 9
  • 98
  • 181
Jack Mulin
  • 109
  • 1
  • 7

2 Answers2

0

Good attempt, you need to modify newtonRaph function to use IF though, like this

(define (newtonRhap x ff ffx)
  (if (> (- x (/ ff ffx)) TOL)
      (newtonRhap (- x (/ ff ffx)) ff ffx))
      (list x)))
river
  • 1,028
  • 6
  • 16
0

First, you're missing an if there:

(define (newtonRhap x ff ffx)
    ( if (> (- x (/ ff ffx)) TOL)
      (newtonRhap (- x (/ ff ffx)) ff ffx)
      (list x) ) )

Without it you would be calling the result of the Boolean test as a function with the following two forms values as arguments (it could work in a lazy functional language with Church-encoded conditionals, but that's besides the point, and Scheme / Racket is not lazy).

Second, and even more crucially, the last two arguments to newtonRhap are functions, but you're treating them as if they were numeric values. Correcting this gives us

(define (nl x)     ; for debugging insight;
   (newline)       ; for production redefine it as
   (display x)     ;    (define (nl x) x)
   x)  

(define (newtonRhap x ff ffx)
  (let ((new-x (nl (- x (/ (ff x) (ffx x))))))  ; Follow The Formula
    ( if (> (abs (- x new-x)) TOL)             ; use abs
      (newtonRhap new-x ff ffx)          ; make next step
      (list new-x) ) ) )        ; return the new x, it's closer to the true result

Now we can run

(display (newtonRhap x f fx))

3.333333333333333
3.019607843137255
3.0000762951094835
3.000000001164153
3.0(3.0)
>
Will Ness
  • 70,110
  • 9
  • 98
  • 181