Python-Java flame-war, anyone?
Python-Java flame-war, anyone?
1. int foo = (int) Math.random() * some_max_value;
The error here is assuming that the multiplication takes place before the truncation. This isn't happening in the Python code because int(expression to truncate) is unambiguous. (+1 to Python here for making it hard to shoot yourself in the foot).
2. int foo = (int) Math.random();
The error here is assuming that Math.random returns something outside [0.0, 1.0). This is the error that all five of the Python examples are showing. (Boo to Python AND Java programmers.)
I can't speak for Python, but in Java it's quite simple to do it right; Random#nextInt(int) "Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)" (also consider using SecureRandom).
public class example
{
public static void main(String[] JAVA_LOL) throws Throwable
{
// prints "6"
System.out.println((int)6.99999);
}
}random.randint(a, b) returns a uniformly distributed int value between a (inclusive) and b (inclusive).
</nitpick>
ducks
All joking aside, I'm just pointing out the absurdity of comparing one language to another based on how easy it is to shoot oneself in the foot.
I bet those 5 were written by folks with more (or stronger) skill with C/C++/Java other strongly typed language where casting is required/common.
Casting is uncommon and "weird" in Python. Usually means you're being unpythonic. As in this case you should be using randint or randrange rather than cast to int.
a = random.randrange(10000)