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);
source share