- 运用了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);
}
/**
* 得到设定的函数的值
* @param x 给定参数
* @return 函数的值
*/
private Double getFunctionVal(double x) {
return function.apply(x);
}
/**
* 得到△X的值
* @return 每个区间的大小, 即△X的值
*/
private double getEachSize() {
return range.getRange() / precision;
}
/**
* 得到一个区间之间的X轴上的随机点
* @param val 区间的左端点
* @return 一个区间之间的X轴上的随机点
*/
private double getξ(double val) {
return ((2 * val) + getEachSize()) / 2;
}
/**
* 计算定积分
* @return 给定函数的定积分
*/
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;
}
}
}
来源:CSDN
作者:淡墨w青衫
链接:https://blog.csdn.net/qq_42254247/article/details/104650398