/* * ========================================================================= * NumericalErrorConditions.java: This program illustrates Java's capability * in handling error conditions related to: * * 1. Overflow and underflow of numbers (i.e., Infinity and -Infinity), * 2. Arithmetic expressions where the result is not-a-number (i.e., NaN). * * Written By: Mark Austin October, 2007 * ========================================================================= */ import java.lang.Math; public class NumericalErrorConditions { public static void main( String args[] ) { double dA = 0.0; double dB, dC; // Format and print data values .... System.out.printf("dA = %8.3f\n", dA ); // Generate error conditions in arithmetic expressions ... System.out.println("Simulate Error Conditions ... "); System.out.println("============================= "); System.out.printf("Divide by zero: ( 1/0.0) = %8.3f\n", 1.0/dA ); System.out.printf("Divide by zero: (-1/0.0) = %8.3f\n", -1.0/dA ); System.out.printf(" Not a number: (0.0/0.0) = %8.3f\n", dA/dA ); // Generate variables that store error conditions.... System.out.println("Variables that store error conditions ... "); System.out.println("========================================= "); dB = 1.0/dA; System.out.printf("dB = 1.0/dA = %8.3f\n", dB ); dC = dA/dA; System.out.printf("dC = dA/dA = %8.3f\n", dC ); // Test for variables that are assigned error conditions.... System.out.println("Test for variable values containing error conditions ... "); System.out.println("======================================================== "); if( dB == Double.POSITIVE_INFINITY ) System.out.println("*** dB is equal to +Infinity" ); else System.out.println("*** dB is not equal to +Infinity" ); if( dB == Double.NEGATIVE_INFINITY ) System.out.println("*** dB is equal to -Infinity" ); else System.out.println("*** dB is not equal to -Infinity" ); if( dB == Double.NaN ) System.out.println("*** dB is Not a Number" ); else System.out.println("*** dB is a Number" ); // =================================================================== // Now let's see what happens when evaluation of arithmetic expression // inadvertently generates an error. // =================================================================== System.out.println("Evaluate y(x) for range of x values"); System.out.println("==================================="); for ( double dX = 1.0; dX <= 5.0; dX = dX + 0.5 ) { double dY = 1.0 + 1.0/(dX - 2.0) - 1.0/(dX - 3.0) + (dX-4.0)/(dX-4.0); System.out.printf(" dX = %4.1f y(dX) = %8.3f\n", dX, dY ); } System.out.println("==================================="); } }