Answer the question
In order to leave comments, you need to log in
Generating a fractional number with a given precision in C++
To implement the search for the extremum of a function by the Monte Carlo method, a generator of random fractional numbers is required, it is desirable that it be possible to set the number of digits after the decimal point. The option from integers to thousandths is quite suitable, but I don’t write in C ++ for so long, the work needs to be done urgently. Can you tell me how to implement it?
UPD: I forgot to clarify, you need to get a fractional number in a given range.
Answer the question
In order to leave comments, you need to log in
The easiest option
#include <stdlib.h>
double GetNormalizedRandomNumber(int digits)
{
double precision = pow(10, digits);
assert(precision < RAND_MAX); // Precision is too high.
double ret = rand() % precision;
ret /= precision;
return ret;
}
It is inconvenient for a computer to work with numbers with different precision. It has hardwired floats and doubles that are fast. Accordingly, all the solutions that you are offered here come down to obtaining a random number with great accuracy and coarsening it to the one you specified. I have a doubt that this coarsening is generally necessary for the Monte Carlo method.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question