다음은 이차방정식 x^2 - x - 1 = 0 의 양의 근 즉 황금비율(golden ratio)을 구하는 OCaml 소스이다. 황금비율을 구하는 비례방정식은 1 : x = x : (x+1) 이며, 이를 이차방정식으로 표현한 것이 x^2 - x - 1 = 0 이다.
See: http://en.wikipedia.org/wiki/Golden_ratio
- (*
- * Filename: testGoldenRatio.ml
- * 황금률(즉, 이차방정식 x^2 - x - 1 = 0 의 양의 근)을 계산한다.
- *
- * Execute: ocaml testGoldenRatio.ml
- *
- * Compile: ocamlc -o testGoldenRatio.exe testGoldenRatio.ml
- * Execute: testGoldenRatio
- *
- * Date: 2013/01/27
- * Author: P. Kim [ pkim _AT_ scripts.pe.kr ]
- *)
- open Printf;;
- let printUsing() =
- printf "Using: TestGoldenRatio [-h|-help]\n" ;
- printf "This calculates the value of the golden ratio.\n" ;;
- exception ZeroCoefficientException;;
- exception NegativeDiscriminantException;;
- (* 이차방정식 a x^2 + b x + c = 0 의 근을 구한다. *)
- let findQuadraticRoot a b c =
- if a = 0.0 then begin
- raise ZeroCoefficientException
- end
- else if (b*.b -. 4.0*.a*.c < 0.0) then begin
- raise NegativeDiscriminantException
- end;
- let x1 = ((-.b) +. (sqrt (b*.b -. 4.0*.a*.c))) /. (2.0 *. a) in
- let x2 = ((-.b) -. (sqrt (b*.b -. 4.0*.a*.c))) /. (2.0 *. a) in
- x1, x2 ;; (* 리턴 겂 두 개 *)
- (* 실행 시작 지점 *)
- let cmdArgs = Sys.argv;;
- if (Array.length cmdArgs > 1) && (cmdArgs.(1) = "-h" || cmdArgs.(1) = "-help") then
- begin
- printUsing();
- exit 1
- end ;;
- let x1, x2 = findQuadraticRoot 1.0 (-1.0) (-1.0) ;;
- if x1 >= x2 then begin
- printf "The bigger root is %g " x1 ;
- printf "and the less root is %g.\n" x2
- end
- else begin
- printf "The bigger root is %g, " x2 ;
- printf "and the less root is %g.\n" x1
- end ;;
컴파일> ocamlc -o testGoldenRatio.exe testGoldenRatio.ml
실행> testGoldenRatio
The bigger root is 1.61803 and the less root is -0.618034.
'프로그래밍 > OCaml' 카테고리의 다른 글
진법(radix) 표 만들기 예제 with OCaml (0) | 2013.01.28 |
---|---|
대화형 모드의 진법(radix) 변환 예제 with OCaml (0) | 2013.01.27 |
현재 시각 알아내기 for OCaml (0) | 2013.01.27 |
80컬럼 컨솔에 19단표 출력하기 예제 for OCaml (0) | 2013.01.27 |
(최대공약수 구하기) while 반복문 없는 예제 for OCaml (0) | 2013.01.27 |