Created
February 12, 2015 17:09
-
-
Save socantre/a50de33b16cb51d00384 to your computer and use it in GitHub Desktop.
newton
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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