-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCancellationError.java
More file actions
40 lines (37 loc) · 1.21 KB
/
Copy pathCancellationError.java
File metadata and controls
40 lines (37 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/* Exercise 5.23
* (Demonstrate cancellation errors) A cancellation error occurs when you are
manipulating a very large number with a very small number. The large number
may cancel out the smaller number. For example, the result of 100000000.0 +
0.000000001 is equal to 100000000.0 . To avoid cancellation errors and obtain
more accurate results, carefully select the order of computation. For example, in
computing the following series, you will obtain more accurate results by computing from right to left rather than from left to right:
1 +
1
2
+
1
3
+ c +
1
n
Write a program that compares the results of the summation of the preceding
series, computing from left to right and from right to left with n = 50000
*
*/
public class CancellationError {
public static void main(String[] args) {
// First computation
double sum = 0.0;
for (double i = 1.0 ; i <= 50000; i++) {
sum += 1 /i;
}
// Display results of first computation
System.out.println("Left computation is: " + sum);
// Second computation
for (double i = 50000.0; i <= 1; i--) {
sum += 1/i;
}
// Display results of second computation
System.out.println("Right computation is: " + sum);
}
}