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