jeudi 29 avril 2021

How to generate random Decimal128, Decimal256 numbers with Python

I am making a test for ClickHouse database for verifying Decimal data types. According to documentation:

Decimal Parameters:

P - precision. Valid range: [1 : 76]. Determines how many decimal digits number can have (including fraction). S - scale. Valid range: [0 : P]. Determines how many decimal digits fraction can have. Depending on P parameter value Decimal(P, S) is a synonym for:

  • P from [1 : 9] - for Decimal32(S)
  • P from [10 : 18] - for Decimal64(S)
  • P from [19 : 38] - for Decimal128(S)
  • P from [39 : 76] - for Decimal256(S)

I am trying to generate random numbers for all of these data types. I've found a good answer already and this is how I used it:

Decimal32:

>>> decimal.Decimal(random.randint(-2147483648, 2147483647))/1000
Decimal('-47484.47')

Decimal64:

>>> decimal.Decimal(random.randint(-9223372036854775808, 9223372036854775807))/100000000000
Decimal('-62028733.96730274309')

These two give me the expected result. But, my function for Decimal128 already is too long and produces wrong result:

>>> decimal.Decimal(random.randint(-170141183460469231731687303715884105728, 170141183460469231731687303715884105727))/1000000000000000000000
Decimal('149971182339396169.8957534906')

Question:

How can I generate random Decimal128 and Decimal256?

Please suggest what I should use.




Aucun commentaire:

Enregistrer un commentaire