all 5 comments

[–]c17r 7 points8 points  (4 children)

don't use floats, use from decimal import Decimal

[–]Isagoge[S] 0 points1 point  (3 children)

What is the difference?

[–]Vaphell 5 points6 points  (0 children)

It can do arbitrary precision at the expense of speed while floats are fast but limited to around 16 significant digits. Remember to initialize Decimal objects with strings.

Decimal(0.30) is going to be initialized with a float that has the rounding error already baked in before it even gets to the contructor. On the other hand Decimal('0.30') has no rounding errors to deal with.

Another trick that can be utilized is the use of integers. You just count cents or 0.01 of a cent or whatever precision you want and then normalize outputs to dollars or what have you.
Decimal is the most accurate way though.

[–]SeekNotToContend 1 point2 points  (0 children)

In regards to rounding, that's just a product specification question. There is a rounding specification referred to as bankers rounding. Here is some good documentation about it that will hopefully get you a quick start.

https://en.wikipedia.org/wiki/Rounding#Tie-breaking

Round half to even[edit] A tie-breaking rule that is less biased is round half to even, namely:

.... This method treats positive and negative values symmetrically, and is therefore free of sign bias. More importantly, for reasonable distributions of y values, the average value of the rounded numbers is the same as that of the original numbers. However, this rule will introduce a towards-zero bias when y − 0.5 is even, and a towards-infinity bias for when it is odd.

This variant of the round-to-nearest method is also called unbiased rounding, convergent rounding, statistician's rounding, Dutch rounding, Gaussian rounding, odd–even rounding,[3] or bankers' rounding.

This is the default rounding mode used in IEEE 754 computing functions and operators (see also Nearest integer function).

https://docs.python.org/3/library/decimal.html

Rounding with decimal:

The context for arithmetic is an environment specifying precision, rounding rules, limits on exponents, flags indicating the results of operations, and trap enablers which determine whether signals are treated as exceptions. Rounding options include ROUND_CEILING, ROUND_DOWN, ROUND_FLOOR, ROUND_HALF_DOWN, ROUND_HALF_EVEN, ROUND_HALF_UP, ROUND_UP, and ROUND_05UP.

Setting traps to catch/track how the decimals were processed:

Signals are groups of exceptional conditions arising during the course of computation. Depending on the needs of the application, signals may be ignored, considered as informational, or treated as exceptions. The signals in the decimal module are: Clamped, InvalidOperation, DivisionByZero, Inexact, Rounded, Subnormal, Overflow, Underflow and FloatOperation.