1. Computing

C++ Tutorial - Lesson One Learning How to Compile With Visual C++ 2005

By

6 of 8

Precision Arithmetic

Double Trouble

There's no long float, but there is a double type that is twice as big as float.
  • Float: Occupies 4 bytes. Range 1.175494351×10-38 to ±3.4028235×1038
  • Double: Occupies 8 bytes. Range 2.2250738585072020×10-308 to ±1.7976931348623157×10308
Unless you're doing scientific programming with very large or small numbers, you'll only use doubles for greater precision. Floats are good for 6 digits of accuracy but doubles offer 15.

Precision

Consider 567.8976523. It appears a valid float value. But if we print it out with this code below you can see lack of precision appearing. The number has 10 digits but is being stored in a float variable with only six digits of precision. I've used the older printf to show the formatting.

 float value= 567.8976523;
 printf( value) ;
 

The function printf() outputs text to the screen. We'll look at it in detail later on in this lesson.

It prints as 567.897644042969. Quite a difference! Now move the decimal point two to the left so the value is 5.678976523 and rerun the program. This time it outputs 5.67897653579712. This is more accurate but still different.

If you count the digits that are the same in both sets of numbers, you can see that after 7 or 8 digits, the numbers differ. I've added a space and padded with 0s to highlight the differences.

  • 567.8976 52300000
  • 567.8976 44042969
  • 5.6789765 2300000
  • 5.6789765 3579712

Rerun both examples as doubles and it will print both exactly as defined.

On the next page : Learn about computer arithmetic.

  1. About.com
  2. Computing
  3. C / C++ / C#
  4. C++ Programming
  5. Learn C++ Programming
  6. All about Precision in Floats

©2014 About.com. All rights reserved.