Click to See Complete Forum and Search --> : float degradation


wxjunkie
10-02-2002, 05:54 PM
Creating a simple change counting program in C++ (example: enter a money amount less than 100 dollars...and the program will make change, telling how many tens, fives, ones, etc.)

I've noticed that when dividing the number by 1 in order to derive the number of ones, I get a repeating decimal amount, such as infinite precision is not there with a float (binary, base 2 instead of base 10, is the cause, I'm assuming).

How can I fix this problem? Basically, when I perform this operation:
1.12 - 1 = .1199999999



This may seem confusing so here's the code I'm working on...


// begin ones routine
int ones;

ones = money / 1; /* int money to remove decimal */

// substr and setw on next cout for formatting and doesn't pertain to my problem

cout << ones << setw(8) << " ones" << " " << setw(0)
<< bars.substr(0,ones) << endl;

money = money - ones; /* subtract ones from total*/

Mancora
10-03-2002, 01:10 AM
Well i dont recigonize that type of code, but then again about all i know is some java.

Ok, a little off topic, if you dont understand the binary system and roundoff error then your should probably read this, its pretty interesting

To understand the binary system it works out best to understand how our normal numbering system works, the decimal system.

And here is a webpage about the decimal numbering system.
http://www.danbbs.dk/~erikoest/decimal.htm#top

Here is a webpage about the binary numbering system. http://www.danbbs.dk/~erikoest/binary.htm#top

If you look at the repeated division by 2 "Repeated Division By 2" in the binary link you can see the round off error.



Your problem is that your floating point is running out of precision, im not sure what the amount of digits a C++ floating point can handle.

Anyways, the way to avoid this is to multiple everything by 100 (to get rid of the decimal), and then when your done with your calculations and want to present it divide it by 100 to get your cents back.
Or you could use a larger floating point type number, however the first method is probably the most easy as you dont have to keep remembering the number of signifigant decimal digits that the floating point type your using can hold without getting round off error.

In fact i believe banks multiply their money by 100,000 so they end up with thousandth of a cent, they use the 1/1000ths of a cent to accuratly caclulate intrest.