"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Methods for generating random integers and double precision numbers in a specific range in Java

Methods for generating random integers and double precision numbers in a specific range in Java

Posted on 2025-04-14
Browse:680

How to Generate Random Integers (and Doubles) Within a Specific Range in Java?

Math.random() Manipulation: Generating Random Integers Within a Specified Range

The Java function Math.random() generates random numbers within the range [0, 1). However, there are situations where you may need to obtain random integers within a specific range. This article demonstrates how to achieve this using Math.random().

Intention to Generate a Random Integer Between Three and Five

While the statement "(int) Math.random() * 5 3" does not correctly generate random integers within the range [3, 5], it can be corrected using a custom method:

int randomWithRange(int min, int max) {
    int range = (max - min)   1;
    return (int) (Math.random() * range)   min;
}

This method calculates the range of possible values, multiplies it by Math.random(), and adds the minimum value to ensure inclusivity.

Output Example

System.out.println(randomWithRange(3, 5));
// Output: 3

Idiot-Proofing for Incorrect Ordering

To prevent errors if min is greater than max, an updated method is:

int randomWithRange(int min, int max) {
    int range = Math.abs(max - min)   1;
    return (int) (Math.random() * range)   (min 

Extensions for Double Random Number Generation

A similar method can be used to generate random double-precision numbers:

double randomWithRange(double min, double max) {
    double range = (max - min);
    return (Math.random() * range)   min;
}

Using this method:

System.out.println(randomWithRange(3.0, 5.0));
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3