Search code examples
node.jsrandom

Random number generator does not produce an expected answer Node JS


In a Node JS script, a formula is being used to generate a random number between two values. Here is the function randomIntInc:

function randomIntInc(low, high) {

return Math.floor(Math.random() * (high - low + 1) + low);

}

The function is called with two values as low and high:

let randomNumber = randomIntInc(requestedStart, requestedEnd);

console.log(requestedStart) before executing the above line produces 542 (expected)

console.log(requestedEnd) before executing the above line produces 592 (expected)

Now, running the above line and logging the output produces any value, generally within 6 and 50.

What is happening? Logging before executing the random number shows the correct ranges, but the outputted number just does not fall within the given range.


Solution

  • It appears the returned JSON is storing the values assigned to requestedStart and requestedEnd as strings rather than numbers. If that is the case, you will need to convert them to numbers before performing the arithmetic for the random number range.

    function randomIntInc(low, high) {
      console.log({
        low,
        high,
        '(high - low) + 1': (high - low) + 1,
        '(high - low + 1) + low': (high - low + 1) + low
      });
    
      return Math.floor(Math.random() * (high - low + 1) + low);
    }
    
    console.log({
      strings: randomIntInc('10', '20'),
      numbers: randomIntInc(10, 20)
    });

    Stepping through the string invocation, '10' and '20', results in the following operations:

    1. ('20' - '10' + 1): the order of operations will cause the subtraction operations to be done first which will automatically convert both strings to numbers and result in 10. The final addition will simply add the two number and produce 11.
    2. The key part is the last addition which attempts to add a number with a string. This will cause the number, '11', to be converted to a string and then concatenated with the string, '10', which results in '1110'. This can be confusing unless you remember that the addition symbol is also used for string concatenation.
    3. Finally the multiplication uses the random number times a string value of '1110' which results in a value of 0 - 11.1.