Skip to content

Commit

Permalink
Merge pull request #13 from jmcwilliams403/main
Browse files Browse the repository at this point in the history
Add nth root function
  • Loading branch information
tommyettinger committed Aug 28, 2022
2 parents ebdc883 + 3e92363 commit 6afa446
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/main/java/com/github/tommyettinger/digital/MathTools.java
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,27 @@ public static float cbrt(float x) {
return x;
}

/**
* The nth root of x, taking advantage of how any nth root can be written as raising x to power of 1/n.
* <br>
* For a detailed description of how this function handles negative roots and roots of negative numbers,
* refer to the documentation for {@link Math#pow(double, double)}.
* <br>
* Additionally, this function aliases results which are extremely close to mathematical integers to actual
* {@code int} values to compensate for any internal precision loss from {@code Math.pow(double, double)}.
*
* @param x a number to find the nth root of
* @param n the degree of the root
* @return a number which, when raised to the power n, yields x
*/
public static float nthrt(final float x, final float n) {
float f = (float) Math.pow(x, 1f / n);
if (Float.isNaN(f) || Float.isInfinite(f))
return f;
int i = round(f);
return isEqual(i, f) ? i : f;
}

/**
* Fast inverse square root, best known for its implementation in Quake III Arena.
* This is an algorithm that estimates the {@code float} value of 1/sqrt(x). It has
Expand Down

0 comments on commit 6afa446

Please sign in to comment.