by vosper · 9y ago · 0 comments
value = decimal.Decimal("12.34567")
Why wouldn't this work? value = 12.34567 D = decimal.Decimal
x = D("1.2345")
Also (at least this was once true) by doing so you save Python from a dictionary lookup after the dot "." each time.There could be an argument for switching to decimals as standard, but even ignoring the practical consequences, I think for historical reasons (I assume this is the standard of programming languages; in Ruby for example is the same) it's not something that will be ever agreed/changed.
https://en.wikipedia.org/wiki/IEEE_floating_point
So, because users will typically be surprised that 2.2 + 3.1 results in 5.300000000000001, or that round(2.675, 2) gives 2.67 (instead of 2.68), best practice is to use Decimal, which will give users the results they expect:
A similar scenario in film (that hasn't caused as much trouble for me) is aspect ratio, which is the height/width of an image. Fractions and decimals are used interchangeably in conversation.
https://docs.python.org/3/library/fractions.html
Also possibly useful in that context (and bringing us back full circle to the OP's subject), Python 3.6 has added the as_integer_ratio() method to Decimal instances:
https://docs.python.org/3.6/library/decimal.html#decimal.Dec...
In other words, it can be inferred to be any type that implements the Fractional typeclass, which includes Decimal types. Not that it is relevant here, because you basically need to have types for something like this to work, if you have proper type inference, then you don't need to assume any type, and can just interpret a literal as whatever is needed.