読者です 読者をやめる 読者になる 読者になる

labunix's blog

labunixのラボUnix

clispとgcl/sbclでガウスの和算、黄金比、フィボナッチ数列。

■clispとgcl/sbclでガウスの和算、黄金比、フィボナッチ数列。

 debian lennyでCommon Lisp(clisp)
 http://d.hatena.ne.jp/labunix/20111123

 clispとgcl/sbclでネイピア数、tan(e)、アークタンジェント/アークコサインによる円周率の計算
 http://labunix.hateblo.jp/entry/20151015/1444857625

■ガウスの和算

$  num=100000;echo '(setq n '$num') (+ (* n (/ n 2)) (/ n 2))' | gcl | tail -3;echo
5000050000

>
$ num=100000;echo '(setq n '$num') (+ (* n (/ n 2)) (/ n 2))' | sbcl | tail -3;echo
; in: SETQ N
;     (SETQ N 100000)
; 
; caught WARNING:
;   undefined variable: N
; 
; compilation unit finished
;   Undefined variable:
;     N
;   caught 1 WARNING condition
* 
5000050000
* 

$ num=100000;echo '(setq n '$num') (+ (* n (/ n 2)) (/ n 2))' | clisp -q
[1]> 
100000
[2]> 
5000050000

■黄金比

$ echo '(defvar tolerance 0.00001)

(defun fixed-point (f first-guess)
(labels ((close-enough-p (v1 v2)
(< (abs (- v1 v2)) tolerance))
(try (guess)
(let ((next (funcall f guess)))
(if (close-enough-p guess next)
next
(try next)))))
(try first-guess)))
(fixed-point (lambda (x) (+ 1 (/ 1 x))) 1.0)' | gcl | tail -3;echo
1.6180327868852458

>

$ echo '(defvar tolerance 0.00001)

(defun fixed-point (f first-guess)
(labels ((close-enough-p (v1 v2)
(< (abs (- v1 v2)) tolerance))
(try (guess)
(let ((next (funcall f guess)))
(if (close-enough-p guess next)
next
(try next)))))
(try first-guess)))
(fixed-point (lambda (x) (+ 1 (/ 1 x))) 1.0L0)' | sbcl | tail -3;echo
* 
1.6180327868852458d0
* 

$ echo '(defvar tolerance 0.00001)

(defun fixed-point (f first-guess)
(labels ((close-enough-p (v1 v2)
(< (abs (- v1 v2)) tolerance))
(try (guess)
(let ((next (funcall f guess)))
(if (close-enough-p guess next)
next
(try next)))))
(try first-guess)))
(fixed-point (lambda (x) (+ 1 (/ 1 x))) 1.0L0)' | clisp -q
[1]> 
TOLERANCE
[2]> 
FIXED-POINT
[3]> 
1.6180327868852459016L0

■フィボナッチ数列

$ echo "(defun mk-list (x max)
 (if (= x max) 
 (list max)
 (cons x (mk-list (+ x 1) max))))
 
 ;; 二重再帰
 (defun fib (x) 
 (cond
 ((= x 1) 1)
 ((= x 2) 1)
 (t (+ (fib (- x 1))(fib (- x 2))))))
 (mapcar #'fib (mk-list 1 10))" | gcl | tail -3 ;echo
(1 1 2 3 5 8 13 21 34 55)

>

$ echo "(defun mk-list (x max)
(if (= x max) 
(list max)
(cons x (mk-list (+ x 1) max))))

;; 二重再帰
(defun fib (x) 
(cond
((= x 1) 1)
((= x 2) 1)
(t (+ (fib (- x 1))(fib (- x 2))))))
(mapcar #'fib (mk-list 1 10))" | sbcl | tail -3 ;echo
* 
(1 1 2 3 5 8 13 21 34 55)
* 

$ echo "(defun mk-list (x max)
(if (= x max) 
(list max)
(cons x (mk-list (+ x 1) max))))

;; 二重再帰
(defun fib (x) 
(cond
((= x 1) 1)
((= x 2) 1)
(t (+ (fib (- x 1))(fib (- x 2))))))
(mapcar #'fib (mk-list 1 10))" | clisp -q
[1]> 
MK-LIST
[2]> 
FIB
[3]> 
(1 1 2 3 5 8 13 21 34 55)