Why is the expression (double.Minvalue == double.Minvalue + 1) true?

Asked

Viewed 115 times

7

The following code C#:

public class Program
{
    public static void Main(string[] args)
    {
        //Your code goes here
        Console.WriteLine(double.MinValue == double.MinValue + 1);
        Console.WriteLine(int.MinValue == int.MinValue + 1);
    }
}

has as output:

True
False

My question is: why does the first line return true? For me, this line should return false, since I’m comparing a number to itself + 1.

1 answer

10


First read What is the correct way to use the float, double and decimal types?.

Ali says that it is not possible to represent all numbers in binary format. Then some numbers are taken by approximation. Note that there are 308 digits in this number it is worth -1.79769313486232E+308.

Since this type of data has no accuracy when you have a number with a value at the extreme, very low or very high, adding 1 does not actually change the value, in such a large quantity the binary representation cannot differentiate one number from the other, the bits of both are the same.

Think about it, um long is the same size as a double, how does the latter manage to represent much more integers and an absurd amount of fractional numbers with the same amount of bits as an integer? Simple, it doesn’t represent all of these numbers, just approximations of them, so very close numbers actually have the same binary representation, there’s no difference of even 1 bit between them, so you can get enough quantity for very large numbers, but he can’t get the exact number, it’s like he just took a sample.

That’s why I always say that if accuracy is important don’t use a binary coded floating point number.

  • 5

    Just because I like this video and explains exactly what you said, for those who want more information in the future: https://youtu.be/pQs_wx8eoQ8

  • 3

    In the series of games Mass Effect has an entire ecosystem of artificial intelligences that divides between those who want to destroy all life forms and those who do not, and the whole schism occurs because of a difference in the nth decimal place of a division with floating point. Think about it when accuracy is important.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.