Please, why must a be < 0.7, when float a = 0.7? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 22

Please, why must a be < 0.7, when float a = 0.7?

15th Jul 2020, 4:10 PM
ProfOduola🙏🇳🇬
ProfOduola🙏🇳🇬 - avatar
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.
15th Jul 2020, 4:43 PM
A S Raghuvanshi
A S Raghuvanshi - avatar
+ 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.
15th Jul 2020, 4:19 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 8
Thanks, Mouli and benjamin , accepted as they say😂👍
15th Jul 2020, 4:19 PM
ProfOduola🙏🇳🇬
ProfOduola🙏🇳🇬 - avatar
+ 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😂😂
15th Jul 2020, 4:21 PM
ProfOduola🙏🇳🇬
ProfOduola🙏🇳🇬 - avatar
+ 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.
15th Jul 2020, 4:25 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 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
15th Jul 2020, 6:22 PM
blACk sh4d0w
blACk sh4d0w - avatar
+ 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.
15th Jul 2020, 6:46 PM
benjamin
+ 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.
17th Jul 2020, 1:06 AM
harimanu932
harimanu932 - avatar