############################## librep 版 ############################## #!/usr/bin/rep !# (defun bisection (f a b) (let* ( (fa (f a)) (fb (f b)) (c (/ (+ a b) 2)) (fc (f c)) ) (cond ((>= (* fa fb) 0) nil) ((or (= c a) (= c b)) c) ; 極少數的情況下, 浮點數才可以用 == ; 或 != 來比較. 這裡就是 ((< (* fc fa) 0) (bisection f a c)) ; c 要來取代 b 的角色, 與 a 相對 ((> (* fc fa) 0) (bisection f c b)) ; c 要來取代 a 的角色, 與 b 相對 (t c) ; 真巧, f(c) = 0 ) ) ) (defun xcm2 (x) (- (* x x x) 2)) ; main program (format standard-output "cubic root of 2 is: %d\n" (bisection xcm2 1.0 2.0) ) ; 另一種寫法 (format standard-output "cubic root of 2 is: %d\n" (bisection (lambda (x) (- (* x x x) 2)) 1.0 2.0) ) ############################## perl 版 ############################## #!/usr/bin/perl -w use strict; sub bisection { my ($f, $a, $b) = @_; my ($fa, $fb) = (&$f($a), &$f($b)); my ($c, $fc); die if $fa*$fb >= 0; do { $c = ($a+$b)/2; return $c if $c == $a || $c == $b; # 極少數的情況下, 浮點數才可以用 == # 或 != 來比較. 這裡就是 $fc = &$f($c); if ($fc*$fa < 0) { # c 要來取代 b 的角色, 與 a 相對 $b = $c; $fb = $fc; } elsif ($fc*$fa > 0) { # c 要來取代 a 的角色, 與 b 相對 $a = $c; $fa = $fc; } else { return $c; # 真巧, f(c) == 0 } } while (1); } sub xcm2 { my ($x)=@_; return $x*$x*$x-2; } # main program printf("cubic root of 2 is: %f\n", bisection(\&xcm2, 1, 2) ); # 另一種寫法 printf("cubic root of 2 is: %f\n", bisection(sub { my ($x)=@_; return $x*$x*$x-2; }, 1, 2) ); ############################## c 版 ############################## #include #include double bisection(double f(double x), double a, double b) { double fa = f(a), fb = f(b), c, fc; assert(fa*fb < 0); do { c = (a+b)/2; if (c == a || c == b) return c; /* 極少數的情況下, 浮點數才可以用 == 或 != 來比較. 這裡就是 */ fc = f(c); if (fc*fa < 0) { /* c 要來取代 b 的角色, 與 a 相對 */ b = c; fb = fc; } else if (fc*fa > 0) { /* c 要來取代 a 的角色, 與 b 相對 */ a = c; fa = fc; } else { return c; /* 真巧, f(c) == 0 */ } } while (1); } double xcm2(double x) { return x*x*x-2; } int main(void) { printf("cubic root of 2 is: %f\n", bisection(&xcm2,1,2)); return 0; }