다음은  이차방정식 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


  1. (*
  2.  *  Filename: testGoldenRatio.ml
  3.  *    황금률(즉, 이차방정식 x^2 - x - 1  = 0 의 양의 근)을 계산한다.
  4.  *
  5.  *   Execute: ocaml testGoldenRatio.ml
  6.  *
  7.  *   Compile: ocamlc -o testGoldenRatio.exe testGoldenRatio.ml
  8.  *   Execute: testGoldenRatio
  9.  *
  10.  *      Date:  2013/01/27
  11.  *    Author: P. Kim   [ pkim _AT_ scripts.pe.kr ]
  12.  *)
  13. open Printf;;
  14. let printUsing() =
  15.     printf "Using: TestGoldenRatio [-h|-help]\n" ;
  16.     printf "This calculates the value of the golden ratio.\n" ;;
  17. exception ZeroCoefficientException;;
  18. exception NegativeDiscriminantException;;
  19. (* 이차방정식 a x^2 + b x + c  = 0 의 근을 구한다. *)
  20. let findQuadraticRoot a b c =
  21.     if a = 0.0 then begin
  22.         raise ZeroCoefficientException
  23.     end
  24.     else if (b*.b -. 4.0*.a*.c < 0.0) then begin
  25.         raise NegativeDiscriminantException
  26.     end;
  27.     let x1 = ((-.b) +. (sqrt (b*.b -. 4.0*.a*.c))) /. (2.0 *. a) in
  28.     let x2 = ((-.b) -. (sqrt (b*.b -. 4.0*.a*.c))) /. (2.0 *. a) in
  29.     x1, x2  ;;  (* 리턴 겂 두 개 *)
  30. (* 실행 시작 지점 *)
  31. let cmdArgs = Sys.argv;;
  32. if (Array.length cmdArgs > 1) && (cmdArgs.(1) = "-h" || cmdArgs.(1) = "-help") then
  33. begin
  34.     printUsing();
  35.     exit 1
  36. end ;;
  37. let x1, x2  = findQuadraticRoot 1.0  (-1.0)  (-1.0) ;;
  38. if x1 >= x2 then begin
  39.     printf "The bigger root is %g " x1 ;
  40.     printf "and the less root is %g.\n" x2
  41. end
  42. else begin
  43.     printf "The bigger root is %g, " x2 ;
  44.     printf "and the less root is %g.\n" x1
  45. end ;;

 

컴파일> ocamlc -o testGoldenRatio.exe testGoldenRatio.ml

실행> testGoldenRatio
The bigger root is 1.61803 and the less root is -0.618034.



Posted by Scripter
,