프로그래밍/Java
황금비율(golden ratio) 구하기 with Java
Scripter
2008. 3. 24. 15:57
다음은 이차방정식 x^2 - x - 1 = 0 의 양의 근 즉 황금비율(golden ratio)을 구하는 자바 애플리케이션 소스이다. 황금비율을 구하는 비례방정식은 1 : x = x : (x+1) 이며, 이를 이차방정식으로 표현한 것이 x^2 - x - 1 = 0 이다.
See: Golden ratio - Sajun.org
- /*
- * Filename: TestGoldenRatioApp.java
- * 황금률(즉, 이차방정식 x^2 - x - 1 = 0 의 양의 근)을 계산한다.
- *
- * Compile: javac -d . TestGoldenRatioApp.java
- *
- * Execute: java TestGoldenRatioApp
- *
- * Date: 2008/03/24
- * Author: PH Kim [ pkim (AT) scripts.pe.kr ]
- */
- import java.util.ArrayList;
- public class TestGoldenRatioApp {
- public static void printUsing() {
- System.out.println("Using: java TestGoldenRatioApp [-h|-help]");
- System.out.println("This calculates the value of the golden ratio.");
- }
- // 이차방정식 a x^2 + b x + c = 0 의 근을 구한다.
- public ArrayList<Double> findQuadraticRoot(double a, double b, double c) {
- double x1, x2;
- if (a == 0.0) {
- throw new RuntimeException("Since the highest coefficient is zero, the given equation is not a quadratic equation.");
- }
- else if (b*b - 4*a*c < 0.0) {
- throw new RuntimeException("Since the discriminant " + (b*b - 4*a*c) + " is negative, the given equation has no real root.");
- }
- x1 = (-b + Math.sqrt(b*b - 4*a*c)) / (2.0 * a);
- x2 = (-b - Math.sqrt(b*b - 4*a*c)) / (2.0 * a);
- ArrayList<Double> array = new ArrayList<Double>();
- array.add(new Double(x1));
- array.add(new Double(x2));
- return array;
- }
- public static void main(String[] args) {
- TestGoldenRatioApp app = new TestGoldenRatioApp();
- if (args.length > 0 && (args[0].equals("-h") || args[0].equals("-help"))) {
- app.printUsing();
- System.exit(1);
- }
- ArrayList<Double> values = app.findQuadraticRoot(1.0, -1.0, -1.0);
- double x1, x2;
- x1 = values.get(0).doubleValue();
- x2 = values.get(1).doubleValue();
- if (x1 >= x2) {
- System.out.println("The bigger root is " + x1 + ", ");
- System.out.println("and the less root is " + x2 + ".");
- }
- else {
- System.out.println("The bigger root is " + x2 + ", ");
- System.out.println("and the less root is " + x1 + ".");
- }
- }
- }
컴파일> javac -d . TestGoldenRatioApp.java
실행> java TestGoldenRatioApp
The bigger root is 1.618033988749895,
and the less root is -0.6180339887498949.
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.