- 运用了Java
lambda
表达式
- 简单版本,仅供参考
import java.util.function.UnaryOperator;
public class DefiniteIntegral {
private UnaryOperator<Double> function;
private DoubleRange range;
private int precision;
public DefiniteIntegral(UnaryOperator<Double> function, DoubleRange range, int precision) {
this.function = function;
this.range = range;
this.precision = precision;
}
public static DefiniteIntegral create(UnaryOperator<Double> function, DoubleRange range, int precision) {
return new DefiniteIntegral(function, range, precision);
}
private Double getFunctionVal(double x) {
return function.apply(x);
}
private double getEachSize() {
return range.getRange() / precision;
}
private double getξ(double val) {
return ((2 * val) + getEachSize()) / 2;
}
public double calculateArea() {
double result = 0.0;
double eachSize = getEachSize();
for (double i = range.getStart(); i < range.getEnd(); i += eachSize) {
result += eachSize * getFunctionVal(getξ(i));
}
return result;
}
public static void main(String[] args) {
UnaryOperator<Double> function = x -> x + 1;
DoubleRange range = DoubleRange.create(5, 9);
int precision = 10000;
DefiniteIntegral functionArea = DefiniteIntegral.create(function, range, precision);
System.out.println(functionArea.calculateArea());
}
private static class DoubleRange{
private double start;
private double end;
public static DoubleRange create(double start, double end) {
return new DoubleRange(start, end);
}
public DoubleRange(double start, double end) {
this.start = start;
this.end = end;
}
public double getRange() {
return end - start;
}
public double getStart() {
return start;
}
public double getEnd() {
return end;
}
}
}