다음은 이차방정식 x^2 - x - 1 = 0 의 양의 근 즉 황금비율(golden ratio)을 구하는 Common Lisp 애플리케이션 소스이다. 황금비율을 구하는 비례방정식은 1 : x = x : (x+1) 이며, 이를 이차방정식으로 표현한 것이 x^2 - x - 1 = 0 이다.
See: http://en.wikipedia.org/wiki/Golden_ratio
아래의 소스는 CLisp 으로 테스트되었다.
- ;; Filename: testGoldenRatio.lsp
- ;; 황금률(즉, 이차방정식 x^2 - x - 1 = 0 의 양의 근)을 계산한다.
- ;;
- ;; Execute: clisp testGoldenRatio.lsp
- ;;
- ;; Date: 2013. 9. 1.
- (defun printUsing()
- (format t "Using: lisp testGoldenRatio.lsp [-h|-help]~%")
- (format t "This calculates the value of the golden ratio.~%")
- )
- (defun handle-zero-error(msg)
- (catch 'handle-zero-error
- (foprmat t msg)
- (quit)))
- ;; 이차방정식 a x^2 + b x + c = 0 의 근을 구한다.
- (defun findQuadraticRoot(a b c)
- (if (zerop a)
- (throw 'fn-a 'done))
- (if (< (- (* b b) (* 4 a c)) 0.0)
- (throw 'fn-a 'done))
- (setf x1 (/ (+ (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2.0 a)))
- (setf x2 (/ (- (- b) (sqrt (- (* b b) (* 4 a c)))) (* 2.0 a)))
- (list x1 x2)
- )
- ;; 실행 시작 지점
- (if (and (> (length ext:*args*) 0) (or (equal (nth 0 ext:*args*) "-h") (equal (nth 0 ext:*args*) "-help"))) (progn
- (printUsing)
- (quit) ))
- (setf values (findQuadraticRoot 1.0 (- 1.0) (- 1.0)))
- (setf x1 (nth 0 values))
- (setf x2 (nth 1 values))
- (if (>= x1 x2) (progn
- (format t "The bigger root is ~F, ~%" x1)
- (format t "and the less root is ~F.~%" x2) )
- (progn
- (format t "The bigger root is ~F, ~%" x2)
- (format t "and the less root is ~F.~%" x1) )
- )
실행> clisp testGoldenRatio.lsp
The bigger root is 1.618034,
and the less root is -0.618034.
'프로그래밍 > Common Lisp' 카테고리의 다른 글
진법(radix) 표 만들기 예제 with Common Lisp (0) | 2013.09.04 |
---|---|
대화형 모드의 진법(radix) 변환 예제 with Common Lisp (0) | 2013.09.02 |
현재 시각 알아내기 for Common Lisp (0) | 2013.08.31 |
조립제법(Horner의 방법) 예제 for Common Lisp (0) | 2013.08.30 |
80컬럼 컨솔에 19단표 출력하기 예제 for Common Lisp (0) | 2013.08.29 |