Skip to content

Instantly share code, notes, and snippets.

@PtrMan
Last active March 27, 2018 00:33
Show Gist options
  • Select an option

  • Save PtrMan/2d5793bec221b4fc74482dff88058ca6 to your computer and use it in GitHub Desktop.

Select an option

Save PtrMan/2d5793bec221b4fc74482dff88058ca6 to your computer and use it in GitHub Desktop.
D Math
// https://de.wikipedia.org/wiki/Bin%C3%A4re_Exponentiation#Pseudocode_(Algorithmus)
double powi(double v, int pow) {
double res = 1;
// we just use the 8 bit
for(int i=7;i>=0;i--) {
res = res*res;
//if( pow & (1 << i) )
// res = res * v;
// jump free version of the above code
int a = (pow >> i) & 1;
res *= ((a*v) + ((1-a)*1));
}
return res;
}
// see https://en.wikipedia.org/wiki/Nth_root_algorithm
double nthRoot(double v, int n, double epsilon = 0.000001) {
import std.math : abs, sqrt;
double x = sqrt(v);
for(;;) {
double delta = (1.0/n) * (powi(x, n-1) - x);
x += delta;
if( abs(delta) < epsilon ) break;
}
return x;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment