Skip to content
Fix Code Error

Math.random() explanation

March 13, 2021 by Code Error
Posted By: Anonymous

This is a pretty simple Java (though probably applicable to all programming) question:

Math.random() returns a number between zero and one.

If I want to return an integer between zero and hundred, I would do:

(int) Math.floor(Math.random() * 101)

Between one and hundred, I would do:

(int) Math.ceil(Math.random() * 100)

But what if I wanted to get a number between three and five? Will it be like following statement:

(int) Math.random() * 5 + 3

I know about nextInt() in java.lang.util.Random. But I want to learn how to do this with Math.random().

Solution

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

Output of randomWithRange(2, 5) 10 times:

5
2
3
3
2
4
4
4
5
4

The bounds are inclusive, ie [2,5], and min must be less than max in the above example.

EDIT: If someone was going to try and be stupid and reverse min and max, you could change the code to:

int randomWithRange(int min, int max)
{
   int range = Math.abs(max - min) + 1;     
   return (int)(Math.random() * range) + (min <= max ? min : max);
}

EDIT2: For your question about doubles, it’s just:

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

And again if you want to idiot-proof it it’s just:

double randomWithRange(double min, double max)
{
   double range = Math.abs(max - min);     
   return (Math.random() * range) + (min <= max ? min : max);
}
Answered By: Anonymous

Related Articles

  • What is the worst programming language you ever worked with?
  • How can I resolve Web Component Testing error?
  • Examples of GoF Design Patterns in Java's core libraries
  • How to convert image into byte array and byte array…
  • JUNIT @ParameterizedTest , Parameter resolution Exception
  • Generating random whole numbers in JavaScript in a…
  • How to convert number to words in java
  • Dynamically update values of a chartjs chart
  • assign flexbox cells the same width
  • Increasing size of semi circle using css
  • When I'm testing a web app by JUnit and Mockito I…
  • SecurityException: Permission denied (missing…
  • Tokenize mathematic string expression
  • How to prevent scrolling the whole page?
  • Unable to run Robolectric and Espresso with a…
  • center 3 items on 2 lines
  • Eclipse will not start and I haven't changed anything
  • How to print binary tree diagram?
  • java.lang.ClassNotFoundException: HttpServletRequest
  • android studio 0.4.2: Gradle project sync failed error
  • TLS 1.3 server socket with Java 11 and self-signed…
  • ClassNotFoundException:…
  • Generate single complex JSON object from PostgreSQL query
  • Checking if a variable is an integer in PHP
  • Could not install Gradle distribution from…
  • Neither BindingResult nor plain target object for…
  • How to convert java.util.Date to java.sql.Date?
  • Design DFA accepting binary strings divisible by a…
  • org.springframework.beans.factory.NoSuchBeanDefiniti…
  • Generate new observations based on IF statement R
  • How do SO_REUSEADDR and SO_REUSEPORT differ?
  • Pandas pivot_table: filter on aggregate function
  • Jetpack Compose and Hilt Conflict
  • SQLException: No suitable Driver Found for…
  • How to show title in hover - css / jquery
  • Plotting curve over several subplots in R
  • Why does C++ code for testing the Collatz conjecture…
  • Changes do not get reflected when getting property by name
  • Explanation on Integer.MAX_VALUE and…
  • How to re-size polygon in jPanel?
  • Active tab issue on page load HTML
  • Python: got an output image with unexpected grid lines
  • Nexus 7 not visible over USB via "adb devices" from…
  • No function matches the given name and argument types
  • java IO Exception: Stream Closed
  • How to use html template with vue.js
  • Requested bean is currently in creation: Is there an…
  • Reference - What does this regex mean?
  • VueJS with normal JavaScript
  • Android- Error:Execution failed for task…
  • Can't access Eclipse marketplace
  • Three.js: Cannot display mesh created with texture array
  • Vue, TypeScript Can't Call Component Methods
  • How do I generate a random integer between min and…
  • Tomcat 7 "SEVERE: A child container failed during start"
  • Java 8 stream's .min() and .max(): why does this compile?
  • How to parse JSON file with Spring
  • Launching Spring application Address already in use
  • Auto-fit TextView for Android
  • Using enums in a spring entity
  • easiest way to extract Oracle form xml format data
  • Gradle error: Execution failed for task…
  • Eclipse - Run in Debug Mode fails
  • How do I keep only the first map and when the game…
  • Jetty server throws idle timeout for REST calls
  • Exception in thread "JobGenerator"…
  • Start redis-server with config file
  • Why do we use __init__ in Python classes?
  • Which is more efficient, a for-each loop, or an iterator?
  • Modelling an elevator using Object-Oriented Analysis…
  • Getting started with Haskell
  • Converting between color models
  • Using setInterval for creating animation
  • Add JsonArray to JsonObject
  • Partition a Dataset according to the Min & Max…
  • Execution failed for task…
  • C Program to Mark as "Min" and "Max" from the array…
  • What's the difference between eval, exec, and compile?
  • For-each over an array in JavaScript
  • Sort table rows In Bootstrap
  • How do I convert a float number to a whole number in…
  • Vaadin Spring Boot - There was an exception while…
  • How do I install Java on Mac OSX allowing version switching?
  • multi level ul li backbone.js
  • Find Minimum and Maximum in given array where…
  • How to convert a string to an integer in JavaScript?
  • CSS animate a conical gradient as border image
  • JPA Hibernate Persistence exception…
  • Fastest way to iterate over all the chars in a String
  • Name [jdbc/mydb] is not bound in this Context
  • What's the difference between Instant and LocalDateTime?
  • How to read strings from a Scanner in a Java console…
  • javaScript - Uncaught TypeError: Cannot read…
  • python max function using 'key' and lambda expression
  • Drawing a simple line graph in Java
  • Ember.js: rendering google chart in template (AKA…
  • Mock MQRFH2 header in JUnit Testing Error [MQRFH2…
  • how to get the df names and first input value for…
  • How do you round a floating point number in Perl?
  • DataTable draw daterange from vaadin-date-picker in polymer

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Use of “instanceof” in Java

Next Post:

How to uninstall Python 2.7 on a Mac OS X 10.6.4?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error