Jump to content
  • Advertisement
cebugdev

C++ double accuracy in C++

Recommended Posts

a simple assignment such as bellow 

    int main()
    {
         double variable = 1.4;
         double value = variable;
         return 0;
    }

the value of both variable and value is 1.399999999999999

Why is this?

BUT when setting this

    double value = 1.5;

Gives correct result!! why?

Any idea on how to resolve this or atleast a workaround?

image.png.8fc4fe671631807f7b68bf156eacb810.png

Share this post


Link to post
Share on other sites
Advertisement
3 hours ago, cebugdev said:

 

Any idea on how to resolve this or atleast a workaround?

 

As others have noted this is a function of the fact that certain real numbers can not be represented in binary with an exact representation the same as they can in decimal. However in most cases this isn't so critical. For instance if you were to print out 1.4 using printf("%3.1f",1.4) , it will generally give you what you want (i.e. 1.4) even though the internal representation is closer to 1.399999999999999 . Basically your problem is with formatting. So your GUI needs to have some option to do the appropriate formatting on output. Baring that, you can use sprintf or the C++ stream equivalent to format your number and convert it to a string before handing it to your GUI. 

If you really need to store 1.4 exactly you would probably have to use something like BCD. Binary Coded Decimal .  As I recall old 16 bit intel CPUs had some machine language opcodes to help support BCD but I'm not sure if it was carried forward in later architectures. I'm guessing that's not what you really need anyway.

Share this post


Link to post
Share on other sites

Just to add that, this is not unique to C++. Anything that uses (binary) floating point decimal will display this kind of problem. In fact, this is by-design. 

 

Share this post


Link to post
Share on other sites

It's not even a matter of design, it's an inherent property of representing fractions with a finite number of digits. A rational non-integer number can only be accurately represented with a finite number of digits if all the prime factors of the denominator are also prime factors of the radix; otherwise, it requires an infinitely repeating digit sequence.

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!