-2

I'm working on something in python that involves generating a random number that must be 12 digits long, how would I do this?

For example, every time the program is run, it would generate numbers such as 424476789811, etc.

elf
  • 46
  • 1
  • 7

4 Answers4

4

welcome to the SO-community!

How about using random.randint between 10^12 and 10^13 - 1?

import random

print(random.randint(10**12, 10**13 - 1))
# randint is inclusive on both sides, so we need the - 1

# or

print(random.randrange(10**12, 10**13))
# randrange does not include the stop integer
WillMonge
  • 1,005
  • 8
  • 19
2

Try using random.randint:

import random
print(random.randint(100000000000, 999999999999))

Output:

785657835683

This gets a random number between 100000000000 and 999999999999.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

You can use the following code to get random integer having 12 digits long length and you can its range. Hope it will works for you.Peace!

import random

print(random.randint(1**12, 10**12))

#returns a number between 1 and 9, you can change the range of number by changing 1 and 10.
0

Well, there are several ways to accomplish this but it all depends on how you want your numbers to be generated. Python's numpy library has a module random which you can use to generate a random number between 0 and 1 (1 not included) with equal probability. i.e. samples of the uniform distribution: numpy.random.rand()

One way to do it would be to take that number you generate and map it from a domain of 0-1 to a domain of 10**11 to 10**12. Keep in mind that although the latter is a 13 digit number the upper bound is not included!

The linear mapping would thus be the line going through the points (0, 1e11) and (1, 1e12). Can you come up with the equation of that line?

Some things to keep in mind:

  1. The data type in this case is of paramount importance: using float32 is not enough for the precision required and so your datatype should be numpy.float64.

  2. Your numbers will be in that range but won't be rounded, so you should use floor to round them (and exclude the top).

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61