c++ - Splitting a floating point number almost-equally with no loss -
Assuming 2 digits after the decimal view representation of floating point number (eg: currency), with the most to divide the amount What is the best way to minimize the total error?
For example, to deliver 100.00 equally to 3 bank accounts, I do something like this:
double amount = 100.0; Double acc1 = zodiac / 3.0; Double acc2 = zodiac / 3.0; Double acc3 = zodiac / 3.0;
However, when printing each account balance with 2 decimals, I get:
printf ("% .2f \ n", Acc1); Printf ("% .2f \ n", AC2); Printf ("% .2f \ n", ACC3); 33.33 33.33 33.33
It is clear that the amount of all the accounts is 99.99, 0.01 is lost due to rounding.
Ideally, I need some functions / algorithms that print almost equally and visually
33.34 33.33 33.33
It does not matter which of the three accounts gets the extra 0.01.
How do I do this? Is there a round algorithm name for this?
You are creating several errors here double
one double-exact Binary is floating-point number. 100.0 / 3.0>
equal 33.33333333333333570180911920033395290374755859375
; The problem of giving everyone 100.0 / 3.0
is not that you are giving a little less than the entire amount of cake, rather than trying to give as much cake as you have. . Then you score it in two decimal places, which is an operation, you can not expect to keep this amount safe.
I will suggest an integer number of smugglers instead of floating-point number dollar in your application.
With that word, to divide the shape of C
in floating-point parts for distribution between people, you < Code> n-1 size of the size c / n
and the last person size is a piece of fma (-c / n, n-1, c)
. A multiplication in the (C / N) * (N-1)
can cause a goaloff error, so fuse multiplication is essential here. Anyone can also fmod
or remaining
.
Comments
Post a Comment