11.07.2015 Views

tYSR20

tYSR20

tYSR20

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

52 Part I: Introduction to C++ Programminggoing to make any use of it. Because of this limitation, be careful when youuse comparison operators on floating-point numbers. Consider the followingexample:float f1 = 10.0;float f2 = f1 / 3;f1 == (f2 * 3.0);// are these two equal?The comparison in the preceding example is not necessarily true. A floatingpointvariable cannot hold an unlimited number of significant digits. Thus, f2is not equal to the number we’d call “three-and-a-third,” but rather to 3.3333...,stopping after some number of decimal places.A float variable supports about 6 digits of accuracy while a double supports13 digits. I say “about” because the computer is likely to generate anumber like 3.3333347 due to vagaries in floating point calculations.Now, in pure math, the number of threes after the decimal point is infinite —but no computer built can handle infinity. So, after multiplying 3.3333 by 3, youget 9.9999 instead of the 10 you’d get if you multiplied “three-and-a-third” —in effect, a round-off error. Such small differences may be unnoticeable to aperson, but not to the computer. Equality means exactly that — exact equality.Modern processors are very sophisticated in performing such calculations.The processor may, in fact, accommodate the round-off error, but from insideC++, you can’t predict exactly what any given processor will do.Problems can arise even in a straightforward calculation, such as the following:float f1 = 10.0;float f2 = 100 % 30;f1 == f2;// are these two equal?Theoretically, f1 and f2 should be equal (after you apply that percentlikeoperator that Chapter 3 identifies as modulus). There doesn’t appear to beany problem with round off. So far. But you can’t be sure — you have no ideahow the computer that eventually runs your program is going to representfloating-point numbers internally. To flatly claim that there’s no round-offerror lurking here makes unwarranted assumptions about CPU internals.The safer comparison is as follows:float f1 = 10.0;float f2 = f1 / 3;float f3 = f2 * 3.0;(f1 - f3) < 0.0001 && (f3 - f1) < 0.0001;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!