Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add nth root function #13

Merged
merged 1 commit into from
Aug 28, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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