Skip to content

Instantly share code, notes, and snippets.

@nikhedonia
Last active November 9, 2018 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nikhedonia/70c349505d1d19a9ce10a5688bc7dbfa to your computer and use it in GitHub Desktop.
Save nikhedonia/70c349505d1d19a9ce10a5688bc7dbfa to your computer and use it in GitHub Desktop.
template<class TestF class Map>
auto golden(TestF test, Map f) {
  int a = 0;
  int b = 1;
  double ratio = 1;
 
  while (1) {
  tie(a, b) = tuple{b, a+b};
  auto delta = b/(double)a - ratio;
  ratio = b/(double)a;
  if (test(delta, ratio, a, b)) 
  return f(abs(delta), ratio, a, b);
  }
}
}
int main() {
  auto test = [i=0](auto delta, …) mutable {
  if (++i>100 || delta<0.0001)
  return true;
 
  cout << ratio <<endl;
  return false;
  };
 
auto map = [](auto, auto, auto a, auto b) {
  return tuple{b, a};
  };
 
  auto [b, a] = golden(test, map);
 cout << b << a << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment