+ 1

Floats related HELP!

Hey, I’m a newbie. So in the tutorial, it said, “Computers can't store floats perfectly accurately, in the same way that we can't write down the complete decimal expansion of 1/3 (0.3333333333333333...). Keep this in mind, because it often leads to infuriating bugs!” How does it lead to bugs exactly? What do those bugs do?

29th Dec 2018, 1:38 PM
Ananya Bhatia
Ananya Bhatia - avatar
3 odpowiedzi
+ 4
A little dangerious one! My PC been hanged for 5 min, now! LOL Welcome to infinite loop with FP flavore! #include <iostream> #include <iomanip> using namespace std; int main() { cout << fixed << showpoint; cout << setprecision(17); for (double d = 0.0; d != 1.0; d += 0.1) { cout << d << endl; } } Output: 0.00000000000000000 0.10000000000000001 0.20000000000000001 0.30000000000000004 0.40000000000000002 0.50000000000000000 0.59999999999999998 0.69999999999999996 0.79999999999999993 0.89999999999999991 0.99999999999999989 1.09999999999999987 1.19999999999999996 1.30000000000000004 1.40000000000000013 1.50000000000000022 1.60000000000000031 1.70000000000000040 1.80000000000000049 1.90000000000000058 2.00000000000000044 2.10000000000000053 2.20000000000000062 2.30000000000000071 2.40000000000000080 2.50000000000000089 2.60000000000000098 2.70000000000000107 2.80000000000000115 2.90000000000000124 3.00000000000000133 3.10000000000000142 3.20000000000000151 3.30000000000000160 3.40000000000000169 3.50000000000000178 3.60000000000000187 3.70000000000000195 3.80000000000000204 3.90000000000000213 4.00000000000000178 4.10000000000000142 4.20000000000000107 4.30000000000000071 4.40000000000000036 4.50000000000000000 4.59999999999999964 4.69999999999999929 4.79999999999999893 4.89999999999999858 4.99999999999999822 5.09999999999999787 5.19999999999999751 5.29999999999999716 5.39999999999999680 5.49999999999999645 5.59999999999999609 5.69999999999999574 5.79999999999999538 5.89999999999999503 5.99999999999999467 6.09999999999999432 6.19999999999999396 6.29999999999999361 6.39999999999999325 6.49999999999999289 6.59999999999999254 6.69999999999999218 6.79999999999999183 6.89999999999999147 6.99999999999999112 7.09999999999999076 ______ https://rextester.com/QNBPY95727
29th Dec 2018, 2:13 PM
Babak
Babak - avatar
+ 1
if(0.1 + 0.2 == 0.3){ print "this never happens" } If you are aware of floating point maths it's usually not a problem because you rarely need perfect accuracy. But if you do, you will have to use bigints or decimals instead of floating point numbers.
29th Dec 2018, 1:50 PM
Schindlabua
Schindlabua - avatar
0
If x = 1/3 = 0.3333333 y = 3x = 3*0.3333333 = 0.9999999 The situation when that could be a problem is rare enough, that I have never had any problem with that.
29th Dec 2018, 1:57 PM
Seb TheS
Seb TheS - avatar