I am trying to generate a random decimal number between -90.00 and 90.00, inclusive.
Here is my attempt:
float randomDecimal, result;
int randInt;
void setup() {
Serial.begin(9600);
}
void loop() {
randInt = random(-90,91); // a random integer from -90 to 90
randomDecimal = random(0, 100) / 100.0; // a random decimal number from 0.00 to 0.99
result = randInt + randomDecimal; // a random decimal number from -90.00 to 90.99
Serial.println(result);
delay(300);
}
These are the issues i'm encountering:
The random number generated is from -90.00 to 90.99. I could set it up to 89.99 but i'm not sure how to generate it until the upper limit of 90.00.
What is the seed number used in random()? It should always start with a fixed seed number if i understood correctly?
Notes and Warnings
If it is important for a sequence of values generated by random() to differ, on subsequent executions of a sketch, use randomSeed() to initialize the random number generator with a fairly random input, such as analogRead() on an unconnected pin.
The difficulty with any processor based random number generator is that any processor is strictly deterministic making it difficult to generate a truly random number. Things that will improve the randomness are reading an unconnected analogue pin and using the result as the basis of the seed (even better if the pin has a long wire connected to it to pick up noise from the environment) or including an external event over which the processor has no control (maybe a button press or some data received) as part of the random number generator.
Hi,
Generate a random number from -9000 to +9000, then divide the result by 100.0.
Then store it in a float variable.
long randNumber;
float flrandNumber;
void setup()
{
Serial.begin(9600);
// if analog input pin 0 is unconnected, random analog
// noise will cause the call to randomSeed() to generate
// different seed numbers each time the sketch runs.
// randomSeed() will then shuffle the random function.
randomSeed(analogRead(0));
}
void loop()
{
// print a random number from -90.00 to 90.00
randNumber = random(-9000, 9000);
flrandNumber = (float)randNumber / 100.00;
Serial.println (flrandNumber);
delay(500);
}