Ethameshep
Ethameshep

Reputation: 31

Javascript: Generate random number using a range inside a range

I am trying to make a number simulation that functions as follows:

  1. Begins at baseline value
  2. Generates random value within given range of baseline
  3. Takes generated value and generate another value within same range
  4. All generated values remain within a larger range

So if I have a starting value of 5, I need it to generate a number within a range of say 2. It then needs to take that value (between 3 and 7) and generate another number with the same range of 2, and so on. But I also need any numbers generated to stay between 0 and 10.

I can use random() with a single defined range, but I don't know how to do two:

function generateValue(min, max) {
    var max = 2,
        min = 0,
        value = (Math.random() * (max - min) + min).toFixed(6);
    return value;
}

Upvotes: 1

Views: 313

Answers (2)

RaphaMex
RaphaMex

Reputation: 2839

Here is your function. Its parameter is the baseline value. You can make min, max, range parameters too if you wish:

function generateValue(value) {
    let max = 10,
        min = 0,
        range = 2,
        newValue = value; // Start at baseline value
    newValue += (2 * Math.random() - 1) * range; // Generate new value within +/- range
    return (newValue < min ? min : // Cannot be lower than min
            newValue > max ? max : // Cannot be greater than max
            newValue);
}

Upvotes: 0

Boris Lobanov
Boris Lobanov

Reputation: 2454

You need a function that accepts 4 arguments: baseline, range, min and max (if I understand you correctly). Also, I believe you had a mistake in you formula for getting a random number from a range. Here's a function that does what you need, I think:

function generateValue(baseline, range, min, max) {
    let localMin = Math.max(baseline - range, min);
    let localMax = Math.min(baseline + range, max);

    return (Math.random() * (localMax - localMin) + localMin).toFixed(6);
}

Upvotes: 2

Related Questions