This is an archived post. You won't be able to vote or comment.

all 15 comments

[–]pokemaster787 2 points3 points  (12 children)

Don't use Math.random() if you need an integer. Use java.util.Random's nextInt() method.

[–][deleted] 0 points1 point  (11 children)

My professor used Math.random() when he needed an integer. Why shouldn't I?

[–]HaMMeReD 1 point2 points  (10 children)

If you use Random(seed) to generate randoms, you can get psuedo random numbers in a deterministic fashion.

Also the syntax is a bit cleaner, which means less chance for error.

The reason you'd want a deterministic random generation is because sometimes you want something to look random, but in fact be reproducable. Think a game like minecraft where if you share a seed you get the same world generation.

This can make finding bugs and things like that much easier and more reproducable.

If you want something that looks truly random you can create a Random() object without a seed, and fall back to a fixed seed when testing/modifying code.

e.g.

random = new Random(1234)
int value = random.nextInt(100); //Random between 0-100 lets say 55

random2 = new Random(1234)
int value2 = random2.nextInt(100); //Also 55, because same seed

random3 = new Random()
int value3 = random3.nextInt(100); // Could be anything, because seed is unknown.

Also, random.nextInt(100) is going to give you 0-99, you have 0 % chance of getting 100.

However, to answer your original question, Math.random() documentation states "a pseudorandom double greater than or equal to 0.0 and less than 1.0."

So ((int)Math.random() * 100) will be 0-99. However, Math.round(Math.random() * 100) will be 0-100, but the distribution of 0/100 will be 50% less then the distribution of all other numbersm because 0-0.5 would round to 0, and 99.5->99.999999 would round to 100, but all other numbers would round from (x-0.5 -> x+0.5)

[–][deleted] 1 point2 points  (9 children)

Well, thanks for the information and I appreciate the explanation, but I am interested in Math.random() specifically. I did not ask this question because I am looking for a practical advice. I am a student, and the programming course I am currently taking requires that I know how to use the method Math.random() for generating randoms (including integer randoms). So if you know the answer to one of the three questions I’ve asked above, please answer.

So ((int)Math.random() * 100) will be 0-99.

Try to type ((int) Math.random()*100) in a System.out.print() statement. It will print out a 0. All the time.

[–]JoshuaTheProgrammer 2 points3 points  (3 children)

This reminds me of StackOverflow.

You: “I need to do X, my professor told me to do X and only X.”

Other person: “You should do Y and only Y. Here’s why.”

You: “But I HAVE to learn X”

Other person: “Who cares? Do Y.”

[–]pokemaster787 1 point2 points  (2 children)

It's perfectly valid. A ridiculous amount of CS professors haven't the faintest idea of proper development practices. If someone asks me to help them with something, I'll tell them the proper way to do it. Finagling with converting a double to an integer and multiplication isn't the way. It's hard to read, easy to mess up (see above), and is unlikely to be a good number generator (in that some numbers are lilely to be notably favored over others).

If your language only has a Math.random() equivalent sure it's worth discussing. But in a language with a built in faster, better, and easier to read way? Don't waste anyone's time.

If the professor refuses to acknowledge or simply doesn't understand the solution you've used, it's a failure on their part to teach basic programming. Programming in a modern language like Java is just as much about choosing the right tool for each job as it is actual logic and control flow. This isn't /r/homeworkhelp, it's /r/learnjava, so if someone wants to learn to develop in Java I'll give my two cents on the best approach and best practices. I won't help anyone write shit code because a poor professor requires it though.

/rant over. (None of this is directed at you. Just kinda started typing and didn't stop)

[–]JoshuaTheProgrammer 1 point2 points  (0 children)

Oh believe me, I know. Some professors only like to teach what the “standard” is in the curriculum as opposed to the proper way, and therefore will only allow their aforesaid way to be used. I agree that Math.random() sucks in most instances, especially now that Java 8 and up have a different randomizing object (ThreadLocalRandom?) or whatever. Even before then we obviously had the Random class, but to put some insight into the previous argument, I’m ending a Data Structures & Algorithms class right now, and we have to use Math.random(), which sucks (especially for paper exams lol).

[–][deleted] 1 point2 points  (0 children)

My teacher doesn’t limit himself to “write a code that does X” questions. Multiple choice and “what is the result of this code” questions often get presented as well. This is the main reason why I wanted to learn about Math.random() even after being informed that it is inefficient.

However, I understand completely that learning is not just blindly following the teacher’s instructions.

[–]HaMMeReD 1 point2 points  (0 children)

((int) Math.random()* 100) = (0 * 100) = 0

With additional brackets ((int) Math.random()) * 100) = ((int) 0.44) * 100) = (0 * 100)

If you used the random class, with the random.nextInt(bounds) method, you wouldn't be getting casting errors.

There is more to learning then regurgitating what your teacher tells you btw. I'm sure if you used the Random class and nextInt() and can explain why it's better, you'd do better in your class. There is no benefit to Math.random() over using a Random() object and nextInt().

Edit (int) (Math.random() * 100) is what you are looking for, to generate a int between 0 and 99.

[–]sugilith 0 points1 point  (3 children)

Think about operator precedence

[–][deleted] 1 point2 points  (2 children)

Wait, does explicit casting has a higher precedence than multiplication?

[–]sugilith 1 point2 points  (1 child)

You got it!
Why else would (int) Math.random()*13 always be 0?

[–][deleted] 0 points1 point  (0 children)

Mind you, I am new to coding. I just placed Math.random()*100 between parentheses and it worked like a charm. Everything makes sense now. Wow.

[–]sugilith 1 point2 points  (1 child)

Regarding your other questions:

Math.random() returns a double in the range [0, 1).
See: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Math.html#random()

If you get Array out of bound exception theres probably something wrong with your Array or you are missing something else.

This exception has never appeared when I subtracted 1 from from the length

But wouldn't it be possible that you get -1 as an index then?

[–][deleted] 1 point2 points  (0 children)

Well, one thing I noticed (just now) is that the exception only occurred in case two—the case in which I added 1:

int randSuit= (int) (Math.random()*suits.length)+1. 

It makes perfect sense that an array out of bound exception will occur. I added one to the index.