Last active
February 23, 2019 07:57
-
-
Save IanBoyanZhang/d2fe783e8bffbd43bdfc08627718f9c3 to your computer and use it in GitHub Desktop.
Newton Raphson solving x + log2(x) = 0
This file contains hidden or 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 <cmath> | |
// Newton Raphson solving x + log2(x) = 0 | |
// https://en.wikipedia.org/wiki/Newton%27s_method | |
inline double func(double x) { | |
return x + log2(x); | |
} | |
inline double derv(double x) { | |
return 1 + log2(exp(1)) * 1/x; | |
} | |
inline double eval(double x, double y) { | |
return y - func(x); | |
} | |
int main(int argc, char **argv) { | |
const size_t iterations = 100; | |
const double y = 0; | |
const double thres = 0.0001; | |
// initial guess | |
double x_0 = 0.01; | |
double x = x_0; | |
for (size_t i = 0; i < iterations; i+=1) { | |
x = x - func(x)/derv(x); | |
if(eval(x, y) < thres) { | |
break; | |
} | |
std::cout << "x: " << x << std::endl; | |
} | |
std::cout << "res: " << x << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment