Question

Here x is taking 0.699999 instead of 0.7 but y is taking 0.5 as assigned. Can you tell me what is the exact reason for this behavior.

#include<iostream>
using namespace std;

int main()
{
float x = 0.7;
float y = 0.5;
if (x < 0.7)
{
if (y < 0.5)
   cout<<"2 is right"<<endl;
else 
   cout<<"1 is right"<<endl;
}
else 
   cout<<"0 is right"<<endl; 

cin.get();
return 0;
}
Was it helpful?

Solution

There are lots of things on the internet about IEEE floating point.

0.5 = 1/2

so can be written exactly as a sum of powers of two

0.7 = 7/10 = 1/2 + 1/5 = 1/2 + 1/8 + a bit more... etc

The bit more can never be exactly a power of two, so you get the closest it can manage.

OTHER TIPS

It is to do with how floating points are represented in memory. They have a limited number of bits (usually 32 for a float). This means there are a limited number of values that can be represented which means that many numbers from the infinite set of real numbers cannot be represented.

This website explains further

If you want to understand exactly why, then have a look at floating point representation of your machine (most probably it's IEEE 754, https://en.wikipedia.org/wiki/IEEE_floating_point ).

If you want to write robust and portable code, never compare floating-point values for equality. You should always compare them with some precision (e.g. instead of x==y you should write fabs(x-y) < eps where eps is say 1e-6).

floating point representation is approximate only as you cannot have precise representation of real, non-rational numbers on a computer. ` when operating on floats, errros will in general accumulate.

however, there are some reals which can be represented exactly on a digital computer using it's native datatype for this purpose (*), 0.5 being one of them.

(*) meaning the format the floating point processing unit of the cpu operates on (standardized in ieee754). specialized libraries can represent integer and rational numbers exactly beyond the limits of the processor's internal formats. rounding errors may still occur when converting into a human-readable decimal expansion and the alternative also does not extend to irrational numbers (e.g. sqrt(3)). and, of course, these libraries comes at the cost of less speed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top