A
A
Andrey Dugin2020-01-10 22:20:56
Python
Andrey Dugin, 2020-01-10 22:20:56

What is wrong with the Decimal() constructor?

Now it's my turn to ask stupid questions. Meditate on this:
5e18ce25c122f118994211.png

Code to play
import numpy as np
from decimal import Decimal

t = tuple(np.square(Decimal(123).as_tuple().digits))

assert t == (1, 4, 9)
assert type(t) is tuple
assert type(t) == type((1, 4, 9))

Decimal((0, (1, 4, 9), 0))
Decimal((0, t, 0))

What's the catch?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Yakushenko, 2020-01-10
@adugin

The bottom line is that here Checking the tuple, not its elements.

>>> type(t[0])
<class 'numpy.int32'>

And Decimal wants to see a tuple of characters, not objects of class numpy. I'm not good at numpy, from the word in general, so the dumbest, but working solution that immediately came to my mind:
>>> Decimal((0, tuple([int(x) for x in t]), 0))
Decimal('149')

Then dance yourself.

D
Dimonchik, 2020-01-10
@dimonchik2013

either the brackets are superfluous
or a tuple of one element must contain a comma (otherwise it's just brackets - sugar)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question