[swfmill] Patch: accurate format for floating point values

INADA Naoki inadauer at gmail.com
Mon Feb 11 08:41:43 PST 2008


Thanks for your advice.

I tested following code. C++ stream io and C sprintf/sscanf.
g++ 4.1 on Linux (Ubuntu Gutsy) works fine in both way. But string
representation is too long.
g++ 3.4.5 on mingw32 misses in C++ way. And both representation is
differ from g++4.1 on Linux.

I think floating point and string conversion in c/c++ standard io
library is not stable for cross platforms.
I'll make patch and send here again with netlib fp.

-- code --
#include <iostream>
#include <sstream>
#include <iomanip>
#include <cstdio>

using namespace std;

int main()
{
    stringstream sstr;
    unsigned long long val = 0x000FFFFFFFFFFFFFULL;
    double d1 = *(double*)&val;
    double d2;

    cout << "-- C++ stream io --\n" << setprecision(60);
    cout << "d1 = " << d1 << endl;
    sstr << setprecision(60) << d1;
    sstr >> setprecision(60) >> d2;
    cout << "sstr=" << sstr.str() << endl;
    cout << "d2 = " << d2 << endl;
    if (d1 == d2) {
        cout << "success in c++ way." << endl;
    }

    cout << "-- C sprintf/sscanf --\n";
    char buff[512];
    sprintf(buff, "%-.60lg", d1);
    sscanf(buff, "%lg", &d2);
    printf("d1  = %-.60lg\nbuff= %s\nd2  = %-.60lg\n", d1, buff, d2);
    if (d1 == d2) {
        cout << "success in c way." << endl;
    }

    return 0;
}

-- result (Linux) --
-- C++ stream io --
d1 = 2.22507385850720088902458687608585988765042311224095946549352e-308
sstr=2.22507385850720088902458687608585988765042311224095946549352e-308
d2 = 2.22507385850720088902458687608585988765042311224095946549352e-308
success in c++ way.
-- C sprintf/sscanf --
d1  = 2.22507385850720088902458687608585988765042311224095946549352e-308
buff= 2.22507385850720088902458687608585988765042311224095946549352e-308
d2  = 2.22507385850720088902458687608585988765042311224095946549352e-308
success in c way.

-- result (Mingw) --
-- C++ stream io --
d1 = 2.2250738585072009e-308
sstr=2.2250738585072009e-308
d2 = 1.850091739200631e-307
-- C sprintf/sscanf --
d1  = 2.2250738585072009e-308
buff= 2.2250738585072009e-308
d2  = 2.2250738585072009e-308
success in c way.


-- 
INADA Naoki <inadauer at gmail.com>
Blog: http://d.hatena.ne.jp/methane/ (sorry, Japanese only.)



More information about the swfmill mailing list