-3

what is the c++ Version of this python code? I want to have a special random number according to a Special number in a loop. python Version:

import random 
nextRTSeed = 0;
while(True):
    nextRTSeed+=1
    random.seed(nextRTSeed)
    print( "rand ------->>   ", (random.random()) )
    if(nextRTSeed>10):
        break
  1. rand ------->> 0.13436424411240122
  2. rand ------->> 0.9560342718892494
  3. rand ------->> 0.23796462709189137
  4. rand ------->> 0.23604808973743452
  5. ...
  • Is there a specification of what algorithm the python random number generator uses? If not, there is no solution to your question. – Peter Dec 28 '21 at 01:44
  • @Peter Afaik, Python uses the Mersenne Twister internally. I'm not sure with which constants it uses it though. – Ted Lyngmo Dec 28 '21 at 02:11
  • @mahmoodhasanzadeh When you asked this question, did you have a "correct" answer in mind? – Ted Lyngmo Dec 30 '21 at 02:30

2 Answers2

1

A direct translation would probably look like this:

#include <iomanip>
#include <iostream>
#include <random>

int main() {
    std::cout << std::fixed << std::setprecision(17);  // we want many decimals   
 
    std::mt19937 random;                                     // A PRNG
    std::uniform_real_distribution<double> dist(0., 1.);     // distribution [0,1)

    for(int nextRTSeed = 1; nextRTSeed <= 11; ++nextRTSeed) {
        random.seed(nextRTSeed);                             // reseeding the PRNG
        std::cout << dist(random) << '\n';                   // print random number
    }
}

Note: Reseeding your PRNG (pseudo random number generator) is rarely needed. You should usually only seed it once and then just keep calling it. Like this:

int main() {
    std::cout << std::fixed << std::setprecision(17);    
    
    std::mt19937 prng(std::random_device{}());           // A seeded PRNG    
    std::uniform_real_distribution<double> dist(0., 1.);

    for(int i = 0; i < 11; ++i) {
        std::cout << dist(prng) << '\n';
    }
}

Demo

Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
-1

Here is how you will get a random number in C++

#include <iostream> // For input/output
#include <cstdlib> // for rand() and srand()

int main()
{
    int maxRandValue = 100
    srand(time(null)); // Sets seed of random to time now.
    std::cout << "The random number is: "<< rand() % maxRandValue; // Range: 0 - 100
}

NOTE the rand() function in Python/C++ is not random but pseudo-random for more see this video: https://youtu.be/Nm8NF9i9vsQ

Bye!