Skip to content

Instantly share code, notes, and snippets.

@LuxXx
Last active May 12, 2017 14:12
Show Gist options
  • Save LuxXx/901e7896109ab3645916f66021268143 to your computer and use it in GitHub Desktop.
Save LuxXx/901e7896109ab3645916f66021268143 to your computer and use it in GitHub Desktop.
A method to calculate the value of a continued fraction
public class ContinuedFractions {
public static void main(String[] args) {
double[] e_cf = {2,1,2,1,1,4,1,1,6,1,1,8,1,1,10,1,1,12,1,1,14};
System.out.println(cf(e_cf));
System.out.println(Math.E);
}
// optionally pass the index value and do not copy the tail array every time
public static double cf(double... d) {
if (d.length == 0) return 0;
if (d.length == 1) return d[0];
return d[0] + 1 / cf(tail(d));
}
public static double[] tail(double... array) {
if (array.length <= 1) throw new Error("This array has no tail");
double[] tail = new double[array.length - 1];
for (int i = 1; i < array.length; i++) {
tail[i - 1] = array[i];
}
return tail;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment