Skip to content

Instantly share code, notes, and snippets.

@Techcable
Created January 20, 2016 23:29
Show Gist options
  • Select an option

  • Save Techcable/5ce2c9086e03086342b6 to your computer and use it in GitHub Desktop.

Select an option

Save Techcable/5ce2c9086e03086342b6 to your computer and use it in GitHub Desktop.
public class SquareRoot {
/**
* Estimate the sqrt via {@link #superFastSqrt(float)} then refine the accuracy
* <p/>
* Refines the guess onece, which should be 'good enough'
*
* @param d the number to estimate
*/
public static double fastSqrt(double d) {
return increaseAccuracy(guessSqrt(d), 1);
}
/**
* Estimate the sqrt via {@link #superFastSqrt(float)} then refine the accuracy
* <p/>
* Should be faster than {@link Math#sqrt(double)} with only one or two rounds of accuracy
*
* @param d the number to estimate
* @param accuracy the number of times to refine the guess
*/
public static double fastSqrt(double d, int accuracy) {
return increaseAccuracy(guessSqrt(d), accuracy);
}
/**
* Guess the sqrt of the given number
* <p/>
* Uses the <href a=https://en.wikipedia.org/wiki/Fast_inverse_square_root>bit-shifting hack</href> from Quake 3
*
* @param f the number to calculate
* @return the aproxamite sqrt
*/
public static double guessSqrt(double d) {
return guessSqrt((float) d);
}
/**
* Guess the sqrt of the given number
* <p/>
* Uses the <href a=https://en.wikipedia.org/wiki/Fast_inverse_square_root>bit-shifting hack</href> from Quake 3
*
* @param f the number to calculate
* @return the aproxamite sqrt
*/
public static float guessSqrt(float f) {
int i = Float.floatToRawIntBits(f);
i = 0x5f3759df - (i >>> 1)
return Float.intBitsToFloat(i);
}
public static double increaseAccuracy(double d, int accuracy) {
double half = d * 0.5;
for (int i = 0; i < accuracy; i++) {
d *= 1.5 - (half * d * d);
}
return d;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment