Last active
March 27, 2018 00:33
-
-
Save PtrMan/2d5793bec221b4fc74482dff88058ca6 to your computer and use it in GitHub Desktop.
D Math
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
| // 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