다음은  대화형 모드(interactive mode)에서 진법 변환(radix conversion)하는 자바 소스 코드이다.
메뉴는 주메뉴 Command: (S)et radix, (A)bout, (Q)uit or E(x)it
와 부메뉴 SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
로 구성되어 있으며, 진법 변환의 핵심은 Integer 클래스와 Long 클래스의 정적 메소드

         Integer.parseInt(String, int);
         Long.toString(long, int);

을 이용하였으며, 지원되는 진법은 2진법부터 36진법까지이다.



  1. /*
  2.  *  Filename: ConvertRadixApp.java
  3.  *            Convert radix in a interactive mode.
  4.  *
  5.  *  Compile: javac -d . ConvertRadixApp.java
  6.  *  Execute: java ConvertRadixApp
  7.  *
  8.  *      Date:  2008/03/25
  9.  *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  10.  */
  11. import java.io.*;
  12. import java.util.*;
  13. public class ConvertRadixApp {
  14.     public static void printUsage() {
  15.         System.out.println("Usage: java ConvertRadixApp");
  16.         System.out.println("Convert radix in a interactive mode, where the maximum radix is 36.");
  17.     }
  18.     public void printAbout() {
  19.         System.out.println("    About: Convert radix in a interactive mode.");
  20.     }
  21.     public void printMainMenu() {
  22.         System.out.println("  Command: (S)et radix, (A)bout, (Q)uit or E(x)it");
  23.     }
  24.     public void printMainPrompt() {
  25.         System.out.print("  Prompt> ");
  26.     }
  27.     public void printSubMenu(int srcRadix, int destRadix) {
  28.         System.out.println("    Convert Radix_" + srcRadix + " to Radix_" + destRadix);
  29.         System.out.println("    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit");
  30.     }
  31.     public void printSubPrompt() {
  32.         System.out.print("    Input Value>> ");
  33.     }
  34.     public String convertRadix(String s,  int srcRdx, int destRdx) {
  35.         long val;
  36.         String ret = "";
  37.         try {
  38.             val = Integer.parseInt(s, srcRdx);
  39.             ret = Long.toString(val, destRdx);
  40.             return ret.toUpperCase();
  41.         }
  42.         catch (NumberFormatException nfx) {
  43.             System.out.println("    Error: " + nfx.getMessage() + " cantains some invalid character.");
  44.             ret = "????";
  45.         }
  46.         finally {
  47.             return ret.toUpperCase();
  48.         }
  49.     }
  50.     public void doConvert(BufferedReader r, int srcRadix, int destRadix) {
  51.         String line;
  52.         String cmd;
  53.         String srcStr = "", destStr = "";
  54.         System.out.println();
  55.         printSubMenu(srcRadix, destRadix);
  56.         try {
  57.             do {
  58.                 printSubPrompt();
  59.                 while ((cmd = r.readLine()) == null) {
  60.                 }
  61.                 if ("main()".equals(cmd)) {
  62.                     return;
  63.                 }
  64.                 else if ("exit()".equals(cmd) || "quit()".equals(cmd)) {
  65.                     System.exit(0);
  66.                 }
  67.                 try {
  68.                     Integer.parseInt(cmd, srcRadix);
  69.                     srcStr = cmd;
  70.                     destStr = convertRadix(srcStr, srcRadix, destRadix);
  71.                     System.out.println("        ( " + srcStr + " )_" + srcRadix +  "   --->   ( " + destStr + " )_" + destRadix);
  72.                     System.out.println();
  73.                 }
  74.                 catch (NumberFormatException nfx) {
  75.                 }
  76.              } while (true);
  77.         }
  78.         catch (IOException ex) {
  79.             ex.printStackTrace();
  80.         }
  81.     }
  82.     public void doStart() {
  83.         String line;
  84.         String cmd;
  85.         int srcRadix = 10, destRadix = 10;
  86.         String srcStr = "", destStr = "";
  87.         boolean onlyOnce = true;
  88.         BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
  89.         try {
  90.             do {
  91.                 System.out.println();
  92.                 if (onlyOnce) {
  93.                     System.out.println("  The supported maximum radix is 36.");
  94.                     onlyOnce = false;
  95.                 }
  96.                 printMainMenu();
  97.                 printMainPrompt();
  98.                 while ((cmd = r.readLine()) == null) {
  99.                 }
  100.                 if ("qQxX".contains(cmd) && cmd.length() == 1) {
  101.                     System.exit(0);
  102.                 }
  103.                 else if ("aA".contains(cmd) && cmd.length() == 1) {
  104.                     printAbout();
  105.                 }
  106.                 else if ("sS".contains(cmd) && cmd.length() == 1) {
  107.                     System.out.print("  Input the source and target radices (say, 16 2): ");
  108.                     line = r.readLine();
  109.                     StringTokenizer st = new StringTokenizer(line, " ,\t");
  110.                     while (st.countTokens() < 2) {
  111.                         System.out.print("  Input the source and target radices (say, 16 2): ");
  112.                         line = r.readLine();
  113.                         st = new StringTokenizer(line, " ,\t");
  114.                     }
  115.                     srcRadix = Integer.parseInt(st.nextToken());
  116.                     destRadix = Integer.parseInt(st.nextToken());
  117.                     doConvert(r, srcRadix, destRadix);
  118.                 }
  119.             } while (true);
  120.         }
  121.         catch (IOException ex) {
  122.             ex.printStackTrace();
  123.         }
  124.     }
  125.     public static void main(String[] args) {
  126.         if (args.length > 0 && "-h".equals(args[0])) {
  127.             printUsage();
  128.             System.exit(1);
  129.         }
  130.         ConvertRadixApp app = new ConvertRadixApp();
  131.         app.doStart();
  132.     }
  133. }



컴파일> javac -d . ConvertRadixApp.java

실행> java ConvertRadixApp

  The supported maximum radix is 36.
  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> s
  Input the source and target radices (say, 16 2): 10 16

    Convert Radix_10 to Radix_16
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> 256
        ( 256 )_10   --->   ( 100 )_16

    Input Value>> main()

  Command: (S)et radix, (A)bout, (Q)uit or E(x)it
  Prompt> s
  Input the source and target radices (say, 16 2): 16 10

    Convert Radix_16 to Radix_10
    SubCommand: 'main()' to goto Main menu, 'exit()' or 'quit()' to exit
    Input Value>> FFFF
        ( FFFF )_16   --->   ( 65535 )_10

    Input Value>> exit()





Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

다음은  이차방정식 x^2 - x - 1  = 0 의 양의 근 즉 황금비율(golden ratio)을 구하는 C++ 애플리케이션 소스이다. 황금비율을 구하는 비례방정식은   1 : x = x : (x+1) 이며, 이를 이차방정식으로 표현한 것이 x^2 - x - 1  = 0 이다.

See:  Golden ratio - Sajun.org


  1. /*
  2.  *  Filename: testGoldenRatioCPP.cpp
  3.  *    황금률(즉, 이차방정식 x^2 - x - 1  = 0 의 양의 근)을 계산한다.
  4.  *
  5.  *   Compile: cl -GX testGoldenRatioCPP.cpp
  6.  *
  7.  *   Execute: testGoldenRatioCPP
  8.  *
  9.  *      Date:  2008/03/24
  10.  *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  11.  */
  12. #include <iostream>
  13. #include <string>
  14. #include <cmath>
  15. using namespace std;
  16. typedef struct _PAIR {
  17.     double x1;
  18.     double x2;
  19. } PAIR;
  20. void printUsing() {
  21.     cout << "Using: testGoldenRatioCPP [-h|-help]" << endl;
  22.     cout << "This calculates the value of the golden ratio." << endl;
  23. }
  24. // 이차방정식 a x^2 + b x + c  = 0 의 근을 구한다.
  25. PAIR *findQuadraticRoot(double a, double b, double c) {
  26.     static PAIR zeros;
  27.     if (a == 0.0) {
  28.         cerr << "Since the highest coefficient is zero, the given equation is not a quadratic equation." << endl;
  29.         exit(1);
  30.     }
  31.     else if (b*b - 4*a*c < 0.0) {
  32.         cerr << "Since the discriminant " << (b*b - 4*a*c) << " is negative, the given equation has no real root." << endl;
  33.         exit(1);
  34.     }
  35.     zeros.x1 = (-b + sqrt(b*b - 4*a*c)) / (2.0 * a);
  36.     zeros.x2 = (-b - sqrt(b*b - 4*a*c)) / (2.0 * a);
  37.     return (PAIR *) &zeros;
  38. }
  39. void main(int argc, char *argv[]) {
  40.     double x1, x2;
  41.     PAIR *values = (PAIR *) findQuadraticRoot(1.0, -1.0, -1.0);
  42.     if (argc > 1 && (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0)) {
  43.         printUsing();
  44.         exit(1);
  45.     }
  46.     values = findQuadraticRoot(1.0, -1.0, -1.0);
  47.     x1 = values->x1;
  48.     x2 = values->x2;
  49.     if (x1 >= x2) {
  50.         cout << "The bigger root is " << x1 << endl;
  51.         cout << "and the less root is " << x2 << endl;
  52.     }
  53.     else {
  54.         cout << "The bigger root is " << x2 << endl;
  55.         cout << "and the less root is " << x1 << endl;
  56.     }
  57. }



컴파일> cl -GX testGoldenRatioCPP.cpp

실행> testGoldenRatioCPP
The bigger root is 1.618034,
and the less root is -0.618034.



Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

다음은  이차방정식 x^2 - x - 1  = 0 의 양의 근 즉 황금비율(golden ratio)을 구하는 C 애플리케이션 소스이다. 황금비율을 구하는 비례방정식은   1 : x = x : (x+1) 이며, 이를 이차방정식으로 표현한 것이 x^2 - x - 1  = 0 이다.

See:  Golden ratio - Sajun.org


  1. /*
  2.  *  Filename: testGoldenRatio.c
  3.  *    황금률(즉, 이차방정식 x^2 - x - 1  = 0 의 양의 근)을 계산한다.
  4.  *
  5.  *   Compile: cl testGoldenRatio.c
  6.  *
  7.  *   Execute: testGoldenRatio
  8.  *
  9.  *      Date:  2008/03/24
  10.  *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  11.  */
  12. #include <stdio.h>
  13. #include <string.h>
  14. #include <math.h>
  15. typedef struct _PAIR {
  16.     double x1;
  17.     double x2;
  18. } PAIR;
  19. void printUsing() {
  20.     printf("Using: testGoldenRatio [-h|-help]\n");
  21.     printf("This calculates the value of the golden ratio.\n");
  22. }
  23. // 이차방정식 a x^2 + b x + c  = 0 의 근을 구한다.
  24. PAIR *findQuadraticRoot(double a, double b, double c) {
  25.     static PAIR zeros;
  26.     if (a == 0.0) {
  27.         fprintf(stderr, "Since the highest coefficient is zero, the given equation is not a quadratic equation.\n");
  28.         exit(1);
  29.     }
  30.     else if (b*b - 4*a*c < 0.0) {
  31.         fprintf(stderr, "Since the discriminant %f is negative, the given equation has no real root.\b", b*b - 4*a*c);
  32.     exit(1);
  33.     }
  34.     zeros.x1 = (-b + sqrt(b*b - 4*a*c)) / (2.0 * a);
  35.     zeros.x2 = (-b - sqrt(b*b - 4*a*c)) / (2.0 * a);
  36.     return (PAIR *) &zeros;
  37. }
  38. void main(int argc, char *argv[]) {
  39.     double x1, x2;
  40.     PAIR *values = (PAIR *) findQuadraticRoot(1.0, -1.0, -1.0);
  41.     if (argc > 1 && (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "-help") == 0)) {
            printUsing();
  42.         exit(1);
  43.     }
  44.     values = findQuadraticRoot(1.0, -1.0, -1.0);
  45.     x1 = values->x1;
  46.     x2 = values->x2;
  47.     if (x1 >= x2) {
  48.         printf("The bigger root is %lf, \n", x1);
  49.         printf("and the less root is %lf.\n", x2);
  50.     }
  51.     else {
  52.         printf("The bigger root is %lf, \n", x2);
  53.         printf("and the less root is %lf.\n", x1);
  54.     }
  55. }



컴파일> cl testGoldenRatio.c

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


Ch를 이용하면 C 언어 소스 코드를 (컴파일하지 않고) 직접 실행시킬 수 있다.

실행> ch testGoldenRatio.c
The bigger root is 1.618034,
and the less root is -0.618034.



Posted by Scripter
,

다음은  이차방정식 x^2 - x - 1  = 0 의 양의 근 즉 황금비율(golden ratio)을 구하는 Lua 애플리케이션 소스이다. 황금비율을 구하는 비례방정식은   1 : x = x : (x+1) 이며, 이를 이차방정식으로 표현한 것이 x^2 - x - 1  = 0 이다.

See:  http://en.wikipedia.org/wiki/Golden_ratio


  1. -- Filename: testGoldenRatio.lua
  2. --    황금률(즉, 이차방정식 x^2 - x - 1  = 0 의 양의 근)을 계산한다.
  3. --
  4. --  Execute: lua testGoldenRatio.lua
  5. --
  6. -- Date    24-March-2008
  7. -- Author  PH Kim   [ pkim (AT) scripts.pe.kr ]
  8. function printUsing()
  9.     print("Using: lua testGoldenRatio.lua [-h|-help]");
  10.     print("This calculates the value of the golden ratio.");
  11. end
  12. -- 이차방정식 a x^2 + b x + c  = 0 의 근을 구한다.
  13. function findQuadraticRoot(a, b, c)
  14.     if a == 0.0 then
  15.         error( "Since the highest coefficient is zero, the given equation is not a quadratic equation." )
  16.     elseif b*b - 4*a*c < 0.0 then
  17.         error( "Since the discriminant " .. (b*b - 4*a*c) .. " is negative, the given equation has no real root." )
  18.     end
  19.     x1 = (-b + math.sqrt(b*b - 4*a*c)) / (2.0 * a)
  20.     x2 = (-b - math.sqrt(b*b - 4*a*c)) / (2.0 * a)
  21.     return {x1, x2}
  22. end
  23. -- 실행 시작 지점
  24. if #arg > 0 and (arg[1] == "-h" or arg[1] == "-help") then
  25.     printUsing()
  26.     os.exit(1)
  27. end
  28. values = findQuadraticRoot(1.0, -1.0, -1.0)
  29. x1 = values[1]
  30. x2 = values[2]
  31. if x1 >= x2 then
  32.     print("The bigger root is " .. x1 .. ", ")
  33.     print("and the less root is " .. x2 .. ".")
  34. else
  35.     print("The bigger root is " .. x2 .. ", ")
  36.     print("and the less root is " .. x1 .. ".")
  37. end



실행> lua testGoldenRatio.lua
The bigger root is 1.6180339887499,
and the less root is -0.61803398874989.



Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

다음은  이차방정식 x^2 - x - 1  = 0 의 양의 근 즉 황금비율(golden ratio)을 구하는 Ruby 애플리케이션 소스이다. 황금비율을 구하는 비례방정식은   1 : x = x : (x+1) 이며, 이를 이차방정식으로 표현한 것이 x^2 - x - 1  = 0 이다.

See:  http://en.wikipedia.org/wiki/Golden_ratio


  1. #  Filename: testGoldenRatio.rb
  2. #    황금률(즉, 이차방정식 x^2 - x - 1  = 0 의 양의 근)을 계산한다.
  3. #
  4. #   Execute: ruby testGoldenRatio.rb
  5. #
  6. #      Date:  2008/03/24
  7. #    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  8. def printUsing()
  9.     print("Using: ruby testGoldenRatio.rb [-h|-help]\n")
  10.     print("This calculates the value of the golden ratio.\n")
  11. end
  12. # 이차방정식 a x^2 + b x + c  = 0 의 근을 구한다.
  13. def findQuadraticRoot(a, b, c)
  14.     if a == 0.0
  15.         raise "Since the highest coefficient is zero, the given equation is not a quadratic equation."
  16.     elsif b*b - 4*a*c < 0.0
  17.         raise "Since the discriminant " + (b*b - 4*a*c).to_s + " is negative, the given equation has no real root."
  18.     end
  19.     x1 = (-b + Math.sqrt(b*b - 4*a*c)) / (2.0 * a)
  20.     x2 = (-b - Math.sqrt(b*b - 4*a*c)) / (2.0 * a)
  21.     return [x1, x2]
  22. end
  23. # 실행 시작 지점
  24. if ARGV.length > 0 && (ARGV[0] == "-h" || ARGV[0] == "-help")
  25.     printUsing()
  26.     exit(1)
  27. end
  28. values = findQuadraticRoot(1.0, -1.0, -1.0)
  29. x1 = values[0]
  30. x2 = values[1]
  31. if x1 >= x2 then
  32.     print("The bigger root is #{x1}, \n")
  33.     print("and the less root is #{x2}.\n")
  34. else
  35.     print("The bigger root is #{x2}, \n")
  36.     print("and the less root is #{x1}.\n")
  37. end



실행> ruby testGoldenRatio.rb
The bigger root is 1.61803398874989,
and the less root is -0.618033988749895.


실행> jruby testGoldenRatio.rb
The bigger root is 1.618033988749895,
and the less root is -0.6180339887498949.




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

다음은  이차방정식 x^2 - x - 1  = 0 의 양의 근 즉 황금비율(golden ratio)을 구하는 Python 애플리케이션 소스이다. 황금비율을 구하는 비례방정식은   1 : x = x : (x+1) 이며, 이를 이차방정식으로 표현한 것이 x^2 - x - 1  = 0 이다.

See:  http://en.wikipedia.org/wiki/Golden_ratio


  1. # -*- encoding: ms949 -*-
  2. #  Filename: testGoldenRatio.py
  3. #    황금률(즉, 이차방정식 x^2 - x - 1  = 0 의 양의 근)을 계산한다.
  4. #
  5. #   Execute: python testGoldenRatio.py
  6. #
  7. #      Date:  2008/03/24
  8. #    Author: PH Kim   [ pkim (AT) scripts.pe.kr ]
  9. import sys
  10. import math
  11. def printUsing():
  12.     print("Using: python testGoldenRatio.py [-h|-help]")
  13.     print("This calculates the value of the golden ratio.")
  14. # 이차방정식 a x^2 + b x + c  = 0 의 근을 구한다.
  15. def findQuadraticRoot(a, b, c):
  16.     if a == 0.0:
  17.         raise RuntimeError("Since the highest coefficient is zero, the given equation is not a quadratic equation.")
  18.     elif b*b - 4*a*c < 0.0:
  19.         raise RuntimeError("Since the discriminant " + (b*b - 4*a*c) + " is negative, the given equation has no real root.")
  20.     x1 = (-b + math.sqrt(b*b - 4*a*c)) / (2.0 * a)
  21.     x2 = (-b - math.sqrt(b*b - 4*a*c)) / (2.0 * a)
  22.     return [x1, x2]
  23. # 실행 시작 지점
  24. if len(sys.argv) > 1 and (sys.argv[1] == "-h" or sys.argv[1] == "-help"):
  25.     printUsing()
  26.     sys.exit(1)
  27. values = findQuadraticRoot(1.0, -1.0, -1.0)
  28. x1 = values[0]
  29. x2 = values[1]
  30. if x1 >= x2:
  31.     print("The bigger root is " + str(x1) + ", ")
  32.     print("and the less root is " + str(x2) + ".")
  33. else:
  34.     print("The bigger root is " + str(x2) + ", ")
  35.     print("and the less root is " + str(x1) + ".")



실행> python testGoldenRatio.py
The bigger root is 1.61803398875,
and the less root is -0.61803398875.


실행> jython testGoldenRatio.py
The bigger root is 1.618033988749895,
and the less root is -0.6180339887498949.



위의 소스 코드에서 인코딩 선언 부분만

# -*- encoding: cp949 -*-

로 고치면, IronPython에서도 실행된다.


실행> ipy testGoldenRatio.py
The bigger root is 1.61803398875,
and the less root is -0.61803398875.


만일 Jython 2.5.0 이상이면
LookupError: unknown encoding 'ms949'
또는
SyntaxError: Unknown encoding: ms949
와 같은 에러를 만날 수 있다. 이럴 때는

# -*- encoding: iso-8859-1 -*-
또는
# coding: iso-8859-1

로 해야할 것이다. (이는 Jython 2.5.x 의 버그인 것으로 보인다.)



Creative Commons License
저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

다음은  이차방정식 x^2 - x - 1  = 0 의 양의 근 즉 황금비율(golden ratio)을 구하는 Groovy 애플리케이션 소스이다. 황금비율을 구하는 비례방정식은   1 : x = x : (x+1) 이며, 이를 이차방정식으로 표현한 것이 x^2 - x - 1  = 0 이다.

See:  http://en.wikipedia.org/wiki/Golden_ratio

  1. /*
  2.  *  Filename: testGoldenRatio.groovy
  3.  *    황금률(즉, 이차방정식 x^2 - x - 1  = 0 의 양의 근)을 계산한다.
  4.  *
  5.  *   Execute: groovy testGoldenRatio.groovy
  6.  *
  7.  *      Date:  2008/03/24
  8.  *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  9.  */
  10. import java.util.ArrayList
  11. def printUsing() {
  12.     println("Using: groovy testGoldenRatio.groovy [-h|-help]")
  13.     println("This calculates the value of the golden ratio.")
  14. }
  15. // 이차방정식 a x^2 + b x + c  = 0 의 근을 구한다.
  16. def findQuadraticRoot(double a, double b, double c) {
  17.     if (a == 0.0) {
  18.         throw new RuntimeException("Since the highest coefficient is zero, the given equation is not a quadratic equation.");
  19.     }
  20.     else if (b*b - 4*a*c < 0.0) {
  21.         throw new RuntimeException("Since the discriminant " + (b*b - 4*a*c) + " is negative, the given equation has no real root.")
  22.     }
  23.     double x1 = (-b + Math.sqrt(b*b - 4*a*c)) / (2.0 * a)
  24.     double x2 = (-b - Math.sqrt(b*b - 4*a*c)) / (2.0 * a)
  25.     def array = [x1, x2].asImmutable()
  26.     return array
  27. }
  28. // 실행 시작 지점
  29. if (args.length > 0 && (args[0].equals("-h") || args[0].equals("-help"))) {
  30.     printUsing()
  31.     System.exit(1)
  32. }
  33. def values = findQuadraticRoot(1.0, -1.0, -1.0)
  34. def x1 = values[0]
  35. def x2 = values[1]
  36. if (x1 >= x2) {
  37.     println("The bigger root is " + x1 + ", ")
  38.     println("and the less root is " + x2 + ".")
  39. }
  40. else {
  41.     println("The bigger root is " + x2 + ", ")
  42.     println("and the less root is " + x1 + ".")
  43. }



실행> groovy testGoldenRatio.groovy
The bigger root is 1.618033988749895,
and the less root is -0.6180339887498949.




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,

다음은  이차방정식 x^2 - x - 1  = 0 의 양의 근 즉 황금비율(golden ratio)을 구하는 자바 애플리케이션 소스이다. 황금비율을 구하는 비례방정식은   1 : x = x : (x+1) 이며, 이를 이차방정식으로 표현한 것이 x^2 - x - 1  = 0 이다.

See:  Golden ratio - Sajun.org

  1. /*
  2.  *  Filename: TestGoldenRatioApp.java
  3.  *    황금률(즉, 이차방정식 x^2 - x - 1  = 0 의 양의 근)을 계산한다.
  4.  *
  5.  *   Compile: javac -d . TestGoldenRatioApp.java
  6.  *
  7.  *   Execute: java TestGoldenRatioApp
  8.  *
  9.  *      Date:  2008/03/24
  10.  *    Author:  PH Kim   [ pkim (AT) scripts.pe.kr ]
  11.  */
  12. import java.util.ArrayList;
  13. public class TestGoldenRatioApp {
  14.     public static void printUsing() {
  15.         System.out.println("Using: java TestGoldenRatioApp [-h|-help]");
  16.         System.out.println("This calculates the value of the golden ratio.");
  17.     }
  18.     // 이차방정식 a x^2 + b x + c  = 0 의 근을 구한다.
  19.     public ArrayList<Double> findQuadraticRoot(double a, double b, double c) {
  20.         double x1, x2;
  21.         if (a == 0.0) {
  22.             throw new RuntimeException("Since the highest coefficient is zero, the given equation is not a quadratic equation.");
  23.   }
  24.         else if (b*b - 4*a*c < 0.0) {
  25.             throw new RuntimeException("Since the discriminant " + (b*b - 4*a*c) + " is negative, the given equation has no real root.");
  26.   }
  27.         x1 = (-b + Math.sqrt(b*b - 4*a*c)) / (2.0 * a);
  28.         x2 = (-b - Math.sqrt(b*b - 4*a*c)) / (2.0 * a);
  29.         ArrayList<Double> array = new ArrayList<Double>();
  30.         array.add(new Double(x1));
  31.         array.add(new Double(x2));
  32.         return array;
  33.     }
  34.     public static void main(String[] args) {
  35.        TestGoldenRatioApp app = new TestGoldenRatioApp();
  36.         if (args.length > 0 && (args[0].equals("-h") || args[0].equals("-help"))) {
  37.             app.printUsing();
  38.             System.exit(1);
  39.         }
  40.         ArrayList<Double> values = app.findQuadraticRoot(1.0, -1.0, -1.0);
  41.         double x1, x2;
  42.         x1 = values.get(0).doubleValue();
  43.         x2 = values.get(1).doubleValue();
  44.         if (x1 >= x2) {
  45.             System.out.println("The bigger root is " + x1 + ", ");
  46.             System.out.println("and the less root is " + x2 + ".");
  47.         }
  48.         else {
  49.             System.out.println("The bigger root is " + x2 + ", ");
  50.             System.out.println("and the less root is " + x1 + ".");
  51.         }
  52.     }
  53. }



컴파일> javac -d . TestGoldenRatioApp.java

실행> java TestGoldenRatioApp
The bigger root is 1.618033988749895,
and the less root is -0.6180339887498949.




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,
현재 시각을 컨솔에 보여주는 간단한 애플리케이션의 Lua 언어 소스 코드이다.
UTC란 1970년 1월 1일 0시 0분 0초를 기준으로 하여 경과된 초 단위의 총 시간을 의미한다.
* UTC(Universal Time  Coordinated, 협정세계시, 協定世界時)


  1. --[[
  2.    Filename: testCTime.lua
  3.    Execute: lua testCTime.lua
  4. --]]
  5. -- See http://www.lua.org/manual/5.1/manual.html#pdf-os.clock
  6. weekNames = { "일", "월", "화", "수", "목", "금", "토" }
  7. cNow = os.date("*t")
  8. -- 1970년 1월 1일 0시 0분 0초부터 시작하여 현재까지의 초
  9. print("UTC: " .. os.time(cNow) .. "초")
  10. -- 현재 시각 표시: 200x년 x월 xx일 (x요일) xx시 xx분 xx초
  11. io.write(cNow["year"] .. "년 " .. cNow["month"] .. "월 " .. cNow["day"] .. "일 ")
  12. io.write("(" .. weekNames[cNow["wday"]] .. "요일) ")
  13. io.write(cNow["hour"] .. "시 " .. cNow["min"] .. "분 " .. cNow["sec"] .. "초")
  14. print()
  15. -- 1월 1일은 1, 1월 2일은 2
  16. -- Time.now.isdat == false 이면, 서머타임 없음
  17. strIsDST = "안함"
  18. if cNow["isdst"] then
  19.     strIsDST = "함"
  20. end
  21. print("올해 몇 번째 날: " .. cNow["yday"] .. ", 서머타임 적용 여부: " .. strIsDST)



실행> lau testCTime.lua
UTC: 1206325100초
2008년 3월 24일 (월요일) 11시 18분 20초
올해 몇 번째 날: 84, 서머타임 적용 여부: 안함




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,
현재 시각을 컨솔에 보여주는 간단한 애플리케이션의 Ruby 언어 소스 코드이다.
UTC란 1970년 1월 1일 0시 0분 0초를 기준으로 하여 경과된 초 단위의 총 시간을 의미한다.
* UTC(Universal Time  Coordinated, 협정세계시, 協定世界時)


  1. =begin
  2.    Filename: testCTime.rb
  3.    Execute: ruby testCTime.rb
  4. =end
  5. def println(s)
  6.     print("#{s}\n")
  7. end
  8. weekNames = [ "일", "월", "화", "수", "목", "금", "토" ]
  9. cNow = Time.now
  10. # 1970년 1월 1일 0시 0분 0초부터 시작하여 현재까지의 초
  11. println("UTC: %d초" % cNow.to_i)
  12. # 현재 시각 표시: 200x년 x월 xx일 (x요일) xx시 xx분 xx초
  13. println("%d년 %d월 %d일 (%s요일) %d시 %d분 %d초" % [cNow.year, cNow.mon, cNow.day, weekNames[cNow.wday], cNow.hour, cNow.min, cNow.sec] )
  14. # 1월 1일은 1, 1월 2일은 2
  15. # Time.now.isdat == false 이면, 서머타임 없음
  16. println("올해 몇 번째 날: %d, 서머타임 적용 여부: %s" % [cNow.yday, cNow.isdst ? "함" : "안함"])



실행> ruby testCTime.rb
UTC: 1206325100초
2008년 3월 24일 (월요일) 11시 18분 20초
올해 몇 번째 날: 84, 서머타임 적용 여부: 안함


실행> jruby testCTime.rb
UTC: 1206325102초
2008년 3월 24일 (월요일) 11시 18분 22초
올해 몇 번째 날: 84, 서머타임 적용 여부: 안함




Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.

Posted by Scripter
,