0

I want to randomize a value between 0.03- and 0.05. I understand there is infinite values between the two numbers and that rand takes unsigned int data type. I'm wondering how to make a function to randomize double/float data type and set the limits only to two decimals

my code is the following:

double i=0.0;
double minP = 0.03;
double maxP = 0.05;
unsigned seed =time(0);
srand(seed);r
i = rand()% (maxP -minP +0.01) +minP;
Santiagopph48
  • 131
  • 1
  • 2
  • 8
  • 1
    well if you have a value from `0-1`, what happens if you say, multiply it by `maxP-minP` and add `minP`? Or in this case, `0.02` and `0.03` – Rogue Nov 23 '19 at 23:36

1 Answers1

-1

The % operator does not work on doubles. Your best bet for generating a double is going to be generating individual place values and the adding them together. Here is an example:

#include <iostream>
#include <time.h>
using namespace std;
int main() {
    srand(time(0));
    double random;
    random =  (rand() % 3) + .1*(rand() % 10) + .01*(rand() % 10);
    cout.precision(2);
    cout << fixed <<random;
}

This code would generate a random float between 0.00 and 2.99

EDIT: After thinking about this for about two seconds I realized there is a much better way of doing this. If you just generate a integer with digits equal to the amount of significant figures you need and divide that down you will get a random double.

double randDouble(double precision, double lowerBound, double upperBound) {
    double random;
    random = static_cast<double>(((rand()%(static_cast<int>(std::pow(10,precision)*(upperBound - lowerBound) + 1))) + lowerBound*std::pow(10,precision)))/std::pow(10,precision);
    return random;
}