top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How reliable are floating-point comparisons?

+4 votes
472 views
How reliable are floating-point comparisons?
posted Feb 27, 2014 by Kanika Prashar

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+2 votes

Floating-point numbers are the black art of computer programming. One reason why this is so is that there is no optimal way to represent an arbitrary number. The Institute of Electrical and Electronic Engineers (IEEE) has developed a standard for the representation of floating-point numbers, but you cannot guarantee that every machine you use will conform to the standard.

Even if your machine does conform to the standard, there are deeper issues. It can be shown mathematically that there are an infinite number of real numbers between any two numbers. For the computer to distinguish between two numbers, the bits that represent them must differ. To represent an infinite number of different bit patterns would take an infinite number of bits. Because the computer must represent a large range of numbers in a small number of bits (usually 32 to 64 bits), it has to make approximate representations of most numbers.

Because floating-point numbers are so tricky to deal with, it is generally bad practice to compare a floating-point number for equality with anything. Inequalities are much safer.

answer Feb 27, 2014 by Hiteshwar Thakur
0 votes

Floating point numbers are never stored in the form of exact value so there are chances that comparison can fail (specially if you are using == or !=).

Consider the following example

double a = 1.0 / 3.0;
double b = a + a + a;
if (a != b)
    printf("Oh no!");
else 
    printf("a and b are equal");

If you think from mathematical point of view the code should enter into the else area but i will not. Rest if self explainable.

answer Feb 27, 2014 by Salil Agrawal
Similar Questions
+3 votes

Using fprintf() print a single floating point number right-justified in a field of 20 spaces, no leading zeros, and 4 decimal places. The destination should be stderr and the variable is called num.

+7 votes

Write a routine to draw a circle (x ** 2 + y ** 2 = r ** 2) without making use of any floating point computations at all ??

...