Author Topic: Equation solve - dichotomy method  (Read 1701 times)

0 Members and 1 Guest are viewing this topic.

qjchen

  • Bull Frog
  • Posts: 285
  • Best wishes to all
Equation solve - dichotomy method
« on: May 06, 2010, 09:46:53 AM »
Recently for studying the equation solve, I learn from the MIT book "Structure and interpretaion of computer programs" which recommended by Evgeniy. And translate the "dichotomy" (half search method) code from SCHEME to autolisp. It is as following code.

The code solve the equation -x^3+2x+3=0. The test value 1.0, 2.0 must let the value of -x^3+2x+3 , one is + and the other is -. or it will get wrong.

Code: [Select]
;;; By qjchen@gmail.com
;;; The main code is mainly taken from the MIT book "Structure and interpretaion of computer programs"
;;; judge whether the initial range is suitable
(defun halfsolve (f a b / a-value b-value)
  (setq a-value ((eval f) a)
b-value ((eval f) b)
  )
 
  (cond
    ((and (< a-value 0) (> b-value 0)) (searchhalf f a b))
    ((and (> a-value 0) (< b-value 0)) (searchhalf f b a))
    ((= a-value 0) a)
    ((= b-value 0) b)
    (T (prompt "The Values maybe not between a and b"))
  )
)

;;core code of dichotomy
(defun searchhalf (f neg-point pos-point / test-value midpoint)
  (setq midpoint (/ (+ neg-point pos-point) 2))
  (cond
    ((close-enough? neg-point pos-point) midpoint)
    (T
     (setq test-value ((eval f) midpoint))
     (cond
       ((> test-value 0) (searchhalf f neg-point midpoint))
       ((< test-value 0) (searchhalf f midpoint pos-point))
       (T midpoint)
     )
    )
  )
)

;;judge small enough
(defun close-enough? (x y)
  (< (abs (- x y)) 1e-10)
)

;; The equation to be solve, -x^3+2x+3=0
(defun myfuntosolve (x)
  (- (* x x x) (* 2 x) 3)
)

;;Main function by qjchen@gmail.com
(defun c:test()
  (princ (rtos (halfsolve myfuntosolve 1.0 2.0) 2 14))
  (princ)
)

http://qjchen.mjtd.com
My blog http://chenqj.blogspot.com (Chinese, can be translate into English)