Home > Software design >  Generating Random (Seed) Numbers in Python
Generating Random (Seed) Numbers in Python

Time:11-14

How can I generate a random number using Uniform distributed random number range between (Length of the string and 2000000), integer only., by using all the time constant seed(2) in random generation to get the same results in each run?

x = random.uniform(len(String),200)

How can I use seed next?

CodePudding user response:

You can use a list comprehension for a more compact (and potentially faster) code:

import random

# Fixed seed for repetitive results
const_seed = 200

# Bounds of numbers
n_min = 0
n_max = 2

# Final number of values 
n_numbers = 5

# Seed and retrieve the values
random.seed(const_seed)

numbers = [random.uniform(n_min, n_max) for i in range(0, n_numbers)]

print(numbers)

By always seeding with the same number your sequence of numbers will be the same (at least on the same platform - i.e. computer). Here is a confirmation from the official documentation.


This is the requested version that generates integers following a uniform distribution (the above creates floats). The smallest possible integer is the length of a string and the largest is 2,000,000:

import random

# Fixed seed for repetitive results
const_seed = 200

# Bounds of numbers
some_string = 'aString'
n_min = len(some_string)
n_max = 2000000

# Final number of values 
n_numbers = 5

# Seed and retrieve the values
random.seed(const_seed)

numbers = [random.randint(n_min, n_max) for i in range(0, n_numbers)]

print(numbers)

CodePudding user response:

The seed() method is used to initialize the random number generator. The random number generator needs a number to start with (a seed value), to be able to generate a random number. By default the random number generator uses the current system time. Use the seed() method to customize the start number of the random number generator. Note: If you use the same seed value twice you will get the same random number twice. using random.seed() and setting the same seed everytime will give the same output

here is an example:

import random
random.seed(12)
for i in range (1, 10):
    a = random.randint(1,10)
    print(a)
  • Related