HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Reinventing the Math Functions

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
reinventingfunctionsthemath

Problem

Just for practice in the mathematical side of programming, I decided to rewrite the math functions, with the addition of the root() function, which the Math library does not provide, but can be easily done with Math.pow(x, 1 / y) where you want to find out x to the yth root.

I also wrote this to review the Newton's Method, which works like this:

Given an approximate \$x\$-intercept \$x_n\$, a better estimate \$x_{n+1}\$ is calculated with the following:

$$x_{n+1}=x_n-\frac{f(x_n)}{f'(x_n)}$$

Where \$f(x)\$ is the function to find the \$x\$-intercept, and \$f'(x)\$ is the derivative.

In the case of roots, to find \$\sqrt[z]y\$, \$f(x) = {x_n}^z - y\$, and \$f'(x) = zx^{z-1}\$, resulting in:

$$x_{n+1}=x_n-\frac{{x_n}^z - y}{z{x_n}^{z-1}}$$

```
public class MathUtils {

/**
*
* Returns the given root of the given number.
*
*
*
* Assuming n is the first argument, and m is the
* second argument, the result is n to the mth
* root.
*
*
* @param number
* the number
* @param root
* the root
* @return the result
*
* @see #root(double, long)
*/
public static double root(double number, double root) {
return pow(number, 1 / root);
}

/**
*
* Returns the given root, which is an integer, of the given number.
*
*
*
* This method is very similar to the {@link MathExt#root(double, double)}
* method, but with optimization improvements as the algorithm is different.
*
*
* @param number
* the number
* @param root
* the root
* @return the result
*
* @see #root(double, double)
*/
public static double root(double number, long root) {
double approx = 1;
// x2 = x1 - fx1 / f'x1
// fx1 = x^n - y
// f'x1 = n * x ^ (n - 1)
for (int i = 0; i
* Returns the given power of the given

Solution

Make MathUtils final and give it a private constructor. It should be neither extended nor constructed.

Don't use abbreviations in method names.

Your javadoc needs improvement. You do a reasonable job of explaining what methods do when everything is on the happy path, but you don't discuss error conditions or corner cases at all. For instance, compare your ceil() javadoc to the javadoc for Math#ceil(). Double.MAX_VALUE is significantly larger than Long.MAX_VALUE. The best way to fix it is think of every corner case you can, add unit tests for all of them, and then document what happens. If you don't like what happens, adjust your test to the behaviour you want, document that, and then fix the code to return it. Repeat that for every method you have. Then find a buddy and ask them to read the docs only and tell you what corner cases you didn't mention.

Context

StackExchange Code Review Q#115087, answer score: 3

Revisions (0)

No revisions yet.