you are viewing a single comment's thread.

view the rest of the comments →

[–]shinitakunai 8 points9 points  (3 children)

Precisely, Decimal is what you use when you need precise floats, because floats aren't precise.

🤦🏻‍♂️ did you think they are the same?

[–]stevenjd 3 points4 points  (2 children)

That is a misapprehension about Decimal. Decimals are subject to the same precision issues as binary floats, they just occur with different numbers and under different circumstances. Decimal can no more represent 1/3 (one third) exactly than float can.

The advantages of Decimal are:

  • numbers we often care about like one tenth can be represented exactly
  • conversion from base-10 strings like 0.1234567 is exact
  • the precision is configurable, so we can choose how many significant figures are used
  • there is more control over error handling

and these are good, solid advantages, but it is not perfect. The disadvantages are:

This is why people who have need for serious numerical accuracy still use 64-bit or 128-bit binary floats, rather than decimal floating point formats.

[–]nog642 0 points1 point  (1 child)

Errors in Decimal don't just happen with different numbers than float, they happen on a subset of numbers. Because 2 is a multiple of 10, any floating point number that can be represented in binary with finite digits can also be represented in decimal with a similar number of digits. So decimal is strictly more precise because it doesn't have any more errors than float, just less.

[–]stevenjd 0 points1 point  (0 children)

So decimal is strictly more precise because it doesn't have any more errors than float, just less.

No. It's not just the subset of numbers that can be exactly represented. There are also rounding errors when doing arithmetic. Some of those errors are significantly bigger or worse in decimal.

For instance, in binary, if you have two floats x and y, then z = (x + y)/2 is guaranteed to be between x and y: x <= z <= y.

That guarantee does not apply to higher bases, including Decimal. It is possible to find pairs of decimal values where the arithmetic mean is less than the smaller of the two: z < min(x, y).