+ 22
Please, why must a be < 0.7, when float a = 0.7?
9 Answers
+ 12
Both have difference too
float a=0.7;
Its not float value it is a double value by default float value is treat as double.if u will write like this
float a=0.7f then it is float value. Double size is greater than float .
here double value is assigned to( a )and a is float type so a is float but 0.7 is double so float (a)< 0.7 double hope u understood.
+ 11
MiKoLa🔥3L17.4L16.2.5k=>L18.🙏IDLE , if I guess it right you mean that floating point number is smaller in fact than the declared value. The reason is precision of the representation of the number, so the number is something like 0.69998.
+ 7
TheWh¡teCat 🇧🇬 a lay man would want to argue that 0.700001 could also be represented as 0.7, but for this binary conversions😂😂
+ 7
MiKoLa🔥3L17.4L16.2.5k=>L18.🙏IDLE , it's a matter of accuracy maybe strange, but floating point numbers are represented in binary format and perfection is hard to achieve.
+ 4
That's floating point binary for you. Read this: http://effbot.org/pyfaq/why-are-floating-point-calculations-so-inaccurate.htm
Or
https://stackoverflow.com/questions/21895756/why-are-floating-point-numbers-inaccurate
+ 3
MiKoLa🔥3L17.4L16.2.5k=>L18.🙏IDLE
Run below code:
#include <stdio.h>
int main() {
float a = 0.7;
printf("a: %.12f\n", a);
printf(" %.12f\n", 0.7);
return 0;
}
You'll notice the difference.
Floating point values have less precision than Double type values.
Float have a precision up to 7 decimal places.
Double have precision up to 15 decimal places.
So when float value is compared with double, the float is converted to double type and thus it looses precision. That's why value of variable <a> is less than 0.7
+ 3
blACk sh4d0w good explanation. I've made it into a code snippet to make it easier for op to view:
https://code.sololearn.com/cC8CCJm6uV0y/?ref=app
A bit more info:
The % indicates the start of a format specifier.
The .12f means format it as decimal with 12 places.
The \n is for a new line.
+ 2
Floating point numbers are represented in as bits in computer memory.
(0.7)base10 =(0.101100100...)base2
But there is only 8 bits for exponent part allocated to float type. So the rest of the bits may be ignored or rounded by the processor. That is why we can't do such types of comparisons. It is also a good practice not to use == and != in such cases.