Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Overflow for Intermediate Results

Status
Not open for further replies.

zytryt

Instructor
Feb 27, 2003
5
US
I am wondering why the following code works:

double x,y,z,w,v;
x = 2.0e300;
y = 1.0e300;
z = 1.0e300;
w = 1.0e300;
v = (x*y)/(z*w);
cout << &quot;v = &quot; << v << endl << endl;

The correct answer of 2 prints out. However, both numerator and denominator exceed the range of double, which is approximately 10 to the 308 power.

Why isn't there an overflow error on the intermediate results? Either a runtime error should occur or the final result should be nonsense instead of 2.

Thanks.
 
While calculations are being performed within the processor itself, floating point numbers are stored in 'long double' format.

long double has a max exponent of 4932 compared to the 308 of a double, so the intermediate results of 2.0e600 is well within range. When the calculation is complete, the long double is converted back to a double, which is no problem since the result is back in range of a double.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top