Chapter 5 Exercise 23, Introduction to Java Programming, Tenth Edition Y. Daniel
ID: 3780940 • Letter: C
Question
Chapter 5 Exercise 23, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.
*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:
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.
1-n 1-3 1Explanation / Answer
public class Series {
public static void main(String[] args) {
int n = 50000;
double leftSum = 0.0;//For storing left sum
double rightSum = 0.0;//For storing right sum
// Find left sum.
for( int i = 1; i <= n; ++i ){
leftSum += 1.0 / (double) i;
}
// Find right sum.
for( int i = n; i >=1; --i ){
rightSum += 1.0 / (double) i;
}
// Display the two series sums.
System.out.println( "Left sum is : " + leftSum );
System.out.println( "Right sum is : " + rightSum );
if(leftSum>rightSum)
{
System.out.println( "Left sum is greater than Right sum");
}
else
{
System.out.println( "Right sum is greater than Left sum");
}
}
}
===================================================================
Output:
akshay@akshay-Inspiron-3537:~/Chegg$ javac Series.java
akshay@akshay-Inspiron-3537:~/Chegg$ java Series
Left sum is : 11.397003949278504
Right sum is : 11.397003949278519
Right sum is greater than Left sum
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.