-1

need to calculate with decimals but python show error, but the solution that the book give, don't work!!!

By example if try to sum 0.1 + 0.1 + 0.1 show the classical error but if try:

from decimal import Decimal
d = Decimal(0.1)
d + d + d

The error obtained is:

Decimal('0.3000000000000000166533453694')

what's supposed the solution gives an error, please help, using python 3.8 in openSuse TumbleWeed.

Image of the python fail

My question is different from the post Is floating point math broken?, that post dont ask about "decimal" library.

robbykz
  • 1
  • 4
  • Please show the output as text, not as a screenshot. – Code-Apprentice Feb 06 '21 at 01:44
  • 1
    Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Code-Apprentice Feb 06 '21 at 01:45
  • 1
    "The error obtained is..." This is not an error. It is the output of a successful calculation. This works exactly as it is supposed to. See the link above for details about why you don't get exactly `0.3` as you probably expect. – Code-Apprentice Feb 06 '21 at 01:47
  • @Code-Apprentice that post is not the same, my issue is about de Decimal library and that post you share don't ask about such library. – robbykz Feb 06 '21 at 01:52
  • It is the same because you initialize the `Decimal` object with a floating point value. – Code-Apprentice Feb 06 '21 at 01:55
  • @Code-Apprentice in that post the solution is if (abs(x - y) < myToleranceValue) { ... }, I don't understend how that can help me. – robbykz Feb 06 '21 at 01:58
  • To clarify, the **cause** is the same as in that post. The behavior you see here is due to the fact that **floating point numbers are not real numbers (in the mathematical sense)**. Rather, floats are an approximation to the real numbers. As such, they have quirky behaviors that all programmers should be aware of. – Code-Apprentice Feb 06 '21 at 02:00
  • I shared the link so you can read about why this happens rather than giving a solution. – Code-Apprentice Feb 06 '21 at 02:02

2 Answers2

2

The output you see is not an error. Since you initialize Decimal() with a float value, it uses float arithmetic. On the other hand, if you do

d2 = Decimal('0.1')
print(d2 + d2 + d2)

You will get the result you expect.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
0

Here is an example, you can also adjust the precision with getcontext().prec

from decimal import *

getcontext().prec = 100   # Set a new precision
b = Decimal(0.1)
c = Decimal("0.1")

print(b+b+b)
print(c+c+c)

# 0.3000000000000000166533453693773481063544750213623046875
# 0.3
zoltron
  • 67
  • 6