Created
November 2, 2015 23:08
-
-
Save poseidon4o/877842fd2b252513e2fb to your computer and use it in GitHub Desktop.
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 <cmath> | |
#include <iostream> | |
using namespace std; | |
const double eps = 0.000001; | |
int signof(double x) { | |
return x == 0 ? 0 : (x > 0 ? 1 : -1); | |
} | |
double root(int k, int n) { | |
double guess = k / n; | |
double err = 0.; | |
double step = 1; | |
int lastSign = 1; | |
do { | |
err = pow(guess, n) - k; | |
if (signof(err) != lastSign) { | |
step *= 0.75; | |
lastSign = -lastSign; | |
} | |
if (err > 0) { | |
guess *= 1/(1 + step); | |
} else { | |
guess *= (1 + step); | |
} | |
} while (fabs(err) > eps); | |
return guess; | |
} | |
bool eq(double a, double b) { | |
return fabs(a - b) < eps; | |
} | |
int main() { | |
for (int c = 100; c < 1000; c++) { | |
for (int r = 2; r < 5; ++r) { | |
double mroot = root(c, r); | |
double rroot = pow(c, 1.0 / (double)r); | |
cout << "root(" << c << "," << r << ") = " << mroot << " -> " << rroot << endl; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment