Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (481)
Games in Android Showcase (110)
games submitted by our members
Games in WIP (548)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1] 2
  ignore  |  Print  
  Is It Okay To Static-ify Random?  (Read 2037 times)
0 Members and 1 Guest are viewing this topic.
Offline wessles

JGO Wizard


Medals: 66
Projects: 4
Exp: 3 years


Profile picture isn't relevant.


« Posted 2013-10-19 00:03:25 »

I am tired of making an object for random every time I want to do something random. Can I just make a class and use it like this:
1  
2  
RandomClass.nextBoolean();
// RandomClass just wraps around a Random object.

As apposed to
1  
2  
3  
4  
Random rand = new Random();
// ...
if(rand.nextBoolean())
    printCrap();

Offline Abuse

JGO Knight


Medals: 12


falling into the abyss of reality


« Reply #1 - Posted 2013-10-19 01:06:15 »

I personally wouldn't, but yes you can do that.

Things to watch out for are:

- threading; while Random is thread-safe, the class warns concurrent use across threads can cause contention issues.
- determinism; if you need it, you'll find you have to redesign your code.
- lazy design; do this for Random, and you might find yourself static-ifying other more important stuff. [yoda quote here, relating to dark path & dominated destiny].

Make Elite IV:Dangerous happen! Pledge your backing at KICKSTARTER here! https://dl.dropbox.com/u/54785909/EliteIVsmaller.png
Offline wessles

JGO Wizard


Medals: 66
Projects: 4
Exp: 3 years


Profile picture isn't relevant.


« Reply #2 - Posted 2013-10-19 01:30:26 »

Don't worry. Nothing else will be staticified. I decided that every time you ask for a nextFloat, or nextInt, it refreshes the seed to the millis of the day * some mumbo jumbo... Sounds like it will work.

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline opiop65

JGO Kernel


Medals: 154
Projects: 7
Exp: 3 years


JumpButton Studios


« Reply #3 - Posted 2013-10-19 01:46:05 »

Quote
I decided that every time you ask for a nextFloat, or nextInt, it refreshes the seed to the millis of the day * some mumbo jumbo... Sounds like it will work.
You do know how the random class works right?

Offline SHC
« Reply #4 - Posted 2013-10-19 13:16:58 »

I personally prefer
Math.random()
for the same reason as you. Some methods for you with documentation.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
/**
 * Returns a random real number between 0 and x. The number is always
 * smaller than x.
 *
 * @param x The maximum range
 * @return A random real number
 */

public static int random(int x)
{
    return (int)(Math.floor(Math.random() * x));
}

/**
 * Returns a random real number between x1 (inclusive) and x2 (exclusive).
 *
 * @param x1 The inclusive
 * @param x2 The exclusive
 * @return A random real number between x1 and x2
 */

public static int random_range(int x1, int x2)
{
    return (int)(Math.floor(x1 + (Math.random() * (x2 - x1))));
}

My
GUtil
class if you want more functions. You are warned that this class is older than 2 years and is used with Java2D.

If you want to use booleans, try this.

1  
2  
3  
4  
public static boolean random_boolean()
{
    return random(2) == 0;
}

Hope this helps.

Offline Dxu1994
« Reply #5 - Posted 2013-10-19 14:24:25 »

I personally prefer
Math.random()
for the same reason as you. Some methods for you with documentation.

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
/**
 * Returns a random real number between 0 and x. The number is always
 * smaller than x.
 *
 * @param x The maximum range
 * @return A random real number
 */

public static int random(int x)
{
    return (int)(Math.floor(Math.random() * x));
}

/**
 * Returns a random real number between x1 (inclusive) and x2 (exclusive).
 *
 * @param x1 The inclusive
 * @param x2 The exclusive
 * @return A random real number between x1 and x2
 */

public static int random_range(int x1, int x2)
{
    return (int)(Math.floor(x1 + (Math.random() * (x2 - x1))));
}

My
GUtil
class if you want more functions. You are warned that this class is older than 2 years and is used with Java2D.

If you want to use booleans, try this.

1  
2  
3  
4  
public static boolean random_boolean()
{
    return random(2) == 0;
}

Hope this helps.

You're doing an awful lot of conversions from int->double and vice-versa there. A better implementation would be:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
package renoria.util;

/**
 * Random utility... o.O!
 * @author David
 */

public final class RandomUtil {
   /**
    * State of this object cannot be trusted, so always use this for a random number you don't care about synchronizing
    */

    public static final MersenneTwister rand = new MersenneTwister();

    private RandomUtil() {}

    public static long choose(long... args) {
        int choice = rand.nextInt(args.length - 1);

        return args[choice];
    }

    public static double choose(double... args) {
        return args[rand.nextInt(args.length - 1)];
    }

    public static char choose(char... args) {
        return args[rand.nextInt(args.length - 1)];
    }

    public static Object chooseObject(Object... args) {
        return args[rand.nextInt(args.length - 1)];
    }

    public static int range(int lbound, int ubound) {
        return (rand.nextInt(ubound - lbound + 1)) + lbound;
    }

    public static float range(float lbound, float ubound) {
        return (rand.nextFloat() * (ubound - lbound + 1)) + lbound;
    }

    public static boolean bool() {
        return rand.nextBoolean();
    }
}


I use MersenneTwister here but you can easily just drop in java.util.Random.

Offline wessles

JGO Wizard


Medals: 66
Projects: 4
Exp: 3 years


Profile picture isn't relevant.


« Reply #6 - Posted 2013-10-19 18:49:51 »

Quote
I decided that every time you ask for a nextFloat, or nextInt, it refreshes the seed to the millis of the day * some mumbo jumbo... Sounds like it will work.
You do know how the random class works right?
Could you elaborate? This doesn't help too much...

Offline opiop65

JGO Kernel


Medals: 154
Projects: 7
Exp: 3 years


JumpButton Studios


« Reply #7 - Posted 2013-10-19 18:51:05 »

The random class is seeded to the time of day since I believe 1980. Just making random static doesn't mean it will stop seeding its numbers.

Online Roquen
« Reply #8 - Posted 2013-10-19 19:16:24 »

Don't worry. Nothing else will be staticified. I decided that every time you ask for a nextFloat, or nextInt, it refreshes the seed to the millis of the day * some mumbo jumbo... Sounds like it will work.
That's a really bad idea.  Random number will now be correlated which is opposite of what you want.  It's almost this:



Quote
I use MersenneTwister...
My strong suggestion is to not use MT unless you need a supercomputer to run your program.

(EDIT: typo)
Offline wessles

JGO Wizard


Medals: 66
Projects: 4
Exp: 3 years


Profile picture isn't relevant.


« Reply #9 - Posted 2013-10-19 19:23:20 »

So just use Math.random() like said?

Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Riven
« League of Dukes »

JGO Overlord


Medals: 781
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #10 - Posted 2013-10-19 20:22:19 »

1  
2  
3  
    public static float range(float lbound, float ubound) {
        return (rand.nextFloat() * (ubound - lbound + 1)) + lbound;
    }

Who cares about upper bounds Smiley

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Offline Cero
« Reply #11 - Posted 2013-10-20 02:22:40 »

I use

1  
2  
3  
4  
5  
6  
7  
8  
9  
    public static final int getRandom(int minimum, int maximum)
    {
        return (int)(Math.random()*((maximum+1)-minimum)+minimum);
    }

    public static final float getRandom(float minimum, float maximum)
    {
        return (float)(Math.random()*((maximum+1)-minimum)+minimum);
    }


first: never be afraid of static - we use it a lot. Everbody should know about best practises in programming but also realize that programming a game with a limited amount of people is different from working at a huge codebase, written to be reused in other projects and so forth.

second: on the topic of random.
the question is how good has your random got to be here ? if you just want some random movement for example, thats a different level of concern that having a droprate in a game which can directly influence a mmo's global economy or might even be abused
but in usual cases the static way is absolutely fine
Seeds are great for testing - IF this particular part of the code will ever need test with these random values

Offline namrog84

JGO Ninja


Medals: 46
Projects: 4


Keep programming!


« Reply #12 - Posted 2013-10-20 05:05:15 »

seeded to the time of day since I believe 1980.

Jan 1st, 1970 00:00:00

I answered this in a trivia competition today and I won $10 itunes card...

What am I gonna do with this pointless card?  Emo Huh

"Experience is what you get when you did not get what you wanted"
Offline SHC
« Reply #13 - Posted 2013-10-20 05:14:31 »

What am I gonna do with this pointless card?  Emo Huh

Give it to me!  Grin

Offline opiop65

JGO Kernel


Medals: 154
Projects: 7
Exp: 3 years


JumpButton Studios


« Reply #14 - Posted 2013-10-20 10:40:16 »

seeded to the time of day since I believe 1980.

Jan 1st, 1970 00:00:00

I answered this in a trivia competition today and I won $10 itunes card...

What am I gonna do with this pointless card?  Emo Huh
Damn, I knew I was wrong! Fine, you win Smiley

Offline Riven
« League of Dukes »

JGO Overlord


Medals: 781
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #15 - Posted 2013-10-20 11:42:19 »

1  
2  
3  
    public static float range(float lbound, float ubound) {
        return (rand.nextFloat() * (ubound - lbound + 1)) + lbound;
    }


1  
2  
3  
4  
    public static final float getRandom(float minimum, float maximum)
    {
        return (float)(Math.random()*((maximum+1)-minimum)+minimum);
    }

Who cares about upper bounds Smiley

Seriously dudes, test your code.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Offline namrog84

JGO Ninja


Medals: 46
Projects: 4


Keep programming!


« Reply #16 - Posted 2013-10-20 16:57:48 »

@Riven

I feel like I am missing something about it?

Why are we 'not caring about upper bounds' ?

What if I wanted a number between 90 and 100
Sure, one could just write Math.random()*10 + 90   but they could also write getRandom(90,100) as well ?  I mean I guess its not really much more or less code but with the method it seems a little more clear?

"Experience is what you get when you did not get what you wanted"
Offline Riven
« League of Dukes »

JGO Overlord


Medals: 781
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #17 - Posted 2013-10-20 17:04:52 »

They add 1.0f. Which is barely defendable for integers, but flat out wrong for floats.


Their methods return values with the upper bound increased by 1.0:
1  
2  
range(0.2f, 0.5f) => returns values between 0.2f and 1.5f
getRandom(-0.3f, 1.5f) => returns values between -0.3f and 2.5f


Given this bug is so obvious, and guaranteed to return out of range values often, it's hard to believe that:
this class is older than 2 years

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Offline namrog84

JGO Ninja


Medals: 46
Projects: 4


Keep programming!


« Reply #18 - Posted 2013-10-20 17:05:26 »

Hah!  Brilliant   Grin Tongue

"Experience is what you get when you did not get what you wanted"
Offline Cero
« Reply #19 - Posted 2013-10-20 18:25:50 »

They add 1.0f. Which is barely defendable for integers, but flat out wrong for floats.
It worked for ints so I did it and never ever looked at it.
Sometime I needed a float one, didn't think about it and just changed int to float, never really tested it.

Given this bug is so obvious, and guaranteed to return out of range values often, it's hard to believe that:
this class is older than 2 years
Actually older for me...
Mostly used the int one though

Offline Cero
« Reply #20 - Posted 2013-10-20 18:31:18 »

Should be

1  
2  
3  
4  
    public static final float getRandom(float minimum, float maximum)
    {
        return (float)(Math.random()*(maximum-minimum))+minimum;
    }

While it is implied that maximum is higher than minimum

Offline Riven
« League of Dukes »

JGO Overlord


Medals: 781
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #21 - Posted 2013-10-20 20:15:41 »

They add 1.0f. Which is barely defendable for integers, but flat out wrong for floats.
It worked for ints so I did it and never ever looked at it.
Sometime I needed a float one, didn't think about it and just changed int to float, never really tested it.

What you were looking for was adding one ulp, to include the upper bound value in the returned range.

For integers that's 1, for floats and doubles that's very close to zero.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Online Roquen
« Reply #22 - Posted 2013-10-20 20:44:21 »

[1,1] -> mapToPMO
Offline wookoouk

Senior Newbie





« Reply #23 - Posted 2013-10-21 19:52:34 »

I use
1  
int myRand = new random().nextInt();


if it HAS to be static-ish

(although I am sure many of you are cringing reading this)
Offline opiop65

JGO Kernel


Medals: 154
Projects: 7
Exp: 3 years


JumpButton Studios


« Reply #24 - Posted 2013-10-21 19:55:04 »

I use
1  
int myRand = new random().nextInt();


if it HAS to be static-ish

That isn't static though...

Offline wookoouk

Senior Newbie





« Reply #25 - Posted 2013-10-21 19:56:31 »

It can be used in a static method... Thats all the static I ever need Wink
Online Roquen
« Reply #26 - Posted 2013-10-21 19:57:12 »

The biggest problem with random number generation is people using them is in a bad way.  Creating a new generator each time you use one is again one step away from the XKCD code (return 4) above.

(EDIT: typo...again...I'm badly correlated...yuck yuck)
Offline opiop65

JGO Kernel


Medals: 154
Projects: 7
Exp: 3 years


JumpButton Studios


« Reply #27 - Posted 2013-10-21 20:00:04 »

It can be used in a static method... Thats all the static I ever need Wink
That still isn't static though. If you create a new instance of your 'static' object, except for at runtime, then why use static at all? Just create a new instance of the random class and don't deal with static at all. Or, do it right and create one instance of the static object for the whole program to call upon.

Offline wookoouk

Senior Newbie





« Reply #28 - Posted 2013-10-21 20:06:06 »

oh, totally agreed. btw, isnt having a static random almost as bad as having a static method for println?
Offline opiop65

JGO Kernel


Medals: 154
Projects: 7
Exp: 3 years


JumpButton Studios


« Reply #29 - Posted 2013-10-21 20:11:43 »

No, using static is just tricky in general. You use a static reference to println everytime you call System.out.println
If the print method wasn't static, you'd have to create a new instance of System everytime you'd want to print something out, and that would be a pain in the ass seeing as the console is mainly use for debugging, and these print statements are usually deleted anyway.

Static is tricky because you need to be careful about what you add static to. You should google the theory behind the static keyword. I used to, when I first started out, use static all the time, I just didn't understand what it was. Now I avoid it if possible like the plague.

Pages: [1] 2
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

atombrot (27 views)
2014-08-19 09:29:53

Tekkerue (25 views)
2014-08-16 06:45:27

Tekkerue (23 views)
2014-08-16 06:22:17

Tekkerue (15 views)
2014-08-16 06:20:21

Tekkerue (22 views)
2014-08-16 06:12:11

Rayexar (61 views)
2014-08-11 02:49:23

BurntPizza (39 views)
2014-08-09 21:09:32

BurntPizza (31 views)
2014-08-08 02:01:56

Norakomi (37 views)
2014-08-06 19:49:38

BurntPizza (67 views)
2014-08-03 02:57:17
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!