简体   繁体   中英

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.

The problem you face, is that the precisison is not set high enough to record all the digits in your division. The simplest way to fix it, is to increase the precision (at the expense of the division and all other operations taking longer to execute. The default precision is set to 28, that is 28 correct fractional digits. This is enough for Decimal64 , but too few for Decimal128 and Decimal256

To update the precision you write:

decimal.getcontext().prec = 38 # Maximum number of fractional digits in Decimal128

After this your code should work. Of course, for Decimal256 , the precision needs to be set to 76.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM