PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, August 9, 2022

[FIXED] How to generate random Decimal128, Decimal256 numbers with Python

 August 09, 2022     clickhouse, decimal, python, random     No comments   

Issue

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.


Solution

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.



Answered By - JohanL
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing