I wish to calculate limits (calculus) with Java. I have the following class Limit
that can calculate limits:
package calculus;
public final class Limit {
private Limit() {
}
public static final double limit(Function function, double approach) {
double below = Limit.limitFromBelow(function, approach);
double above = Limit.limitFromAbove(function, approach);
return below == above ? below : Double.NaN;
}
public static final double limitFromBelow(Function function, double approach) {
for (double d = approach - 10; d <= approach; d = approach
- ((approach - d) / 10)) {
if (function.apply(d) == Double.POSITIVE_INFINITY) {
return Double.POSITIVE_INFINITY;
} else if (function.apply(d) == Double.NEGATIVE_INFINITY) {
return Double.NEGATIVE_INFINITY;
} else if (Double.isNaN(function.apply(d))) {
return function.apply(approach + ((approach - d) * 10));
} else {
if (d == approach) {
return function.apply(d);
} else if (approach - d < 0.00000000001) {
d = approach;
}
}
}
return Double.NaN;
}
public static final double limitFromAbove(Function function, double approach) {
for (double d = approach + 10; d >= approach; d = approach
- ((approach - d) / 10)) {
if (function.apply(d) == Double.POSITIVE_INFINITY) {
return Double.POSITIVE_INFINITY;
} else if (function.apply(d) == Double.NEGATIVE_INFINITY) {
return Double.NEGATIVE_INFINITY;
} else if (Double.isNaN(function.apply(d))) {
return function.apply(approach + ((approach - d) * 10));
} else {
if (d == approach) {
return function.apply(d);
} else if (d - approach < 0.00000000001) {
d = approach;
}
}
}
return Double.NaN;
}
}
However, I was wondering: Is there another way to calculate limits other than exhaustion and recursive testing? Is there a more efficient method?
Your technique is called numerical approximation of a limit. It is widely used, simple to implement, and generally good enough for many applications. It is easy to use because all you need is a function that you can evaluate in order to apply it.
If you want another way, it is called symbolic or algebraic calculation of limits. In this case, you need to have more information than just the capability to evaluate an unknown function. You need to have an entire parse tree expression for a function including an indication of the independent variable. This is more than just the capability to evaluate the function at a given point. One example of this in Python is shown here:
http://scipy-lectures.github.io/advanced/sympy.html#limits
The symbolic style uses real math rules similar to how you might work out the limit by hand using rules of algebra or calculus.