Math.random Scenario

j.doe

Example 1: 50 + (int)(Math.random() * 50) returns an integer between 50 and 99. The maximum number in decimal form being 99.9 recurring.

Example 2: 34 + (int)(Math.random() * 21) returns an integer between 34 and 55. The maximum number in decimal form being 54.9 recurring.

Why is it that example 2 returns 55 and not 54?

Cup of Java

Math.random() returns a decimal in the range of [0.0, 1.0),

So your assumptions are correct in each example

For the first example, 50 + 49.9 = 99.9

For the second example, 34 + 20.9 = 54.9

I am not sure where you are getting 55 for example two because when the decimal is cast to an int, the decimal will lose its precision, effectively rounding it down to create the max of 99 for example 1 and 54 for example 2

Edit

The book is wrong, if you wanted the range to be 34 to 55, the code would have to be

34 + (int)(Math.random() * 22)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Is it possible for Math.random() === Math.random()

From Dev

Javascript Math.random() not *that* random…?

From Dev

Math.Random is not so random

From Dev

Math.random not working

From Dev

Math & JavaScript | Random chances

From Dev

Arrays Random Multiplication Math

From Dev

Java Math.random() How random is it?

From Dev

Math.random number of random bits

From Dev

Java Math.random not random in while loop

From Dev

Math.Random() To pick random array

From Dev

Making Math.random() more random?

From Dev

Math.random number of random bits

From Dev

Math.Random() To pick random array

From Dev

PHP math with random numbers with random mathematical symbols

From Dev

Why Math.random() type is number and Math.random is function?

From Dev

Lua math.random not working

From Dev

Type Casting Math.random?

From Dev

Math.random in regards to arrays

From Dev

Lua Math.random and if statement

From Dev

Java Math.random period

From Dev

Math.random() problems in method

From Dev

Java Math.random() concern

From Dev

Javascript - Math.random as parameter

From Dev

Randomizing webpages with math.random

From Dev

Random math generation algorithm not working

From Dev

How does the distribution of Math.random()*50 + Math.random()*20 compare to Math.random()*70?

From Dev

Is generating and concatenating 3 Math.random() values more random than 1 Math.random() value?

From Dev

Is generating and concatenating 3 Math.random() values more random than 1 Math.random() value?

From Dev

Difference between math.random() and math.randomseed() in Lua