定积分
import static java.lang.Math.*;
public class homeworkfour {
// 0~1区间n等分
private static int n = 100000;
// 随便定义个曲线e的x次方, 取其x在0~1的定积分;
public static double f(double x) {
double f;
f = pow(E, x);
return f;
}
// 梯形法求定积分
/**
* x0: 坐标下限, xn: 坐标上限
*/
public static double getDefiniteIntegralByTrapezium(double x0, double xn) {
double h = abs(xn - x0) / n;
double sum = 0;
for (double xi = 0; xi <= xn; xi = xi + h) {
sum += (f(xi) + f(xi + h)) * h / 2;
}
return sum;
}
/**
* x0: 坐标下限, xn: 坐标上限
*/
// 矩形法求定积分, 右边界
public static double getDefiniteIntegralByRectangle1(double x0, double xn) {
//h: 步长
double h = abs(xn - x0) / n;
double sum = 0;
for (double xi = 0; xi <= xn; xi = xi + h) {
sum += f(xi + h) * h;
}
return sum;
}
// 矩形法求定积分, 左边界
public static double getDefiniteIntegralByRectangle2(double x0, double xn) {
double h = abs(xn - x0) / n;
double sum = 0;
for (double xi = 0; xi <= xn; xi = xi + h) {
sum += f(xi) * h;
}
return sum;
}
/**
* 测试定积分
*/
public static void main(String[] args) {
System.out.println(getDefiniteIntegralByTrapezium(0, 1));
System.out.println(getDefiniteIntegralByRectangle1(0, 1));
System.out.println(getDefiniteIntegralByRectangle2(0, 1));
}
}
最普通的定积分程序
public class Calculation { //主类
private static double f(double x) { //被积函数为f(x)=x*x
return x * x;
}
private static double integral(double a, double b, int n) { // 数值积分函数
double dx = (b - a) / n; // dx 为把区间[a,b]平均分为n份后每一个小区间的长度
double sum = 0.0; // 用于计算累加值的变量
for (int i = 0; i < n; ++i) {
double x = a + i * dx; //每一个小区间的左端点的x坐标
double s = f(x) * dx; // 用小区间左端点为小长方形的高,dx为底边长,f(x)*dx就是小长方形的面积
sum = sum + s; // 累加所有的小长方形的面积
}
return sum; // 返回累加值
}
public static void main(String[] args) {
double a = 1.0; // a 是积分区间的左端点
double b = 2.0; // b 是积分区间的右端点
int n = 10000; // n 是把积分区间分割的份数
double integ = integral(a, b, n); // 调用数值积分函数
System.out.printf("The integral is %14.10f\n", integ); // 输出
}
}
求定积分?请详细介绍!