What methods does RM use to get Randomness?

If you're not familiar, nothing is ever truly random in the computer space.
Typically speaking randomness is generated on a multitude of factors that to any normal person, just seems random (either through mathematical formulae, date/exact time formulae, or other methods) but the truth is that it is not truly random.

The reason I am asking about this is that I've been recently working with a lot of randomly rolled variables, and through all of the play testing of these features, I've noticed that it seems to be biased towards specific numbers, especially noticeable in a 50/50 roll (0 or 1).
Take for example: I have a chest, it rolls a 50/50 chance, 50% chance a weapon, 50% chance an armor. There are 11 armors possible to obtain from the armor chest. Armors can only be obtained once. There are 29 chests. Yet somehow one play test I obtained all 11 armors and only 1 weapon (the rest of the chests awarded a "bunk" item which can be obtained in a few other ways from the chest not relevant to the discussion)
Other play tests have had a somewhat more balanced distribution of armor/weapons, though still favoring armor.
I mean, with randomness it is technically possible for that to happen - just the odds are really, really low; I just wonder if whatever algorithm RM uses may have a slight bias.
I'm hoping to figure out how the randomness works to see if I can't work around this bias or manipulate it to give at least slightly more fair odds.
It uses Javascript's standard pseudorandom number generator (Math.random) and that will never be perfect. It uses numbers between 0 and 1, so you're going to encounter rounding problems, which already creates inaccuracies. These inaccuracies are further reinforced by Math.floor operations.
I don't know how RM gets its RNG, but I do have a little plugin in one of my games, that makes it so the result is not repeated until a different roll was achieved. (Meaning if you got a variable between 0 and 1 for weapon or armor, the plugin will not give you the same result twice in a row, you would always get weapon>armor>weapon>armor because it rouldn't roll 0 twice in a row.

If that can help your cause, hit me up 😀
MV uses JavaScript's built-in Math.random() method to generate pseudorandom numbers. However, this unfortunately doesn't tell you a whole lot, because the algorithm being used to implement that method varies based on which browser is running the JavaScript.

In your case, the JavaScript is presumably being run through NW.js (which uses the V8 engine). However, the V8 engine has changed its algorithm for Math.random() a few times over the years, and I have no clue which version you've got. If you're using the version that came with MV, then you might try manually updating it something a bit less old and see if it helps any. (I use v0.48.4)

If you're using a fairly modern version of NW.js, then the algorithm being used should be reasonably decent--not at a level that is suitable for security purposes, but definitely at a level where you shouldn't be able to notice a glaring bias in your game.

Not to point fingers, but in my experience, issues with obvious RNG bias are usually not the fault of the random number generator itself, but moreso a product of how a programmer is choosing to use the random number generator and the resulting number. Would you perhaps be willing to show us the algorithm that you're using to do this random chest business, just to make sure that the issue doesn't lie there before digging deeper?
@Poryg Always glad to hear from you. You and Arthran I would definitely trust to know this kind of stuff. If it's rounding being the problem, then we just need to use more digits right? So I restructured the way the randomness is handled. Rather than binary 0 or 1, I changed it to a 0 or 99, and the conditional is just checking for 49 or less for one option and 50 or more for the other option.
I did 3 runs, with a tally of 17 armor, 15 weapons in total which seems way more balanced to me. Also with it set up like this I can always raise or lower the conditional to compensate for any bias.

@SGHarlekin Thanks for the plugin offer. Unfortunately it wouldn't work with what I have set up, since I am also using the same 0/1 randomness to do some level generation, so that plugin would effectively wind up creating a pattern rather than something that is perceived as pure randomness.

@Arthran I updated to 0.48.4 as well, if I remember correctly. You're welcome to point fingers, I'm pretty useless when it comes to this kind of stuff, but I think my method is fairly sound as it's just get a random variable. then a conditional: if the variable is x, do this. If it's y, do this instead. I'll continue to test the method I mentioned when addressing Poryg. If I continue to find a bias, I'll post some screen shots.
(I'm mostly lazy about doing this because the events are quite long, requiring a lot of screen shots, and I've been using a shorthand of "armor" and "weapons" in this thread to keep it simple, but it's a little bit more complicated than that, requiring a little bit of explanation.)
If it's rounding being the problem, then we just need to use more digits right?
This is not going to be possible. In Javascript every number is a 32bit float unless it's too big for that. And if we just use 0-9999 instead of 0-99, that won't really do us any favors either, because while changing Math.random()*100 for Math.random*10000 gives us higher precision before we round it down, it doesn't have any impact if we use the below 50% and above 50% algorithm.

What you can do to combat the initial rounding issue? Use other algorithms to determine the loot. For instance, since we're dealing with low and high numbers bias, it will help to spread the results across low and high numbers. Ergo, instead of using <50 and 50> you can use modulo 2 (aka odd and even). If the result is odd, you get armor, if even, you get weapons. This way you'll have both options spreaded out evenly among low and high numbers, mitigating a degree of the bias. Just keep in mind that division and modulo are the slowest arithmetic operations and are slower than if else, so don't do a million divisions at once. 😀

But it has its advantage.
Using the modulo operator will also mean that the higher you push the max value, the more precision you're going to receive before you Math.floor the number.
Also a warning, watch out if you need to use more than 2 possible results (for instance, let's say weapon/armor/shield/shoes/helmet/gloves). You'll have to use modulo x and you have to make sure that the number of possible results is divisible by the x. In our case it'd be modulo 6 and the numbers would go from 0-119 to give us 120 possible results, which are divisible by 6.
It's worth noting as well that MV and MZ use a custom function for random numbers in a lot of places that uses integers instead of 0-1: Math.randomInt. It takes the max value as a parameter, and gives you an integer from 0 to that number exclusive. It's just a wrapper for a multiplied Math.random though:

JavaScript:
Math.randomInt = function(max) {
    return Math.floor(max * Math.random());
};
It uses numbers between 0 and 1, so you're going to encounter rounding problems, which already creates inaccuracies. These inaccuracies are further reinforced by Math.floor operations.
I could be misunderstanding you, but I don't see a good reason why either of those things should matter in this situation.

Firstly, being a number between 0 and 1 shouldn't necessitate any rounding, since it's essentially a ratio. You can just scale it up, and then it's no longer a number between 0 and 1. For example, the ratio 0.75 is equivalent to 75%, even though one is a number between 0 and 1 and the other is a number between 0 and 100. All that matters is that they can be broken up into the same number of individual units. I.e: 0.01 / 1 = 1 / 100 = 10 / 1000 = 100 / 10000, etc. Sorry, I probably didn't explain that well, but I'm not a math teacher, so I don't know how to explain it any better than that.

And the Math.floor operation that is generally used in the process of converting the number isn't any type of detriment, since the algorithm properly accounts for (and actually relies on) it.

JavaScript:
Math.randomInt = function(max) {
    return Math.floor(max * Math.random());
};

Supposing that you want to randomly generate either a 0 or a 1, you would supply an argument of 2 to the above function. I'll just manually write out some possible scenarios, pretending that Math.random returns a floating point number with only two digits after the decimal:
Code:
Math.random Result | Result after (max * Math.random) | Result after Math.floor |
-------------------|----------------------------------| ------------------------|
0.00               | 2 * 0.00 = 0.00                  | 0                       |
-------------------|----------------------------------| ------------------------|
0.10               | 2 * 0.10 = 0.20                  | 0                       |
-------------------|----------------------------------| ------------------------|
0.20               | 2 * 0.20 = 0.40                  | 0                       |
-------------------|----------------------------------| ------------------------|
...
0.49               | 2 * 0.49 = 0.98                  | 0                       |
-------------------|----------------------------------| ------------------------|
0.50               | 2 * 0.50 = 1.00                  | 1                       |
-------------------|----------------------------------| ------------------------|
0.60               | 2 * 0.10 = 1.20                  | 1                       |
-------------------|----------------------------------| ------------------------|
0.70               | 2 * 0.70 = 1.40                  | 1                       |
-------------------|----------------------------------| ------------------------|
...
0.99               | 2 * 0.99 = 1.98                  | 1                       |
-------------------|----------------------------------| ------------------------|

I don't know if I depicted that in a way that makes sense at all, but basically... any time Math.random() generates a value from 0.00 to 0.49, the end result is 0. Any time it generates a value from 0.50 to 0.99, the end result will be 1. This means that (in this example) there are exactly 50 possibilities that can yield a 0, and exactly 50 possibilities that can yield a 1, which in turn means that there is a proper 50% chance to get either a 0 or a 1 (provided that the internal implementation of Math.random() does yield an approximately uniform distribution). As you can see in the table, Math.floor doesn't hurt the precision of the result--rather it's a key component of the algorithm.

Of course, the number returned by Math.random() actually has a much higher precision than only two digits after the decimal, but that doesn't matter. Regardless, exactly half of the possible numbers that it returns are capable of yielding 0 as an end result, and exactly half are capable of yielding 1... so it's still a 50% chance. I simply went with two digits because it made the example easier to write and (presumably) read.

Just keep in mind that division and modulo are the slowest arithmetic operations and are slower than if else, so don't do a million divisions at once.
Sorry if this is pedantic, but just as an FYI, If the second operand is a power of 2, then it might actually be pretty fast, because there are some simple bit operations that can be used as shortcuts. For example, for modulo 2, you can actually just do a bitwise AND 1. In other words:
JavaScript:
(x % 2) == (x & 1)
And for division by 2, you just have to shift each bit one to the right (>> 1). However, I don't know whether or not V8 is smart enough to automatically make those optimizations, so you could do the bit operations manually to be on the safe side.


Rather than binary 0 or 1, I changed it to a 0 or 99, and the conditional is just checking for 49 or less for one option and 50 or more for the other option.
It shouldn't matter. Internally, JavaScript is generating a random number between 0 and 1 anyway, and you're just scaling it up after the fact.

I wrote a really simple test. Playtest your game, press F12, click on the Console tab, paste this code and press enter:
JavaScript:
(() => {
    const numTrials = 100000;
    let armors = 0;
    let weapons = 0;

    for (let i = 0; i < numTrials; i++) {
        if (Math.randomInt(2) == 0) {
            armors++;
        } else {
            weapons++;
        }
    }

    console.log(`Armors  = ${armors}\nWeapons = ${weapons}`);
    console.log(`Armor percent = ${armors / numTrials * 100}%`);
})();

What it will do is randomly generate either a 0 or a 1 (essentially the same way that RPG Maker would do it in a Control Variables: Random 0~1 event command) 100000 times, keep track of the frequency of each number, and tell you how many of each at the end (0 = Armors and 1 = Weapons). Just for reference, here are the results of me running it twice:
Code:
/* First run */
Armors  = 49855
Weapons = 50145
Armor percent = 49.855%

/* Second run */
Armors  = 50123
Weapons = 49877
Armor percent = 50.123%

To me, it doesn't seem that there's anything blatantly egregious going on. It would vary more widely if you're only running like 10 trials instead of 100000 (you can change the number of trials by changing the 100000 in the second line of code), but that's just how probability works. Of course, proper statistical testing of PRNG is a lot more complicated than this simple test, but the PRNG in a video game doesn't exactly have to be cryptographically secure (and for performance reasons, it probably shouldn't be), so I think this is good enough.

IMO, your initial playtests either had really crazy luck, or you may have a bug in your implementation.
Thanks for the explanation.
I think either 2 things happened. Either I just had crazy luck during the play test as you said, and subsequent play tests seemed normal as they coincided with my change to the RNG system, or when I revised my RNG system I had to redo a few aspects to work with the larger number, and by doing so I fixed some sort of error that I had that may have been biasing things previously.
Either way, whether the 0-99 system actually makes a difference or not doesn't really matter, it feels like it is making a difference, so much so I revised other parts of my random generation to use larger numbers and I feel like the generation feels more...organic? That feels like the wrong type of word to describe it, but you know what I mean; more correctly random.
Randomness is really interesting! (Wall of text incoming, hit the deck.)
Spoiler: PRNG
As mentioned, Math.random is a PRNG (pseudorandom), thus derives its randomness solely from its seed; everything thereafter is entirely deterministic, i.e. 100% predictable, given knowledge of the underlying algorithm. In other words, results are mutually dependent.

Last I checked, Chromium uses the xorshift-128 algorithm, offering 64 random bits. That means it technically cannot access result sets larger than 2^64, e.g. the full permutation space of a list of 21+ items (21 factorial). This is only really relevant because the limit applies per seed, thus probably per session (this is implementation-dependent). That said, it will typically not be noticed by users due to the sheer volume of outcomes across a variety of contexts, as well as the presence of other, concealing factors.
Spoiler: CSPRNG
If a "better" source of randomness is required for whatever reason, e.g. security, consider a CSPRNG (cryptographically-secure pseudorandom) instead. Each result from a CSPRNG is independent of other results, therefore there is effectively no limit on random bits per session. In JavaScript the built-in CSPRNG is crypto.getRandomValues. It can be wrapped up as a more standard "random integer" function, e.g.
CSPRNGs cost more resources: complex applications like games often don't bother going this extra mile for something that players generally won't notice.
Spoiler: perception
There are also a variety of misconceptions that people fall prey to regarding randomness, such as the clustering illusion: the tendency to imagine patterns when no actual patterns are perceived. This has lead to some research into "declustering" algorithms, e.g. for random shuffles in music players (technical paper!):
Spoiler: JS number format
And just to clarify...the Number format is 64-bit IEEE-754, i.e. double-precision floating-point, with a 52-bit mantissa. That's not especially relevant when speaking of limitations in randomness, though, unless you're trying to get a single number to represent a very large number of outcomes (e.g. Lehmer codes for permutations). In that case consider BigInt (or a polyfill since RMMV ships with an old version of NWJS that doesn't support it natively).
There are also a variety of misconceptions that people fall prey to regarding randomness, such as the clustering illusion: the tendency to imagine patterns when no actual patterns are perceived.
This is typically the biggest factor when people complain about biased RNG, and what is probably at play here.

the rest of the chests awarded a "bunk" item which can be obtained in a few other ways from the chest not relevant to the discussion
I think it's relevant - when you're saying your chest has a 50/50 chance to give an armor or a weapon, and then you're trying to evaluate the fairness of those chances, getting 17 bunks is really significant. It means that you only actually got measurable results from 42% of your chests, and 12 is a very small sample size.

I mean, with randomness it is technically possible for that to happen - just the odds are really, really low
That depends on the bit about the bunks - without knowing what has to happen in order for the chest to produce a bunk instead of either a weapon or armor, none of us can agree or disagree.

I just wonder if whatever algorithm RM uses may have a slight bias.
As has already been said (and Arthran demonstrated), your sample size is just way too small to make any kind of judgment or presumption along those lines.


I've had plays where I swear I get way too many evades in combat. But then I stop and make myself think about how many actual attack swings I've witnessed that given game 😉
Thank you @caethyril and @ATT_Turan for your explanation.
Mr. Turan, you'll just have to take my word on the "bunk" items not actually being a factor here. I shouldn't have brought it up in the first place considering I was already using shorthand to describe the situation, meaning I haven't given you an accurate depiction of what is going on. Easier to just use simple terms like "weapons" and "armor" and "items" than having to explain a complicated system.

Original thread: https://forums.rpgmakerweb.com/threads/what-methods-does-rm-use-to-get-randomness.152164/