How to get goldenRatio using recursion in Java?

I am working on this simple java recursion problem, given the following areas:

  • Calculate the golden ratio.

  • Given two numbers a and b with a> b> 0, the ratio b / a.

I did some code, but I was stuck with making recursion work correctly. Here is my code:

public class MyTesting { public static void main(String[] args) { System.out.println(ratio(8 , 4)); } public static double ratio(int a, int b) { int goldelRatio = 0; if(a > b && b > 0){ return goldelRatio = a / b; } return goldelRatio; } } 
+5
source share
3 answers

How about something like this:

 double goldenRatio(double a, double b, double epsilon) { if(Math.abs((b / a) - ((a + b) / b)) < epsilon) { return ((a + b) / b); } else { return goldenRatio(b, a + b, epsilon); } } 

This way you achieve what you need in one function, with epsilon deciding how good the resolution will be.

Also as an added bonus, and although Java does not (at the time of writing this, at least) optimize tail recursion, theoretically this function can be optimized by tail recursion.

hard coded epsilon example:

 double goldenRatio(double a, double b) { double epsilon = 0.00001; if(Math.abs((b / a) - ((a + b) / b)) < epsilon) { return ((a + b) / b); } else { return goldenRatio(b, a + b); } } 

run example:

 public static void main(String[] args) { double goldenRation1 = goldenRatio(1.0, 1.0); System.out.println(goldenRation1); // prints 1.618032786885246 System.out.println(goldenRation1 > 1.61800 && goldenRation1 < 1.61806); // prints true double goldenRation2 = goldenRatio(100.0, 6.0); System.out.println(goldenRation2); // prints 1.6180367504835589 System.out.println(goldenRation2 > 1.61800 && goldenRation2 < 1.61806); // prints true } 
+5
source

You do not have a recursive function, a recursive function that calculates the Gold coefficient will look like the one shown below.

 private int MAX_COUNTER = 50; private int count = 0; public double ratio(double a, double b) { count++; double goldenRatio = b / a; if (count < MAX_COUNTER) { return ratio(b, a + b); } return goldenRatio; } 

NOTE. I put counters because, given that this is a recursive function trying to find a number with infinite decimal places, this will cause the JVM to switch to StackOverflow :), so we had to stop it sooner or later.

+2
source

Recursion basically means methods that call themselves, which means you should try something like this:

 public double recursionMethod(int a, int b){ int c = a+b; if(Math.abs(ratio(b,a)-ratio(c,b))< (double) 1/42) return ratio(c,b); else return recursionMethod(b,c); } 

1/42 is your accuracy, you can implement any other violation that you like. Call this method mainly with arguments (1,1).

+1
source

Source: https://habr.com/ru/post/1241474/


All Articles