Skip to content

Instantly share code, notes, and snippets.

@rayheberer
Created June 3, 2017 16:48
Show Gist options
  • Save rayheberer/d853ae5484607caea07e7bdea3014c74 to your computer and use it in GitHub Desktop.
Save rayheberer/d853ae5484607caea07e7bdea3014c74 to your computer and use it in GitHub Desktop.
function that takes an arbitrary amount of numerics and returns a continued fraction (a + 1/(b+1/(c+...))) with a, b, c... being the order in which the arguments are passed into the function
# Use Reduce() to write a function for generating continued fractions. For example continued_fraction(4, 2, 6, 7) should return 4.462366.
continued_fraction = function(...) {
input.vector = as.numeric(c(...)) #since Reduce() acts on vectors, the arguments are first joined as a vector
return(Reduce(function(a,b) b + 1/a, rev(input.vector))) #rev() to reverse the order of the vector, so that the binary operation will work as intended
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment