Friday 19 August 2016

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:

 1+12+13+...+1n1+12+13+...+1n

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 ProgrammingEx5_23 {
 
 public static void main(String[] args) {
   
   final int N = 50000;
   double sumL2R =0, sumR2L = 0;
    
    
   for(int i=1 ; i<=N; i++){
     sumL2R = sumL2R+ 1.0/i;
     sumR2L = sumR2L+ 1.0/(N-i+1);
    
   }
     
  System.out.println("Summation from left to right:" + sumL2R);
  System.out.println("Summation from right to left:" + sumR2L);
 }
 
}

No comments :

Post a Comment