Skip to content

Instantly share code, notes, and snippets.

@socantre
Created February 12, 2015 17:09
Show Gist options
  • Save socantre/a50de33b16cb51d00384 to your computer and use it in GitHub Desktop.
Save socantre/a50de33b16cb51d00384 to your computer and use it in GitHub Desktop.
newton
#include <iostream>
#include <random>
#include <cassert>
#include <cstdint>
template< typename T, typename F, typename DF >
T newton(T x, F f, DF df)
{
using std::abs;
T y = f(x);
while (abs(y) > static_cast< T >(1.0e-12))
{
x = x - y / df(x);
y = f(x);
}
return x;
}
int main() {
double n = 69;
std::cout << std::sqrt(n) << '\n';
std::cout << newton(8., [=](double x) { return x*x - n; }, [](double x) { return 2.*x; }) << '\n';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment