How to Generate n digit random numbers? [duplicate] - c++

This question already has answers here:
Getting big random numbers in C/C++
(6 answers)
Closed 6 years ago.
I'm trying to generate n digit random numbers. I can generate a random number, but here the case is to generate a n digit number.
I tried doing it by storing the random numbers in an array but I need it in a long long format and not an array.

There are two things you need to do:
Work out how to output random numbers within a given range
Work out what range you need in order to get only 10-digit numbers
Part (1) is actually a bit tricky, if you want to ensure every number in your range is equally likely to occur. Fortunately, the standard library in C++11 onwards comes with a facility called uniform_int_distribution which does the required calculations for you:
// Create and seed the random number generator
auto gen = std::mt19937{std::random_device{}()};
// Create our desired distribution
auto dist = std::uniform_int_distribution<int_type>{lower, upper};
// Get numbers
std::cout << dist(gen) << "\n";
For part (2), we need to work out what lower and upper should be above. That's actually pretty easy: the lowest 10-digit number is 1,000,000,000 (one billion), and the highest is 9,999,999,999 (one less than 10 billion). We can put these numbers straight in to C++
constexpr auto lower = 1'000'000'000;
constexpr auto upper = 9'999'999'999;
(Note you'll need a C++14 compiler to use ' as a digit separator).
Now, there's one last problem: on a typical system, lower and upper above will be different types, because lower will fit into an int but upper will not. So we need to make sure that our output uses the larger of the two types. A good way to do this is to use a type alias and decltype:
using int_type = decltype(upper);
This says we are declaring a new type name int_type which is an alias for the type of upper.
Put these together and you'll have a routine that will output 10 digit numbers on any system that uses C++11.

Related

What are the ways to implement the function which counts the number of same significant digits between two doubles?

I'm following along a series of youtube lectures on modern C++ by Igor Bogoslavskyi. In CPP-06 he's shown how floating point numbers are represented internally i.e. sign bit, magnitude and mantissa. In the homework he asks to implement the following:
int CountSameSignificantDigits(double a, double b);
This function should count how many significant digits are there between the two numbers. Only count
the number of significat digits up to 100, so that the function returns 100 if the numbers are equal.
It does not make sense to me how he wants the count of up to 100 significant digits. What if the two same doubles have less than 100 significant digits? My current idea is to simply convert these values to strings and iterate over them, but I'm not confident this is a good solution, and even then I'm not sure how to deal with aformentioned ambiguity. Any thoughts?
You can use to_string() function from the <string> header to convert given number and after that, you can access the individual digits using indexing for comparision like:
string a="hello"
Then a[0] is 'h'.

Method to find number of digits after converting from a different base number

The text in quotes gives a bit of background on my program in case it's needed to understand my issue, you might be able to fully understand with the stuff at the end unquoted if you don't feel like reading it.
I'm working on the common project of sorting in C++, and I am
currently doing radix sort. I have it as a function, taking in a
vector of strings, an integer holding the max number of digits, and an
integer with the radix/base of the numbers: (numbers, maxDigits, radix)
Since the program takes in numbers of different base and as a string,
I'm using stoi to convert them to a base 10 integer to make the
process easier to generalize. Here's a quick summary of the algorithm:
create 10 queues to hold values 0 to 9
iterate through each digit (maxDigit times)
iterate through each number in the vector (here it converts to a base 10)
put them into the queue based on the current digit it's looking at
pull the numbers out of the queues from beginning to end back into the vector
As for the problem I'm trying to wrap my head around, I want to change the maxDigit value (with whatever radix the user inputs) to a maxDigit value after it is converted to base 10. In other words, say the user used the code
radixSort(myVector, 8, 2)
to sort a vector of numbers with the max number of digits 8 and a radix of 2. Since I convert the radix of the number to 10, I'm trying to find an algorithm to also change the maxDigits, if that makes sense.
I've tried thinking about this so much, trying to figure out a simple way through trial and error. If I could get some tips or help in the right direction that would be a great help.
If something is in radix 2 and max digits 8, then its largest value is all ones. And 11111111 = 255, which is (2^8 - 1).
The maximum digits in base 10 will be whatever is needed to represent that largest value. Here we see that to be 3. Which is the base 10 logarithm of 255 (2.40654018043), rounded up to 3.
So basically just round up log10 (radix^maxdigits - 1) to the nearest whole number.

Random number bigger than 100,000

I'm writing in C/C++ and I want to create a lot of random numbers which are bigger than 100,000. How I would do that? With rand();
You wouldn't do that with rand, but with a proper random number generator which comes with newer C++, see e.g. cppreference.com.
const int min = 100000;
const int max = 1000000;
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(min,max);
int random_int = distribution(generator); // generate random int flat in [min, max]
Don't forget to properly seed your generator.
Above I imply that rand is not a "proper" pseudo-RNG since it typically comes with a number of shortcomings. In the best case, it lacks abstraction so picking from a different distribution becomes hard and error-prone (search the web for e.g. "random range modulus"). Also replacing the underlying engine used to generate the random numbers is AFAIK impossible by design. In less optimal cases rand as a pseudo-RNG doesn't provide long enough sequence lengths for many/most use cases. With TR1/C++11 generating high-quality random numbers is easy enough to always use the proper solution, so that one doesn't need to first worry about the quality of the used pseudo-RNG when obscure bugs show up. Microsoft's STL gave a presentation giving a nice summary talk on the topic at GoingNative2013.
// Initialize rand()'s sequence. A typical seed value is the return value of time()
srand(someSeedValue);
//...
long range = 150000; // 100000 + range is the maximum value you allow
long number = 100000 + (rand() * range) / RAND_MAX;
You may need to use something larger than a long int for range and number if (100000 + range) will exceed its max value.
In general you can use a random number generator that goes between 0 and 1, and get any range you want by doing the following transformation:
x' = r x + b
So if you want random numbers between, say, 100,000 and 300,000, and x is your random number between 0 and 1, then you'd set r to be 200,000 and b to be 100,000 and x' will be within the range you want.
If you don't have access to the C++ builtins yet, Boost has a bunch of real randomizers in Boost.Random, including specific solutions for your apparent problem space.
I'd echo the comments that clarifying edits in your question would improve the accuracy of answers eg. "I need uniformly-distributed integers from 100,001 through 1,000,000".

Just how random is std::random_shuffle?

I'd like to generate a random number of reasonably arbitrary length in C++. By "reasonably arbitary" I mean limited by speed and memory of the host computer.
Let's assume:
I want to sample a decimal number (base 10) of length ceil(log10(MY_CUSTOM_RAND_MAX)) from 0 to 10^(ceil(log10(MY_CUSTOM_RAND_MAX))+1)-1
I have a vector<char>
The length of vector<char> is ceil(log10(MY_CUSTOM_RAND_MAX))
Each char is really an integer, a random number between 0 and 9, picked with rand() or similar methods
If I use std::random_shuffle to shuffle the vector, I could iterate through each element from the end, multiplying by incremented powers of ten to convert it to unsigned long long or whatever that gets mapped to my final range.
I don't know if there are problems with std::random_shuffle in terms of how random it is or isn't, particularly when also picking a sequence of rand() results to populate the vector<char>.
How sketchy is std::random_shuffle for generating a random number of arbitrary length in this manner, in a quantifiable sense?
(I realize that there is a library in Boost for making random int numbers. It's not clear what the range limitations are, but it looks like MAX_INT. That said, I realize that said library exists. This is more of a general question about this part of the STL in the generation of an arbitrarily large random number. Thanks in advance for focusing your answers on this part.)
I'm slightly unclear as to the focus of this question, but I'll try to answer it from a few different angles:
The quality of the standard library rand() function is typically poor. However, it is very easy to find replacement random number generators which are of a higher quality (you mentioned Boost.Random yourself, so clearly you're aware of other RNGs). It is also possible to boost (no pun intended) the quality of rand() output by combining the results of multiple calls, as long as you're careful about it: http://www.azillionmonkeys.com/qed/random.html
If you don't want the decimal representation in the end, there's little to no point in generating it and then converting to binary. You can just as easily stick multiple 32-bit random numbers (from rand() or elsewhere) together to make an arbitrary bit-width random number.
If you're generating the individual digits (binary or decimal) randomly, there is little to no point in shuffling them afterwards.

random complex number

i need algorithm for generate random complex number please help i know how generate random number but random complex number confuse me
I would simply generate two random numbers and use one for the real part and one for the imaginary part.
Generate 2 random numbers (x, y) (use the built-in rand/rnd/random class from your environment's libraries), where x is the real part and y is the imaginary part.
Create a complex number class (with a constructor that takes a real and imaginary parameter)
Use the 2 random numbers from step 1 to create a complex number, x + i y
1.Generate 2 vector of numbers say one is real_vector and another is imaginary_vector of size say MAX_SIZE to be generated randomly with differrent seeds.
2.Random shuffle the numbers in vectors(real_vector+imaginary_vector) using any distribution let us say use of std::random_shuffle(uniform distribution).
3.randomly generate a index and apply modulo operator for MAX_SIZE and select index from first array that will provide an real part of ur random number.
4.use step 3 to get imaginary part of your random number.
5.Create a complex number using number got from step 3 and step 4 and store in a container.
6.go to step 3 and check if you want any more complex number;if no then break;