iKlsR
iKlsR

Reputation: 2672

Generate a random number in that falls into a multiple range

How would I go about generating a random integer in python that is random but falls into a multiplication table (times table) range per se and is determined by a value I specify?

Example. Say i want to generate a random number between 10 and 100 but it should be a multiple of 7. Possible return values could be 14, 28, 49, 77 etc.

A mockup of the function could look like this:

def gen_random(f, min, max):
    #generate random number between min and max that is a multiple of fac

Is Python's random module capable of doing this?

Upvotes: 2

Views: 2034

Answers (3)

Fedor Gogolev
Fedor Gogolev

Reputation: 10541

Function randrange has a step parameter, so if you can do something like this:

>>> min = 7
>>> max = 14 + 1
>>> randrange(min, max, 7)
14
>>> randrange(min, max, 7)
7

but:

>>> min = 6
>>> randrange(min, max, 7)
13

so you need to do something like this:

min += 7 - min % 7
max = max - max % 7 + 1

Upvotes: 3

Amber
Amber

Reputation: 526533

Why not just generate a multiplier of fac that gives you a number between your bounds?

import math
import random

def rand_multiple(fac, a, b):
    """Returns a random multiple of fac between a and b."""
    min_multi = math.ceil(float(a) / fac)
    max_multi = math.floor(float(b) / fac)
    return fac * random.randint(min_multi, max_multi)

Upvotes: 9

Kevin Mangold
Kevin Mangold

Reputation: 1155

You will need to manually check for the factor parameter; the random function does not handle that. You could generate a number between min/f and max/f then multiply by f as your final result.

Upvotes: 1

Related Questions