Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python decimal.InvalidOperation error

i'm always getting this error when running something like this:

from decimal import *
getcontext().prec =30

b=("2/3")

Decimal(b)

Error:

Traceback (most recent call last):
  File "Test.py", line 6, in <module>
    Decimal(b)
decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>]

Also, why do i get this result from the console?

>>> Decimal(2/3)
Decimal('0.66666666666666662965923251249478198587894439697265625')

Thanks

like image 861
Matteo Avatar asked Nov 20 '15 12:11

Matteo


Video Answer


2 Answers

Decimal's initializer can't accept strings with a slash in them. Informally, the string has to look like a single number. This table shows the proper format for string arguments. If you want to calculate 2/3, do

>>> Decimal(2)/Decimal(3)
Decimal('0.6666666666666666666666666667')

Decimal(2/3) gives Decimal('0.66666666666666662965923251249478198587894439697265625') because 2/3 evaluates to a floating point number, and floats have inherently limited precision. That's the closest the computer can get to representing 2/3 using a float.

like image 55
Kevin Avatar answered Sep 20 '22 09:09

Kevin


I solved the problem like this

from decimal import *

b = (Decimal(2) / Decimal(3)).quantize(Decimal(1)/(10**Decimal(30)))

Decimal(b)

quantize allows you to get the necessary accuracy

like image 38
user11614811 Avatar answered Sep 21 '22 09:09

user11614811