解:
package shuzhifenxi;
public class Exam344 {
public static void main(String[] args) {
/*
* 步长h=8/2^(i),i=3,4,5....
* 假设在i=10时,误差小于10^(-5)
*/
for (int i = 3; i <= 10; i++) {
double s = countSqrt(1, 9, 8.0 / Math.pow(2, i + 1))
- countSqrt(1, 9, 8.0 / Math.pow(2, i));
if (judgeError(s)) {
System.out.println("误差小于10^(-5)");
double I = countSqrt(1, 9, 8.0 / Math.pow(2, i + 1)) + 1.0 / 3
* s;
System.out.println("在允许误差内I=" + I);
break;
}
}
}
//复化梯形公式计算I
public static double countSqrt(double lowLimit, double upLimit, double h) {
double s = 0;
for (double i = lowLimit + h; i <= upLimit - h; i = i + h) {
s = s + Math.sqrt(i);
}
double I = h / 2 * (1 + 2 * s + 3);
return I;
}
// 判断误差是否大于10^(-5),如果小于10^(-5)返回true,其他情况返回false
public static boolean judgeError(double a) {
if (Math.abs(a) < Math.pow(10, -5)) {
return true;
} else
return false;
}
}
运行结果: 误差小于10^(-5)
在允许误差内I=17.333333333325616
3.5 试用Romberg算法计算题3.4中的数值积分,起始步长取h=1,数值积分精度要求为10^(-8)
解:
package shuzhifenxi;
public class Exam3552 {
static double array[] = new double[5];
static double [] ary ;
public static void main(String[] args) {
//先计算出分段梯形积分值
for (int i = 0; i < array.length; i++) {
double h = 8.0 / Math.pow(2, i + 3);
array[i] = countSqrt(1, 9, h);
}
System.out.println("分段梯形积分值");
printArray(array);
for(int i=4;i>0;i--){
array = romBerg(i);
System.out.println("第"+(5-i)+"层外推值");
printArray(array);
}
}
public static void printArray(double args[]){
for(int i=0;i<args.length;i++){
System.out.println(args[i]);
}
}
// Romberg算法计算依次向外推的值
public static double [] romBerg(int arrayLength) {
double[] array1 = new double[arrayLength];
ary = array;
for (int i = 1; i <= arrayLength; i++) {
array1[i - 1] = (Math.pow(4, 5 - arrayLength) * ary[i] - ary[i - 1])
/ (Math.pow(4, 5 - arrayLength) - 1);
}
return array1;
}
//复化梯形公式计算I
public static double countSqrt(double lowLimit, double upLimit, double h) {
double s = 0;
for (double i = lowLimit + h; i <= upLimit - h; i = i + h) {
s = s + Math.sqrt(i);
}
double I = h / 2 * (1 + 2 * s + 3);
return I;
}
}
运行结果:
分段梯形积分值
17.306000526035717
17.326419818057353
17.331599222819534
17.332899431778884
17.333224834297017
第1层外推值
17.333226248731233
17.333325691073593
17.333332834765333
17.333333301803062
第2层外推值
17.333332320563084
17.33333331101145
17.333333332938913
第3层外推值
17.333333326732852
17.333333333286966
第4层外推值
17.33333333331267
h | 分段梯形积分值 | 第1层外推值 | 第2层外推值 | 第3层外推值 | 第4层外推值 |
1 | 17.306000526035717 | ||||
1/2 | 17.326419818057353 | 17.333226248731233 | |||
1/4 | 17.331599222819534 | 17.333325691073593 | 17.333332320563084 | ||
1/8 | 17.332899431778884 | 17.333332834765333 | 17.33333331101145 | 17.333333326732852 | |
1/16 | 17.333224834297017 | 17.333333301803062 | 17.333333332938913 | 17.333333333286966 | 17.33333333331267 |
第四层外推值和第三层外推值的误差为:
|17.333333333286966-17.33333333331267|=0.00000000002571<10^(-8)
取17.33333333331267作为数值积分结果是满足精度要求的