19.9 Precision and Speed

I l @ ve RuBoard

A variable of type double has about twice the precision of a normal float variable. Most people assume that double-precision arithmetic takes longer than single-precision. This is not always the case. Let's assume we have one of the older compilers that does everything in double .

For the equation:

 float answer, number1, number2;  answer = number1 + number2; 

C++ must perform the following steps:

  1. Convert number1 from single to double precision.

  2. Convert number2 from single to double precision.

  3. Double-precision add.

  4. Convert result into single precision.

  5. Store the result in answer.

If the variables were of type double , C++ would have to perform only the following steps:

  1. Double-precision add.

  2. Store result in answer.

As you can see, the second form is a lot simpler, requiring three fewer conversions. In some cases, converting a program from single precision to double precision makes it run faster .

Because C++ specifies that floating point can be done in double or float , you can't be sure of anything. Changing all float s into double s may make the program run faster, slower, or the same. The only thing you can be sure of when using floating point is that the results are unpredictable.

Many computers, including the PC and Sun/3 series machines, have a special chip called a floating-point processor that does all the floating-point arithmetic. Actual tests using the Motorola 68881 floating-point chip (which is used in the Sun/3) and floating point on the PC show that single precision and double precision run at the same speed.

I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net