Remove floating error

We need to read IEEE 754 floating point standard to understand floating point error. I wrote a program to add 0.01 hundred time and result should be 1.0. But, in reality double data variable will have 1.0000000000000007 as value. Give code has the solution of this problem and it has focus to remove floating error only. Solution line is bold in given code.

int main(int argc, char* argv[])
{
    const double x = 0.01;
    double s = 0, e = 0;
    for (int i = 0; i < 100; i++)
    {
        s = s + x;
        cout << s << “\t” << x << endl;
    }
    ((char *)&s)[0] = ((char *)&s)[0] >> 8;
    e = 1.0 – s;
    cout << “value of e : ” << e << endl;
    return 0;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s