Golden Ratio Java Program

Golden Ratio Java Program | The number is in the golden ratio when the ratio of F(n+1)/ F(n) limit approached n and extends till infinity that is equal to 1.618. This is also called the golden mean, division proportion, and more.

Let the sequence be X1=1, X2=1 + 1/1, X3=1 + 1/1 + 1/1… in the sequence Xn+1 = 1 + 1/Xn where the n > 0. When we compute the Xn the terms of the sequence get closer and closer to golden ration that is 1.618. Two compute the approximation of the golden ratio we use the recursive formula f(0) = 1, f(n) = 1 + 1/f(n-1) where n > 0.

To write the golden ratio Java program we will see 2 different concepts:-
1) To find the approximation of the golden ratio using the recursive formula.
2) Program to Check whether the two numbers are in the golden ratio or not.

Golden Ratio Java Program Code

Java Program to Find The Approximation of The Golden Ratio Using Recursive Formula

import java.util.Scanner;
public class Main {

   public static double golden(int n) {
      if (n <= 0) {
         return 1;
      }
      return 1.0 + 1.0 / golden(n - 1);
   }

   public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);
      System.out.print("Enter a number: ");
      int n = scan.nextInt();
      System.out.println(golden(n));
      scan.close();
   }
}

Output:-

Enter a number: 5
1.625

Enter a number: 10
1.6179775280898876

Java Program to Check Whether The Two Numbers Are in The Golden Ration Or Not

Golden ratio Java program for two given numbers

public class Main {

   public static Boolean checkGolden(float one, float two) {
      if (one <= two) {
         float temp = one;
         one = two;
         two = temp;
      }

      String ratio1 = String.format("%.3f", one / two);
      String ratio2 = String.format("%.3f", (one + two) / one);

      if (ratio1.equals(ratio2) && ratio1.equals("1.618")) {
         System.out.println("Yes");
         return true;
      } else {
         System.out.println("No");
         return false;
      }
   }

   public static void main(String[] args) {
      float one = 0.618f;
      float two = 1;
      checkGolden(one, two);
   }
}

Output:

Yes

Also see:- Hidden Word Java Program

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published.