daisy::Random.GetFloat generating values 2x the max

hello everyone. first time poster here. i am just learning how to use the Daisy Seed and this is my first time coding anything in C++.

i am trying to generate random numbers with the daisy::Random class, but it seems to be generating numbers in a range that is 2x what I am expecting.

if someone could help me understand what I’m doing wrong with my code, I’d be super duper grateful.

here’s a pared down example of the code:

#include "daisysp.h"
#include "daisy_seed.h"
#include "string.h"
using namespace daisy;
using namespace daisysp;

static DaisySeed hw;
static Random drand;

int main(void)
{
    // initialize seed hardware and Svf daisysp module
    hw.Configure();
    hw.Init();

	// Start the log, and wait for connection
    hw.StartLog(false);

    while(1) {
		hw.PrintLine("rand test: %.3f",drand.GetFloat(0,1));
		System::Delay(100);
	}
}

using this code, i get the following sample output:

rand test: 0.191
rand test: 1.579
rand test: 1.121
rand test: 0.061
rand test: 0.377
rand test: 0.242
rand test: 1.444
rand test: 0.765
rand test: 0.023
rand test: 1.122
rand test: 0.485
rand test: 1.920
rand test: 0.178
rand test: 0.050
rand test: 0.084
rand test: 1.782
rand test: 0.422
rand test: 0.812
rand test: 1.505
rand test: 1.410
rand test: 0.464
rand test: 0.001
rand test: 0.254
rand test: 1.436
rand test: 1.624
rand test: 0.936

I don’t think you’re doing anything wrong.

From DaisyExamples/libDaisy/src/per/rng.h:

float Random::GetFloat(float min, float max)
{
    float norm = (float)GetValue() / 0x7fffffff;
    return min + (norm * (max - min));
}

GetValue() returns an unsigned 32-bit, so the result of the division will be 0.0 to 2.0 (or about that, floats can be weird.)

1 Like

thank you for the explanation. i tested my code by dividing the result by 2 and it appears to get me the values in the range i am looking for.

It’s more efficient to just use drand.GetFloat(0.f, .5f).

1 Like