明经CAD社区

 找回密码
 注册

QQ登录

只需一步,快速开始

搜索
查看: 2761|回复: 1

[基础] [原创]二分法求解方程代码 (递归+传递函数)

[复制链接]
发表于 2010-5-6 21:37:00 | 显示全部楼层 |阅读模式
本帖最后由 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的值为一正一负
其他方程亦可使用此方法


  1. ;;; By qjchen@gmail.com    http://www.mjtd.com/bbs/post.asp?action=edit&BoardID=3&replyID=31269&ID=80886&star=1
  2. ;;; The main code is mainly taken from the MIT book "Structure and interpretaion of computer programs"
  3. ;;; judge whether the initial range is suitable
  4. (defun halfsolve (f a b / a-value b-value)
  5.   (setq a-value ((eval f) a)
  6. b-value ((eval f) b)
  7.   )  
  8.   (cond
  9.     ((and (< a-value 0) (> b-value 0)) (searchhalf f a b))
  10.     ((and (> a-value 0) (< b-value 0)) (searchhalf f b a))
  11.     ((= a-value 0) a)
  12.     ((= b-value 0) b)
  13.     (T (prompt "The Values maybe not between a and b"))
  14.   )
  15. )

  16. ;;core code of dichotomy
  17. (defun searchhalf (f neg-point pos-point / test-value midpoint)
  18.   (setq midpoint (/ (+ neg-point pos-point) 2))
  19.   (cond
  20.     ((close-enough? neg-point pos-point) midpoint)
  21.     (T
  22.      (setq test-value ((eval f) midpoint))
  23.      (cond
  24.        ((> test-value 0) (searchhalf f neg-point midpoint))
  25.        ((< test-value 0) (searchhalf f midpoint pos-point))
  26.        (T midpoint)
  27.      )
  28.     )
  29.   )
  30. )

  31. ;;judge small enough
  32. (defun close-enough? (x y)
  33.   (< (abs (- x y)) 1e-10)
  34. )

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

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

"觉得好,就打赏"
还没有人打赏,支持一下
发表于 2010-6-9 16:10:00 | 显示全部楼层

新手学习过程中,多谢分享.

您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|CAD论坛|CAD教程|CAD下载|联系我们|关于明经|明经通道 ( 粤ICP备05003914号 )  
©2000-2023 明经通道 版权所有 本站代码,在未取得本站及作者授权的情况下,不得用于商业用途

GMT+8, 2025-2-22 18:43 , Processed in 0.149645 second(s), 27 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表