Tip 82. Don’t use mathematics with floating point

   

Fig. 82. Don’t use mathematics with floating point

The expansion program (two version) of sum of money (rubles and kopecks) to bank notes and coins is showed in the fig. 82. About this program we have told in tip 49, when we considered the translation program of Arabic numerals to Roman numerals and vice versa: Arabic numeral is sum of money, but its expansion to bank notes and coins is Roman numeral 255 = CCDV = 100 + 100 + 50 + 5. Algorithms of the programs «Roman – Arabic» (fig. 49) and «Cash dispenser» are absolutely the same. But… the first program gives the bug in the fig. 82, if initial sum of money includes kopecks (777 rubles and 77 kopecks, for example). The reason of the bug is in the feature of mathematics of real numbers[1]: for example, if we subtract 0.1 from 4.1, then we can obtain not 4, but 3.9999… or 4.0000…1, i.å. everything except the creator of the program or algorithm plan to obtain. In the fig. 82 the second program works without bugs as it does not have real numbers (rubles and kopecks), but only integer numbers (kopecks): as usual the second argument of the function can keep both rubles and kopecks, but at once the introduced real value is transferred to kopecks by the first operator of the program – to integer number: Summa ¬ 100∙Summa. Hence we could give you the following tip – if during work you can do without real numbers that it is better not to use them. If, for example, we meet meters with fractional «end» in a program, then it is better to transfer them to millimeters at once (hours to minutes, minutes to seconds and etc.).



[1] This is the feature not only Mathcad, but all software tools of calculus mathematics.