 # does random() not generate decimals?

hello, been trying to get a fairly simple RNG up and running.

Currently I need to generate 2 random numbers. The 1st should ideally be an int between 1 and 7, inclusive. The 2nd should be a float (with random decimals!) between 0.01 and 4.00 (ex. 2.76, 3.01, 0.44, etc), also inclusive.

I'm not sure what the problem is, but I cannot get random() to generate decimals for the 2nd value. in the serial monitor, the float is always y.00.

``````float x;
float y;
int z;

void setup() {
Serial.begin(9600);
}

void loop() {
x = random(1, 8);
y = random(0.01, 5);
z = (int)x;

Serial.println(z);
Serial.println(y);
}
``````

So my question is: How do I get random() (or some function) to generate random decimals??

any help would be greatly appreciated!

Create the decimal by generating a random number between 0-99
Divide by 100.
Add it to a random integer number.

Why not just divide the random number by something? That will generate the integer and fraction in one step.

``````   y = random(1, 500) / 100.0
``````

Just in case you wanted the decimal part to do something else with it. I did not think about your method ;)

``````  y = random(1, 401) / 100.0
``````

;)

How many decimals do you need?
Or better, how many different values between 0.01 and 4.00 do you want?
100? 1000? 1 million? more?

The code below will give for datatype float all or almost all possible values,
and for datatype double it will give some 2billion++ different values.

``````//
//    FILE: randomDouble.ino
//  AUTHOR: Rob Tillaart
// VERSION: 0.1.00
// PURPOSE: demo
//    DATE: 2016-01-13
//     URL: http://forum.arduino.cc/index.php?topic=371564.0
//
// Released to the public domain
//

void setup()
{
Serial.begin(115200);
Serial.print("Start ");
Serial.println(__FILE__);
}

double randomDouble(double minf, double maxf)
{
return minf + random(1UL << 31) * (maxf - minf) / (1UL << 31);  // use 1ULL<<63 for max double values)
}

void loop()
{
Serial.println(randomDouble(0.01, 4.00), 8);
}
``````

have fun!