Added normally distributed generation function to RNG

(cherry picked from commit 5f137925dc)
This commit is contained in:
Chaosus 2019-03-14 13:53:08 +03:00 committed by Hein-Pieter van Braam-Stewart
parent ff3987598e
commit 71753edeae
4 changed files with 23 additions and 0 deletions

View File

@ -40,6 +40,7 @@ void RandomNumberGenerator::_bind_methods() {
ClassDB::bind_method(D_METHOD("randi"), &RandomNumberGenerator::randi);
ClassDB::bind_method(D_METHOD("randf"), &RandomNumberGenerator::randf);
ClassDB::bind_method(D_METHOD("randfn", "mean", "deviation"), &RandomNumberGenerator::randfn, DEFVAL(0.0), DEFVAL(1.0));
ClassDB::bind_method(D_METHOD("randf_range", "from", "to"), &RandomNumberGenerator::randf_range);
ClassDB::bind_method(D_METHOD("randi_range", "from", "to"), &RandomNumberGenerator::randi_range);
ClassDB::bind_method(D_METHOD("randomize"), &RandomNumberGenerator::randomize);

View File

@ -55,6 +55,8 @@ public:
_FORCE_INLINE_ real_t randf_range(real_t from, real_t to) { return randbase.random(from, to); }
_FORCE_INLINE_ real_t randfn(real_t mean = 0.0, real_t deviation = 1.0) { return randbase.randfn(mean, deviation); }
_FORCE_INLINE_ int randi_range(int from, int to) {
unsigned int ret = randbase.rand();
return ret % (to - from + 1) + from;

View File

@ -31,6 +31,8 @@
#ifndef RANDOM_PCG_H
#define RANDOM_PCG_H
#include <math.h>
#include "core/math/math_defs.h"
#include "thirdparty/misc/pcg.h"
@ -61,6 +63,13 @@ public:
_FORCE_INLINE_ double randd() { return (double)rand() / (double)RANDOM_MAX; }
_FORCE_INLINE_ float randf() { return (float)rand() / (float)RANDOM_MAX; }
_FORCE_INLINE_ double randfn(double p_mean, double p_deviation) {
return p_mean + p_deviation * (cos(Math_TAU * randd()) * sqrt(-2.0 * log(randd()))); // Box-Muller transform
}
_FORCE_INLINE_ float randfn(float p_mean, float p_deviation) {
return p_mean + p_deviation * (cos(Math_TAU * randf()) * sqrt(-2.0 * log(randf()))); // Box-Muller transform
}
double random(double p_from, double p_to);
float random(float p_from, float p_to);
real_t random(int p_from, int p_to) { return (real_t)random((real_t)p_from, (real_t)p_to); }

View File

@ -27,6 +27,17 @@
Generates pseudo-random float between [code]from[/code] and [code]to[/code], inclusive.
</description>
</method>
<method name="randfn">
<return type="float">
</return>
<argument index="0" name="mean" type="float" default="0.0">
</argument>
<argument index="1" name="deviation" type="float" default="1.0">
</argument>
<description>
Generates normally(gaussian) distributed pseudo-random number, using Box-Muller transform with the specified [code]mean[/code] and a standard [code]deviation[/code].
</description>
</method>
<method name="randi">
<return type="int">
</return>