// A program that explores floating point arithmetic in the IEEE // floating point standard. The source code is SourcesOfError.C. #include #include int main() { float xs, ys, zs, ws; // Some single precision variables. double yd; // A double precision variable. xs = 204.; // Take an exponential that is out of range. ys = exp(xs); cout << "The single precision exponential of " << xs << " is " << ys << endl; yd = exp ( xs ); // In double precision, it is in range. cout << "The double precision exponential of " << xs << " is " << yd << endl; zs = xs / ys; // Divide a normal number by infinity. cout << xs << " divided by " << ys << " gives " << zs << endl; ws = ys; // Divide infinity by infinity. zs = ws / ys; cout << ws << " divided by " << ys << " gives " << zs << endl; zs = sqrt( -1.) ; // sqrt(-1) should be NaN. cout << "sqrt(-1.) is " << zs << endl; ws = xs + zs; // Add NaN to a normal number. cout << xs << " + " << zs << " gives " << ws << endl; xs = sin(1.); // Some generic single precision numbers. ys = 100. *sin(2.); zs = 10000.*sin(3.); float xsPys, ysPxs, xsPzs, zsPxs; // xsPzx holds xs + zs, etc. xsPys = xs + ys; ysPxs = ys + xs; // Try commuting pairs. xsPzs = xs + zs; zsPxs = zs + xs; if ( ( xsPys == ysPxs ) && ( xsPzs == zsPxs ) ) cout << "Adding " << xs << " " << ys << " and "<< zs << " in pairs commutes." << endl; else cout << "Adding " << xs << " " << ys << " and "<< zs << " in pairs does not commute." << endl; float xsPysPzs, ysPzsPxs; // Test for associativity. xsPysPzs = ( xs + ys ) + zs; ysPzsPxs = ( ys + zs ) + xs; if ( xsPysPzs == ysPzsPxs ) cout << "Adding " << xs << " " << ys << " and "<< zs << " is associative." << endl; else cout << "Adding " << xs << " " << ys << " and "<< zs << " is not associative." << endl; int xi, yi; // Some integer variables. xi = 9; // Compute the quotient using integer yi = 10; // and floating point arithmetic. zs = xi/yi; ws = ( (float) xi ) / ( (float) yi ); // Convert, then divide. cout << "Integer division of " << xi << " by " << yi << " gives " << zs << ". Floating point gives " << ws << endl; return(0); }