-1

I am working on a academic problem and I am stuck.

I have to implement a function (make-nstf f). The function should return a function which calculates zero of the function by using the newton method.

To test my function I use https://repl.it/BWbp/1 you can copy the code into this website to test it if you like.

My (not working) code. I wrote some comments in order to give you a little help to understand the code:

(define (abs x)
    (if (< x 0) (- x) x)
)

;defines a function dif which returns another function (derivative)
(define (dif fkt k)
    (lambda (x)
       (/ 
            (- 
                (fkt (+ x k)) 
                (fkt (- x k)) 
            )
            (* 2 k)
        )
    )
)

;Calculates next x for newton method
(define (nextx f x)
    (- 
        x
        (/
            (f x)
            ((dif f 1) x)
        )
    )
)

;Should return a function which does the newton method with function f
(define (make-nstf f)
    (lambda(guess)
        ;Function checks whether the guess is good enough or not
        ;good enoug if guess - next guess < 0.0001 ist
        (define (good-enough? guess)
            (< 
                (abs 
                    (-
                        guess
                        (nextx f guess)
                    )
                )
            )
            0.0001
        )
        ;calculates next guess
        (define (improve guess)
            (nextx f guess)
        )
        ;checks whether guess is good enough and if not improve guess and try again
        (define (sqrt-iter guess)
            (if (good-enough? guess)
                guess
                (sqrt-iter (improve guess))
            )
        )
        ;Start with guess
        (sqrt-iter guess)
    )
)

;defines a function: (3*x*x)-2
(define (myfunc x) 
    (- 
        (* 
            3 
             x 
             x
        ) 
        2
    )
)

;defines a function which calls mak-nstf with my func.
(define nstf 
    (make-nstf myfunc)
)

Can you please help me find the bug?

Regards, hyperion

hyperion
  • 119
  • 5
  • 1
    This is pretty ugly scheme to be honest. Get a good editing environment that can match parenthesis for you. For example in `myfunc` you have one symbol per line using 9 lines for what could easily fit into 2. You can still keep failry good readability if you put a space between parens that close functions on the current line and those that close functions on other line. – WorBlux Nov 04 '15 at 00:20
  • Using more idiomatic formatting, your 76 lines [became 42](https://repl.it/BWrP). – molbdnilo Nov 04 '15 at 14:54

1 Answers1

0

You have a misplaced close paren in good-enough? (those sneaky parentheses...)

(define (good-enough? guess)
    (< 
        (abs 
            (-
                guess
                (nextx f guess)
            )
        )
    )
    0.0001  ;this should be moved up a line
)
Will
  • 451
  • 6
  • 17