[飞马系列] 二分法求解方程代码 (递归+传递函数)
本帖最后由 qjchen 于 2011-12-19 15:12 编辑近日写某代码,需用到求解方程,由于之前对把函数当参数传递及递归函数没有仔细研究,故以此为契机做了一下研究,以MIT的“Structure and interpretaion of computer programs”《计算机程序的构造和解释》的lisp方言SCHEME代码为蓝本,撰写如下代码,希望对有兴趣的朋友有用:)
其他的如牛顿迭代法应该也可类似编出
当然程序还很简陋,没有其他容错等,有待细化
myfuntosolve中定义了待求解的方程-x^3+2x+3=0,求解的时候指定的1.0和2.0需满足能使得-x^3+2x+3的值为一正一负
其他方程亦可使用此方法
;;; By qjchen@gmail.com http://www.mjtd.com/bbs/post.asp?action=edit&BoardID=3&replyID=31269&ID=80886&star=1
;;; 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)
)
<p>新手学习过程中,多谢分享.</p>
页:
[1]