Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Double comparison precision loss in C#, accuracy loss happening when adding subtracting doubles

Just started learning C#. I plan to use it for heavy math simulations, including numerical solving. The problem is I get precision loss when adding and subtracting double's, as well as when comparing. Code and what it returns (in comments) is below:

namespace ex3
{
    class Program
    {
        static void Main(string[] args)
        {

            double x = 1e-20, foo = 4.0;

            Console.WriteLine((x + foo)); // prints 4
            Console.WriteLine((x - foo)); // prints -4
            Console.WriteLine((x + foo)==foo); // prints True BUT THIS IS FALSE!!!
        }
    }
}

Would appreciate any help and clarifications!

What puzzles me is that (x + foo)==foo returns True.

like image 443
Mikhail T. Avatar asked Aug 12 '16 12:08

Mikhail T.


People also ask

How many digits are lost in double precision?

The most commonly used double precision format stores the number with 53 bits of precision. This gives approximately 16 decimal digits of precision. You may find that long double gives more precision, but there is no guarantee that that is any larger than double .

Can you compare doubles in C?

Master C and Embedded C Programming- Learn as you go To compare two floating point or double values, we have to consider the precision in to the comparison. For example, if two numbers are 3.1428 and 3.1415, then they are same up to the precision 0.01, but after that, like 0.001 they are not same.

Is double more precise than float?

double has 2x more precision than float. float is a 32-bit IEEE 754 single precision Floating Point Number – 1 bit for the sign, 8 bits for the exponent, and 23* for the value. float has 7 decimal digits of precision.

Can double and float compare in C?

Since the precision of float is less than the double therefore after a certain point(23 in float and 52 in double) it would truncate the result. Hence, after promotion of float into double(at the time of comparison) compiler will pad the remaining bits with zeroes.


1 Answers

Take a look at the MSDN reference for double: https://msdn.microsoft.com/en-AU/library/678hzkk9.aspx

It states that a double has a precision of 15 to 16 digits.

But the difference, in terms of digits, between 1e-20 and 4.0 is 20 digits. The mere act of trying to add or subtract 1e-20 to or from 4.0 simply means that the 1e-20 is lost because it cannot fit within the 15 to 16 digits of precision.

So, as far as double is concerned, 4.0 + 1e-20 == 4.0 and 4.0 - 1e-20 == 4.0.

like image 119
Enigmativity Avatar answered Sep 30 '22 02:09

Enigmativity