C++ float vs double?

Status
Not open for further replies.

derekjr_1

Smack-Fu Master, in training
67
I am learning c++ in school but cant figure this one out. I am pretty sure it is float vs double but not sure. What I want to know is why the output is different with a float and double. I know floats are smaller then doubles but not sure why the output of this problem is diff. Here is the code:


#include <iostream>

using std::cout;
using std::endl;

#include <iomanip>

using std::setprecision;

const double PI = 3.14159265358979;

int main()
{
const float PI = static_cast< float > ( ::pI );

cout << setprecision[ 20 )
<< " Local float value of PI = " << PI
<< "\nGlobal double value of PI = " << ::pI << endl;

return 0;
}



The output in Microsoft Visual c++ is :

Local float value of PI = 3.1415927410125732
Global double value of PI = 3.14159265358979


Why is the output different? Is it the cast operator, or the float? Any help is much appreciated. Thanks
 

derekjr_1

Smack-Fu Master, in training
67
Ok did some experimenting and this is what I come up with. With the same code above if I change the PI = 3.14, the setprecision screws up the FLOAT after setprecsion( 8 ). Anything before 8 will output the same results as the double type. Anyting after 8 will screw up the float and print different reults. Here is some code of this.


#include <iostream>

using std::cout;
using std::endl;

#include <iomanip>

using std::setprecision;

const double PI = 3.14;

int main()
{
const float PI = static_cast< float > ( ::pI );

cout << setprecision[ 7 )
<< " Local float value of PI = " << PI
<< "\nGlobal double value of PI = " << ::pI << endl;

return 0;
}



The output in Microsoft Visual c++ is :

Local float value of PI = 3.14
Global double value of PI = 3.14


#include <iostream>

using std::cout;
using std::endl;

#include <iomanip>

using std::setprecision;

const double PI = 3.14;

int main()
{
const float PI = static_cast< float > ( ::pI );

cout << setprecision[ 8 )
<< " Local float value of PI = " << PI
<< "\nGlobal double value of PI = " << ::pI << endl;

return 0;
}



The output in Microsoft Visual c++ is :

Local float value of PI = 3.1400001
Global double value of PI = 3.14

The only thing changed in these 2 examples is the PI = 3.14 and the setprecision in both to demonstrate where the float gets screwed up in this paticular example. I find it weird how float after a certain point starts losing precision. Anyone know how far floats can generally go, or have I allready answered this question?
 
I find it weird how float after a certain point starts losing precision.
This is because of the binary representation of the decimal numbers, and is a different problem from what you posted above. Someone posted a while ago about why 2 - 1.51 == 0.499999999 (something along those lines anyway). If you want to see the source of the problem for yourself, try to write 3.14 in binary. You'll probably (I haven't tried) find yourself with an infinite expansion, hence the inherent loss in precision if you store that value in any finite-precision binary format.

Also, my docs say floats are considered to have 7-8 significant digits, doubles 15-16, and long doubles 19-20.
 

derekjr_1

Smack-Fu Master, in training
67
Also, my docs say floats are considered to have 7-8 significant digits, doubles 15-16, and long doubles 19-20.

That is what I figured on the floats to be 7-8 significant digits. Like I said when I changed the number to 3.14 and the precision to 7 OR LESS, then the output was correct as the double would display.

I guess I should just remember to not use more than the numbers of precision that a float, double, or long double can handle if I need correct values.

What do you guys do if you need correct values but have more numbers than the type can handle? Should you just print incorrect results, as they could be farely close?
 
What do you guys do if you need correct values but have more numbers than the type can handle? Should you just print incorrect results, as they could be farely close?
It depends on the application. If you really need more precision (financial calculations, rocket science, whatever), you should look into librairies which offer more (or unlimited) precision. You'll have to live with the performance blow however, and the fact that you may have to rewrite a lot of other functions.
 
Often when you know exactly how many decimal places you need, such as financial numbers, it is best to use fixed point numbers, which are just integers where you have to remember how many digits over to move the decimal. I'd be surprised if there weren't 3rd party fixed point number libraries easily available.
If there aren't, it only takes 10 minutes to write your own...
 
Am I right in thinking that in modern computers there's no speed difference in floats vs doubles since they use the same pipeline - the only reason to use floats is smaller storage ?
It also changes the amount of memory bandwith needed... and FP math is very bandwith dependant (just look at how the P4 shines in some benches). Since floats need only half the bandwith that doubles do, they could be up to twice as fast on the same system. Also, when using SIMD instructions, you can usually process twice as many floats as doubles (4 floats and 2 doubles with 128-bit SIMD).

But as far as only the calculations themselves are concerned, you'd be right. IIRC everything is done with 80 bits internally.
If there aren't, it only takes 10 minutes to write your own...
Turbo pascal (and probably Delphi?) seems to have this built in ("currency" type).
 

jbode

Ars Legatus Legionis
11,752
Subscriptor
To understand why there is a difference, you have to understand how floats are laid out in memory. While the exact format will vary, the general form is an encoding of sign * mantissa * 2^exponent.

The only float format I can speak authoritatively about is the old VAX F (single precision) format, but the concepts should extend to other systems. In this case, the layout as follows:

Code:
VAX F

sign bit    exponent  mantissa
   |           |         |
   |    +------+         |
   V    V                V          
  +-+--------+-----------------------+
  | |        |                       |
  +-+--------+-----------------------+

You have bit for sign, 8 bits for exponent (0x00 = -128, 0x80 = 0, 0xFF = 127), and 23 bits for the mantissa. On the VAX, there was always a "hidden" bit that was assumed to be set to 1, giving a 24-bit mantissa in the range [0.5, 1).

Therefore, in VAX F format, 3.14 = 1 * .785 * 2^2.

Remember that in a binary fraction, bit n corresponds to the value 1/2^n, so that bit 1 = 1/2, bit 2 = 1/4, bit 3 = 1/8, etc. Therefore, the binary fraction 1011 = 1/2 + 1/8 + 1/16 = 11/16 = 0.6875.

When you start converting .785 to a binary fraction, you immediately notice that you need considerably more than 24 bits to represent it exactly. So what gets stored is a value that is close to, but not exactly .785. When you add those bits back up again, you'll get something like .7849999.

Since a double has a wider mantissa than a single-precision float (VAX D has a 56-bit mantissa IIRC), you store a value that is much closer to the ideal value, but may still not be exact.

With single-precision floats, you can only trust the first 6 or 7 significant digits of the result. With doubles, you can trust the first 15 or so significant digits. Everything after that is garbage.
 

jbode

Ars Legatus Legionis
11,752
Subscriptor
Originally posted by derekjr_1:
jbode > Wheww!! That is some intense stuff your talking about. At least you sum it up with you can only trust the first 6-7 digits of a float. In Microsoft Visual C++ 6.0 this is 7 digits for a float.

I think I will read your post a few more times and then try to figure this stuff out.

Actually, don't try to figure this out based on what I wrote. I tend to mangle terminology and leave vital stuff out (re-reading my post I see I made a hash of it). I don't do numerical analysis for a living, so the best I can give is a kind of half-assed explanation based on the half-assed understanding I have.

Just remember the following:

1. As a rule, floating-point values cannot be stored exactly. The actual value stored will be a little above or below the ideal value. The degree of precision (or number of trustworthy significant digits) is a function of the number of bits in the mantissa. In C and C++ double gives more precision than float (and in implementations that have it, long double gives even more precision).

2. Use doubles for everything unless you're really tight on memory. There isn't that much of a performance penalty (on most systems, anyway), and the greater precision means that errors won't propagate as quickly.

3. Errors propagate. That little bit of imprecision in the bottom few bits becomes noticable as you multiply values. Unless you're doing serious number crunching with really big or really small numbers you shouldn't have to worry about it too much, but you really don't want to trust more than the first few significant digits in any calculation.

4. Actually, if you are doing any serious number crunching, you won't be using vanilla C and C++ types or libraries at all, but a special-purpose numerical analysis package. Or Fortran.

If you want to explore this some more, here's a program I wrote in C that shows the binary representation of double values (apologies for the lack of documentation; consider it a learning exercise ;-):

Code:
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <math.h>

void doublerep (double x, char **c)
{
    char *a = (char *) &x;
    size_t i, t = 0;

    if (*c)
        free (*c);

    *c = malloc (sizeof x * CHAR_BIT + sizeof x + 1);

    if (*c)
    {
        for (i = sizeof x; i > 0; i--)
        {
            size_t j;

            for (j = CHAR_BIT; j > 0; j--)
            {
                (*c)[t++] = (a[i-1] & (0x01 << (j-1))) == 0 ? '0' : '1';
            }
            (*c)[t++] = ' ';
        }
        (*c)[t] = 0;
    }
}

int main (int argc, char **argv)
{
    int i;

    printf ("val = value\n"
            "man = mantissa value\n"
            "exp = exponent value\n"
            "bin = binary representation\n\n");

    if (argc >= 2)
    {
        for (i = 1; i < argc; i++)
        {
            char *d = NULL;
            double r;

            r = strtod (argv[i], NULL);
            doublerep (r, &d);

            if (d)
            {
                double mant;
                int exp;

                mant = frexp (r, &exp);

                printf ("val: %6g\n", r);
                printf ("man: %6g\n", mant);
                printf ("exp: %6d\n", exp);
                printf ("rep: %s\n\n", d);
            }
        }
    }

    return 0;
}

And some example runs on a Win2K box:

Code:
./double 0.25 0.5 1.0 2.0 4.0 3.0 3.14 3.14159
val = value
man = mantissa value
exp = exponent value
bin = binary representation

val:   0.25
man:    0.5
exp:     -1
rep: 00111111 11010000 00000000 00000000 00000000 00000000 00000000 00000000

val:    0.5
man:    0.5
exp:      0
rep: 00111111 11100000 00000000 00000000 00000000 00000000 00000000 00000000

val:      1
man:    0.5
exp:      1
rep: 00111111 11110000 00000000 00000000 00000000 00000000 00000000 00000000

val:      2
man:    0.5
exp:      2
rep: 01000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000

val:      4
man:    0.5
exp:      3
rep: 01000000 00010000 00000000 00000000 00000000 00000000 00000000 00000000

val:      3
man:   0.75
exp:      2
rep: 01000000 00001000 00000000 00000000 00000000 00000000 00000000 00000000

val:   3.14
man:  0.785
exp:      2
rep: 01000000 00001001 00011110 10111000 01010001 11101011 10000101 00011111

val: 3.14159
man: 0.785397
exp:      2
rep: 01000000 00001001 00100001 11111001 11110000 00011011 10000110 01101110

Taking the last example, here's how to read it:

Code:
sign bit(+)    exponent(2)                mantissa(0.785397)
   |               |                         |
   |  +------------+                         |
+--+  |                                      |
|     |                                      |
|+----+-----++-------------------------------+---------------
||          ||
01000000 00001001 00100001 11111001 11110000 00011011 10000110 

-------+
       |
01101110

It looks like this format also assumes a hidden leading bit that's always set, so the mantissa is always in the range [0.5, 1).
 

derekjr_1

Smack-Fu Master, in training
67
That helps alot better. I understand this number thing alot better now. And as a plus I get to have a learning experience with C. I am using C++ right now but pretty much know the diffs between the too, so I can read some of your C example.

Pointers are still kind of hard to me, but eventually I will learn them.

THANKS for the explanations on the precision. I think I will definetely use doubles since most say they dont loose much performance from a float, floats just use less memory.
 
Status
Not open for further replies.