How to fill an array with random floating point numbers? - c++

I'm hoping to find a way to fill an array with random floating point numbers. My array is size 50 and I'm hoping to fill this array with random float numbers from range 1-25. Here is what I have so far. I greatly appreciate any tips or answers anyone can offer. Thank you.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
float myArray[50];
for(int i = 1; i <= 25; i++)
{
srand(time(0));
myArray[i] = (rand()% 50 + 1);
cout << myArray[i] << endl;
system("Pause");
return 0;
}
}

If C++11 is an option I would use the random header and uniform_real_distribution:
#include <iostream>
#include <random>
int main()
{
std::random_device rd;
std::mt19937 e2(rd());
std::uniform_real_distribution<> dist(0, 25);
for (int n = 0; n < 50; ++n) {
std::cout << dist(e2) << ",";
}
std::cout << std::endl ;
}
Why do people say there is modulo bias when using a random number generator? explains why the naive use of modulus with rand() causes bias in the distribution and how to avoid it.

If C++11 is not an option, you can just use rand, dividing its result by the RAND_MAX constant casted to float to obtain a uniform distribution of floats in the range [0, 1]; then you can multiply it by 24 and add 1 to get your desired range:
myArray[i] = rand()/float(RAND_MAX)*24.f+1.f;
By the way, as other observed, move srand out of your loop - the RNG seed (normally) must be initialized only once.
(notice that dividing by RAND_MAX will give a distribution that includes the right extreme of your interval; if you want to exclude it, you should divide by e.g. RAND_MAX+1)
Of course, the resulting distribution is only as good as the original rand() distribution (both in randomness and in granularity); you will typically get a LCG and granularity of at least ~0.0007 (guaranteed by the standard, and what VC++ and other compilers actually provide). If you need better random numbers, you should follow the advices posted in the other answers (the default Mersenne twister generator in C++11 provides better randomness and a way bigger guaranteed range).

#include <random>
...
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<float> dist(1.0f, 25.0f);
std::cout << dist(gen);

Each time the for loop iterates, it assigns one value in the array a random number. Since your array is of size 50, you want to iterate 50 times instead of 25 like you do now.
for(int i = 0; i < 50; i++)
Array bounds start at 0, so you can only access from array[0] to array[49].
To get a random number from 1-25, you want
myArray[i] = rand() % 25 + 1;
Also, do you want integers or floating point random numbers? Right now you are just getting integers, meaing 1, 2, 3, ... 25. If you want something like 2.45, 6.883, 23.999, etc. you need to do something different. See C++ random float number generation for the answer.
You probably don't want to pause every time you insert a number into the array. Move this after the for loop.
system("pause");
Also, if you return 0 inside the for loop, you will only assign one number before your program will exit. Move that to after the loop as well.

Use uniform_real. In the following program random float numbers between 1.0 and 2.0 are generated:
#include <random>
#include <iostream>
typedef std::ranlux64_base_01 Myeng;
typedef std::uniform_real<float> Myceng;
int main()
{
Myeng eng;
Myceng ceng(1.0, 2.0);
Myceng::input_type engval = eng();
std::cout << "a random value == " << ceng(eng) << std::endl;
std::cout << "a random value == " << ceng(eng) << std::endl;
std::cout << "a random value == " << ceng(eng) << std::endl;
return (0);
}

Related

Inquire about using a random integer as the size of a vector

so I have trouble remembering how to call upon random numbers in C++. I'm not sure how to, so if someone could remind me that would be fantastic. I'm trying to make a vector with a random size filled with random integers. Here is my following code:
#include <cstdlib>
#include <iostream>
#include <vector>
int main()
{
int randSize = rand();
int sum = 0;
int product = 1;
std::vector<int> numbers(randSize);
int output;
for (int i = 0; i < numbers.size(); i++)
{
int randNum = rand();
numbers[i] = randNum;
output = numbers[i]&2;
if (output == 0)
{
sum += numbers[i];
}
else
{
product = product * numbers[i];
}
}
std::cout << "The sum of even numbers is " << sum << "\n";
std::cout << "The product of off numbers is " << product << "\n";
}
As already pointed out in the comments, best forget about rand() and use the facilities provided by the standard library in <random> instead. For example:
std::vector<int> makeRandomBunch(int min, int max, std::size_t min_elements, std::size_t max_elements)
{
std::mt19937 generator(42);
std::uniform_int_distribution<std::size_t> size_distribution(min_elements, max_elements);
std::size_t num_elements = size_distribution(generator);
std::vector<int> data;
data.reserve(num_elements);
std::uniform_int_distribution<int> element_distribution(min, max);
std::generate_n(std::back_inserter(data), num_elements, [&](){ return element_distribution(generator); });
return data;
}
Here, we're using an mt19937 pseudorandom number generator (don't get spooked by the name, it's just named after the algorithm it uses) seeded with the value 42 as our source of randomness. An std::uniform_int_distribution can be used to shape the randomness provided by a random generator into random integers sampled from a given range. We use a uniform_int_distribution to randomly pick a size between elements_min and elements_max for our vector and reserve that amount of space in our vector. We use another uniform_int_distribution which we'll pick our int elements from (ranging between min and max). Finally, we use std::generate_n in combination with a back_inserter to fill our vector with elements and return the vector…
live example here

Generate random letters

string bolsa_letras::letters_generator(int quantity){
int already_generated = 0;
map<char, int> aux = values;
string out;
while(already_generated != quantity){
char generated_char = 'A' + rand()%26;
if(aux[generated_char] > 0){
out.push_back(generated_char);
aux[generated_char]--;
already_generated++;
}
}
return out;
}
Above is the code that given a number generates random letters.
The map saves the letters and the times that letters can be appeared. The problem is that every time i run the code, it prints the same: NLRBBMQH. Why is so?
I have include cstdlib for the rand function.
A deterministic program cannot naturally generate randomness. We need to get that randomness from elsewhere. In the old days of rand(), we'd generally seed the RNG with the result of std::time(NULL) to produce a different state at each run.
Nowadays, we use the tools provided by <random> which are "more random".
From cppreference.com's documentation on std::uniform_int_distribution you can find an example for integers of type int. Now, char is an integer type too. Let us tweak their example a tiny bit:
#include <random>
#include <iostream>
int main()
{
std::random_device rd; // Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<char> dis('A', 'Z');
for (int n=0; n<10; ++n) {
std::cout << dis(gen) << ' ';
}
std::cout << '\n';
}
And tadaaaa! a random letter generator :)
Live demo

Is it possible to select random numbers from a defined set of numbers

Random function usually generates random numbers within a given range. But is it possible to randomly select from a pre-defined list? For example i have [1,4,5,6] and i want to randomly select from this list only. If so, how?
Thanks :)
P.s:: C++ code would help me a big deal ^^
The following code would help, instead of choose a random integer, we can choose a random index in the set;
int numbers[4] = {1,4,5,6};
srand (time(NULL));
int index = rand() % 4;
int number = numbers[index];
Here is a C++11 version utilizing <random> instead:
#include <random>
int numbers[4] = {1,4,5,6};
std::default_random_engine generator;
std::uniform_int_distribution<int> distribution(0,3);
int index = distribution(generator); // generates number in the range 0..3
int number = numbers[index];
Good way to do that might be using shuffle. Basically, you shuffle array and then start to pick numbers one by one
#include <iostream> // std::cout
#include <algorithm> // std::shuffle
#include <array> // std::array
#include <random> // std::default_random_engine
int main () {
std::array<int, 4> foo {1,4,5,6};
std::shuffle(foo.begin(), foo.end(), std::default_random_engine(12345));
std::cout << "shuffled elements:";
for (int x: foo)
std::cout << ' ' << x;
std::cout << '\n';
return 0;
}

code for generated numbers and how to show highest number to low

Need a program that generates 10 numbers from 1 to 6. code must be stored in an integer array and find out the highest, minimum value of the numbers generated and displayed in the code, also the overall summ of all the numbers generated from 1-6. All three functions must be returned in main..
ok! im awake now i can see that i can edite my original post so here goes my almost finished code.
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
int highest = INT_MAX;
int lowest = INT_MIN;
int i = 0;
int sum = 0;
{
{
srand(time(0));
for (int i = 0; i < 10; i++)
cout << rand() % 6 + 1 << endl;
}
int myArray[10]{ 1,2,3,4,5,6 };
for (int i = 0; i < 10; i++)
myArray[i] = rand() % 6 + 1;
if (myArray[i] < lowest)
lowest = myArray[i];
if (myArray[i] > highest)
highest = myArray[i];
{
for (int i = 0; i < 10; i++)
sum = sum + rand() % 6 + 1;
cout << "The sum of all 10 numbers is " << sum << endl;
cout << "The largest value is = " << INT_MAX << endl;
cout << "The smallest value is = " << INT_MIN << endl;
}
return 1;
}
}
My problem here is that i cant define the int_max or int_min to display my highest numbers from 1-6 . i have tried other examples with int_m but it doesntn work. im hoping some u can give me a hint what im doing worng. Thank you
First of all, be careful with the indentation of your code.
Next, you need to keep track of every generated number by declaring an array.
srand(time(0));
//You have to include the limits library to use INT_MIN and INT_MAX
int highest = INT_MIN;
int lowest = INT_MAX;
int myArray[10]; //Array to hold 10 random numbers
for (int i = 0; i < 10; i ++)
{
myArr[i] = rand() % 6 + 1; // Generates a random number and stores it
if (myArr[i] < lowest)
lowest = myArr[i];
else if (myArr[i] > highest)
highest = myArr[i];
}
Now highest variable should hold the higest number generated and lowest variable should hold the lowest generated number.
And please next time please do more research before asking and be more specific.
I would avoid trying to use rand() or srand() there is a safer, more efficient and reliable way to generate random numbers. I will be showing you how to use one of many random number generators that are defined in the standard library. I will be using a random device to seed the engine or generator and the generator I will be using is the standard mersenne_twister_engine shown as mt19937. I will be using a uniform_int_distribution for the distribution type. There are many other types of generators that can be used, other types of distributions and a few other ways to seed these engines; another way to seed these besides a random_device is by using std::chrono time or steady clock system. You can find out more about these pseudo random number generators and distributions found here: cppreference.com to use these you will need to include the header file <random>.
I will be using a std::vector to contain the numbers generated and for this you will need to include <vector> although if you are required to use a basic default array you can easily replace the vector with an array of ints. I choose to use the std::vector<int> because of the already existing algorithms in the standard library that are available to you to perform the needed or required operations that you are asking for such as finding the minimum and maximum values and by adding all of the elements in that sequence or range of values. To use these algorithms you will need to include <algorithm> and <numeric>.
Here is the short program that I wrote strictly in the main function to show all the functionality that you are asking for. If you need to have these in separate functions that are called within the main then I leave that as a task for you to accomplish.
#include <iostream> // Output
#include <vector> // Container
#include <algorithm> // Algorithms
#include <numeric> // Other Needed Functions
int main() {
std::random_device rd; // Will be used to obtain a seed for the random number engine
std::mt19937 gen( rd() ); // Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> dis( 1, 6 ); // Distribution Of Random Numbers in range of [1,6]
// Vector Or Array To Store Numbers
std::vector<int> numbers;
// Populate Vector
int n = 0;
for ( ; n < 10; ++n){
numbers.push_back( dis( gen ) );
}
// Display Random Values
n = 0;
for ( ; n < 10; ++n ) {
std::cout << numbers[n] << ", ";
}
std::cout << std::endl;
// Min & Max
std::vector<int>::iterator resultMin;
std::vector<int>::iterator resultMax;
resultMin = std::min_element(std::begin(numbers), std::end(numbers));
resultMax = std::max_element(std::begin(numbers), std::end(numbers));
// Sum
int sum = std::accumulate(numbers.begin(), numbers.end(), 0);
// Display Results
std::cout << "min value is: " << (*resultMin) << std::endl;
std::cout << "max value is: " << (*resultMax) << std::endl;
std::cout << "Sum of array is: " << sum << std::endl;
return 0;
}

Math.Random equivalent in C++

I have been programming in Java for three years, and have been using Math.random() to get a random number. I'm fairly new to C++, and I was wondering if there was equivalent to that but in C++? A specific function or method that I could use? Also include an explanation. Thanks so much!
C++ provides a fairly nice random number library, <random>, but it doesn't yet have the sort of dead simple API beginners generally want. It's easy to produce such an API, as I show below, and hopefully some such API will be included at some point.
The C++ API splits random number generation into two parts, sources of 'randomness', and machinery for turning randomness into numbers with specific distributions. Many basic uses of random numbers don't particularly care how good (or fast, or small) the source of 'randomness' is, and they only need 'uniform' distributions. So the typically recommended source of randomness is the "Mersenne Twister" engine. You create one of these and seed it like so:
#include <random>
int main() {
std::mt19937 eng{42};
}
Now eng is an object that can be passed around and used as a source for random bits. It's a value-type so you can make copies of it, assign to it, etc. like a normal value. In terms of thread safety, accessing this value is like accessing any other, so if you need multiple threads you should either put an engine on each thread or use mutual exclusion.
To turn data from an engine into random values, use a distribution object. Typical uses need 'uniform' distributions, so for integral values use std::uniform_int_distribution<int>.
std::uniform_int_distribution<int> dice{1, 6};
A distribution object is a function object, and you get values from it by calling it and passing it the source of randomness it will use:
auto die_roll = dice(eng);
One thing to keep in mind is that the math for producing random values should be encapsulated inside a distribution object. If you find yourself doing some kind of transformation on the results then you probably should be using a different distribution. Don't do things like dist(eng) % 10 or dist(eng) / 6.0 + 10.0. There are several other distributions provided in the library, including ones for producing floating point values with various distributions.
Here's a pretty easy way to wrap the <random> functionality for simple usage:
#include <iostream>
#include <random>
std::mt19937 seeded_eng() {
std::random_device r;
std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
return std::mt19937(seed);
}
class Random {
std::mt19937 eng = seeded_eng();
public:
auto operator()(int a, int b) {
std::uniform_int_distribution<int> dist(a, b);
return dist(eng);
}
};
int main() {
Random random;
for (int i = 0; i < 10; ++i) {
std::cout << "Dice: " << random(1, 6) << " " << random(1, 6) << '\n';
}
}
#include <iostream>
#include <ctime>
int main()
{
srand((unsigned int) time (NULL)); //activates the generator
//...
int a = rand()%10; //gives a random from 0 to 9
double r = ((double) rand() / (RAND_MAX)); //gives a random from 0 to 1
int max, min;
//...
int c = (rand()%(max - min)) + min; //gives a random from min to max
//...
return 0;
}
These ways are the simpliest.
Sometimes it means "the best", sometimes - not.
1.srand((unsigned) time(0)) will make sure that everytime you run your program that the rand() function will get a new seed causing it to produce a different or "random" output. Without stand((unsigned) time(0)), the rand() will produce the same output.
2.int Number, is used to store the random number that is being generated by the rand() function. The rand() % 27 will give you numbers 0-26.
#include <iostream>
#include <ctime>
int main()
{
srand((unsigned)time(0))
int Number = ((rand() % 27));
cout << Number << endl;
return 0;
}
Here is a simple solution. The function random is overloaded. One instance is used to acquire a random number generator for integers. Another instance is used to acquire a random number generator for doubles. After you have these two functions, applications becomes rather trivial as can be observed in the main function.
#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <numeric>
#include <ostream>
#include <random>
// Single global engine, a better version of std::rand
std::mt19937 engine{ std::random_device()() };
// Returns a generator producing uniform random integers in the closed range [a, b]
std::function<int()> random(int a, int b)
{
auto dist = std::uniform_int_distribution<>(a, b);
return std::bind(dist, std::ref(engine));
}
// Returns a generator producing uniform random doubles in the half-open range [x, y)
std::function<double()> random(double x, double y)
{
auto dist = std::uniform_real_distribution<>(x, y);
return std::bind(dist, std::ref(engine));
}
int main()
{
const auto no_iterations = int{ 12 };
auto dice = random(1, 6);
// Roll the dice a few times and observe the outcome
std::generate_n(std::ostream_iterator<int>(std::cout, " "),
no_iterations, dice);
std::cout << std::endl;
// U is a uniform random variable on the unit interval [0, 1]
auto U = random(0.0, 1.0);
// Generate some observations
std::vector<double> observations;
std::generate_n(std::back_inserter(observations), no_iterations, U);
// Calculate the mean of the observations
auto sum = std::accumulate(observations.cbegin(), observations.cend(), 0.0);
auto mean = sum / no_iterations;
std::cout << "The mean is " << mean << std::endl;
return 0;
}