开发者

What is the best way to create a random value?

I am triying to create random value for my game to show enemies on screen. BUt it some times shows 2 together some times 3 ...I want to ask that which is the best formul for creatin开发者_高级运维g random value.. This is my so far random value

 random = 1 * (int) (Math.random() * 100);


"BUt it some times shows 2 together some times 3"

Given perfectly random numbers... In every 100 random values from 0 to 99, you'll find an average of 1.0 doubles. A triple will occur on average once for every 10,000 values. Given 10 million random numbers, java.util.Random yeilds the following results on my machine:

Doubles: 99873
Triples: 985

Double Rate: 1 in 100
Triple Rate: 1 in 10152

Source code:

import static java.lang.System.*;

import java.util.Random;

public class Sandbox {
    public static final int NUM_ITERATIONS = 10000000;
    public static void main(String[] args) {
        Random rand = new Random();

        int cur;
        int last = -1;
        int secondLast = -2;
        int nDoubles = 0;
        int nTriples = 0;

        for (int i = 0; i < NUM_ITERATIONS; i++) {
            cur = rand.nextInt(100);
            if (cur == last) {
                nDoubles++;
                if (cur == secondLast) nTriples++;
            }
            secondLast = last;
            last = cur;
        }

        out.println("Doubles: " + nDoubles);
        out.println("Triples: " + nTriples);
        out.println();
        out.println("Double Rate: 1 in " + Math.round(1.0 * NUM_ITERATIONS / nDoubles));
        out.println("Triple Rate: 1 in " + Math.round(1.0 * NUM_ITERATIONS / nTriples));

        exit(0);
    }
}


Actually the creation of genuinely random random numbers is a complex game in its own right. The Wikipedia article on this subject will give you an insight into the complexity that lies therein. Simple approximations such as those outlined above are probably sufficient for game purposes but will, it should be noted, be inclined to be 'streaky' from time to time.


You can use java.util.Random:

Random random = new Random(); // uses System.nanoTime() as seed
int enemies = random.nextInt(100);

Anyway, your approach is also fine, as it is in fact equivalent (behind the scene) with the above.

You can print a sequence of 100 random numbers generated your way and see for yourself that there isn't a problem.


What you use if perfectly fine.

In case you want something simplier you might like to use Random class like this:

Random generator = new Random(seed);
int number = generator.nextInt(100);


...and sometimes 77, sometimes 23, etc, as expected in a uniform distribution?

If you would like a normal distribution instead for your "enemies", so that extremes are less likely, it seems to be there in Java.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜