Posted By

DrPepper on 01/08/11


Tagged


Versions (?)

[Java] CH4 floating-point round off error example


 / Published in: Java
 

this programming shows you the example of floating point rounded off error. this error usually happen when you calculate numbers which has long decimal places or so on.

  1. /*
  2.   Give an example of a floating-point roundoff error.
  3.   Would the same expample work corrextly if you used int and awitched to a fuggiciebtly small unit, such as cents insted of dollars, so that the value don't have a fractional part?
  4.  
  5. */
  6.  
  7. public class floatingPoint
  8. {
  9.  
  10. public double number1;
  11. public double number2;
  12.  
  13. public floatingPoint()
  14. {
  15. number1 = 23.30;
  16. number2 = 13.21;
  17.  
  18. }
  19. public static void main(String [] args)
  20. {
  21. floatingPoint sample = new floatingPoint();
  22. double amount = ((sample.number1 + (sample.number2*0.30))/45);
  23. System.out.println("************************************************");
  24. System.out.println();
  25. System.out.println("This is natural amount : ");
  26. System.out.print("Java automatically rounded up : ");
  27. System.out.println(amount);
  28. System.out.print("Caliculator automarically rounded up : ");
  29. System.out.println("0.6058444444444444444444444.......");
  30. System.out.println();
  31. System.out.print("This amount is rounded up (Math.round method) : ");
  32. System.out.println(Math.round(amount));
  33. System.out.println();
  34. System.out.println("This caliculation made a floating-point roundoff error");
  35. System.out.println("Because, as I show, this number should continue to infinity digits of decimal places however, Java compiler automatically rounded up by 16th place.");
  36. System.out.println("***********************************************");
  37. }
  38. }

Report this snippet  

You need to login to post a comment.