|
|
|
|
|
by mdellavo
1818 days ago
|
|
It seems incorrect to determine a half a month as 16/31 but ok , for your proposed example: >>> from decimal import Decimal
>>> Decimal(1000) * Decimal(16) / Decimal(31)
Decimal('516.1290322580645161290322581')
>>> 1000 * 16 / 31
516.1290322580645
The point is using Decimal allows control over precision and rounding rather than accepting ad-hoc approximations of a float.https://docs.python.org/3/library/decimal.html If it were me, I wouldn't go around bragging about how much money my software manages while being willfully ignorant of the fundamentals. |
|
Now for your example, I see that float and decimal just give the same result. Provided I'm doing financial computations of a final number, I'm ok with 2 decimals. And both your computations work fine.
Th decimal module in python gives you number of significant digits, not number of decimals. You'll end up using .quantize() to get to two decimals which is rounding (so, no advantage over floats).
As I said, as soon as you have division/multiplication you'll have to take care of rounding manually. But for addition/subtraction, then decimal doesn't need rounding (which is better).
The fact is that everybody say "floats are bad" because rounding is tricky. But rounding is always possible. And my point is that rounding is tricky even with the decimal module.
And about bragging, I can tell you one more thing : rounding errors were absolutely not the worse of our problems. The worse problem is to be able to explain to the accountant that your computation is right. That's the hard part 'cos some computations imply hundreds of business decisions. When you end up on a rounding error, you're actually happy 'cos it's easy to understand, explain and fix. And don't start me on how laws (yes, the texts) sometimes explain how rounding rules should work.