C++ Random Number Generator AKA STOP USING Rand()

Поділитися
Вставка
  • Опубліковано 29 вер 2024
  • The C++ random library is one of the most robust and effective ways of generating random numbers in C++. In this video I'll show you how to generate random numbers using both the old C style interface using rand() and also the Modern C++ style using random engines and distributions
    Give me money:
    / @thebuilder
    Below are affiliate links, I may earn something if you purchase the mentioned product or service linked.
    📚 Recommended Books
    Fluent Python: amzn.to/3Za7PEN
    Tour of C++: amzn.to/3FY0pxW
    💵 Get $100 in credits from Vultr with this link
    www.vultr.com/...

КОМЕНТАРІ • 117

  • @RedStoneMatt
    @RedStoneMatt Рік тому +252

    Bro, you can't go out of your way and tell people to stop using some function that everyone uses if you're using light mode

    • @codigodesenior3995
      @codigodesenior3995 Рік тому +2

      ye lol

    • @jasmintea8825
      @jasmintea8825 Рік тому

      W

    • @appleturdpie
      @appleturdpie Рік тому +15

      Yes he can. Enjoy being an individual with weak beta eyes. While us Chads program using light theme with our eyes capable of handling the intensity.

    • @boar6615
      @boar6615 Рік тому

      grow up

    • @happygofishing
      @happygofishing Рік тому +3

      dark mode is for discord losers that never go outside, thus weak eyes.
      light mode is for codeblocks chads that love nature.

  • @raianmr2843
    @raianmr2843 Рік тому +23

    Back when I used to do C++ for uni projects, I had implemented two very simple texture generation algorithms for an OpenGL game we were making (I only worked on the algorithm side of things). Working with the random library was a delight. It's one of the very few things in C++ that don't have any major hidden pitfalls (for my personal usecases). Coding in C++ feels really empowering when the batteries-included-ness of the stdlib kicks in. I'm trying to migrate to Rust these days and it feels kinda bittersweet to leave C++ behind.

  • @aenapoeka
    @aenapoeka 2 роки тому +6

    Straight to the point and zero useless bullshit, nice.

  • @its4theer
    @its4theer 3 місяці тому +1

    this makes alot of assumtion about the viewer knowledge.

    • @TheBuilder
      @TheBuilder  3 місяці тому

      like what?

    • @its4theer
      @its4theer 3 місяці тому +1

      ​@@TheBuilder
      nullptr
      uniform distribution
      vector
      iota.
      PS i like to understand everything in my code and its hard when youre a bigginer to know what "nullptr" means

    • @TheBuilder
      @TheBuilder  3 місяці тому

      @@its4theer make a list of things you're having trouble with and try to understand them slowly over time

    • @its4theer
      @its4theer 3 місяці тому

      @@TheBuilder I will thanks ❤️

  • @alejandronieto576
    @alejandronieto576 Рік тому

    Thanks for the video.
    I am also getting the same number everytime, even using the exact same code shown in 3:25. The srand is deleted by this point, by which I understand that there is no need to update/change the seed. Thanks for your answer.

    • @TheBuilder
      @TheBuilder  Рік тому

      just use the C++ random device

    • @alejandronieto576
      @alejandronieto576 Рік тому

      @@TheBuilder That's what I am using. The exact same code at 3:25.

    • @TheBuilder
      @TheBuilder  Рік тому

      @@alejandronieto576 post code

  • @Vili69420
    @Vili69420 Рік тому +2

    btw why not use an array instead of a vector, jw since u are already declaring the size of the vector

    • @TheBuilder
      @TheBuilder  Рік тому +1

      Just personal preference. I use std::vector so much I forget std::array is a thing

    • @Vili69420
      @Vili69420 Рік тому

      @@TheBuilder oh lol :v

  • @kenoldavid
    @kenoldavid 2 роки тому +1

    I wish I could give this a double like 👍

  • @islam_095._
    @islam_095._ Рік тому

    Is there an algorithm that predicts the next odds of the aviator game?

  • @stephenhowe4107
    @stephenhowe4107 Рік тому

    How does the code compile at 1:27 without #include ? That header is necessary to use rand()

    • @TheBuilder
      @TheBuilder  Рік тому +1

      probably included by iostream. libraries can include other libraries

    • @Kamion008-xu6ie
      @Kamion008-xu6ie 4 місяці тому

      already included by the compiler

    • @stephenhowe4107
      @stephenhowe4107 4 місяці тому

      Yes libraries can include other libraries but we should not assume that.
      One of
      #include
      #include
      is right.

  • @djthdinsessions
    @djthdinsessions Рік тому +1

    The real issue is using time() as the random seed

    • @coe9900
      @coe9900 Рік тому

      So what to use?

    • @djthdinsessions
      @djthdinsessions Рік тому

      @@coe9900 for linux/unix systems, just read from /dev/urandom or /dev/random. For Windows, use CryptGenRandom. Just don't use time() for random seed as it's predictable

  • @ismailgharbiyeh7743
    @ismailgharbiyeh7743 7 місяців тому

    if (7+null) = true then
    end if
    }
    set "notebook" = net (true)

  • @SamoshiBG
    @SamoshiBG Рік тому +77

    How many libraries do you need to make a random number generator?
    C++: YES!

    • @davidjohnston4240
      @davidjohnston4240 Рік тому

      Personally I want as little code in between my hardware source of random numbers and my running application. That's why we made the random number instructions in Intel CPUs, rather than devices needing a device driver.

    • @cpK054L
      @cpK054L Рік тому +1

      @@davidjohnston4240 just pull a random number from the temp sensor and compare to the Johnson noise 🤣
      Sorry...still mad that my wife made me bust my sandy bridge cpu...

  • @peligros13
    @peligros13 Рік тому +59

    I think this generator is absolutely not recommended to use normally. Random device is a "real" random number generator, which means that does not follow a certain algorithm, but rather takes some variables from the system that are actually random and gives a number back. However, it can be terribly slow (the term people use is "running out of entropy", which causes the system to wait for some time until more is somehow created) and I do not think the quality of the numbers is guaranteed.
    Instead use it only for the seed of an actual pseudo random number generator, like std::mt19937, which is incredibly fast and the numbers are good for a ridiculous amount of time. An example would be:
    std::random_device rd;
    std::mt19937 generator(rd());
    std::uniform_real_distribution dist(0.0, 1.0);
    std::cout

    • @TheBuilder
      @TheBuilder  Рік тому +9

      Good tip

    • @davidjohnston4240
      @davidjohnston4240 Рік тому +2

      ​@@TheBuilder mt19937 is not cryptographically secure. Do not use it for any secure purpose like generating keys or DH or RSA. mt19937 is also not very good compared to state of the art non cryptographic, uniform generators like PGCs.

    • @StefanoTrevisani
      @StefanoTrevisani Рік тому +1

      @@davidjohnston4240 on an x86 CPU AES is pretty darn fast, have not tested how it compares to the mersenne twister, but you can use that as a secure PRNG

    • @davidjohnston4240
      @davidjohnston4240 Рік тому

      @@StefanoTrevisani You can use the AES instructions in an RNG construction, like CTR-DRBG and it will usually be faster in a single thread than RdRand and always faster than RdSeed. With multiple threads, the AES instructions are always faster, because the is one lump of AES hardware for each core so it scales linearly while there is only one entropy source serving all the cores. However the AES instructions do not bring any entropy to the party. You need hardware specifically designed to do that and RdSeed is the instruction for that. There are libraries (E.G. in nginx) that seed from RdSeed and run parallel SW PRNGs using the AES instructions to get the fastest possible random number supply for SSL per-packet nonces.

    • @StefanoTrevisani
      @StefanoTrevisani Рік тому

      @@davidjohnston4240 oh right the rdrand instruction. I don't know why but I bursted down laughing when I first found out about it. I was like "mmm x86 has a lot of cool instructions, like AVX permutations and so on, let's see if there's something for RNG" and of course there was 😂 I was like "wow assembly nowadays is the highest lever language, it has routines for RNG, for AES, for SHA, basically everything you would need an external library or to implement yourself is already available in there 😂"

  • @cno9984
    @cno9984 Рік тому +16

    Looking at the output of your program, I can confirm that 1:41 was filmed exactly on Thursday, September 1st 2022 at 10:06:48 PM GMT.

  • @dibyojyotibhattacherjee4279
    @dibyojyotibhattacherjee4279 2 роки тому +17

    Btw, for users, who don't have access or can't use c++20 for some reason, use std::generate, for a random vector...

    • @PvblivsAelivs
      @PvblivsAelivs Рік тому

      How about "it's way too bloated"? Bjarne Straussup had a good idea. Then committees got to it and ruined it.

  • @PKua007
    @PKua007 Рік тому +2

    Ah, I wish I could use C++20, but the computing cluster I target my software to is stuck on GCC 8.3.0. std::ranges would be very helpful

  • @JakobKenda
    @JakobKenda Рік тому +2

    You said one should always use a random_device with a distribution, but why is that?

    • @TheBuilder
      @TheBuilder  Рік тому

      its a better alternative to using module and division to get a range. also its built in so why not use it?

  • @choupapi9643
    @choupapi9643 Рік тому +2

    very informative video btw but quick question, how to set range of random numbers that are generated in an output lets say my random generator displayed a generated numbers of 78934561 but i want to set a range of only 4 numbers which is 7893. what line of code should i input?

    • @TheBuilder
      @TheBuilder  Рік тому +4

      just change the limits in the distribution function. you can also try using "%" and "/" to get rid of the first or last x digits

  • @kanardia
    @kanardia 11 місяців тому +1

    I am in C++ for 30 years and I think the C rand() function is just fine for some uses. Yes, it is "bad" in terms of true randomness, but it can be still useful from time to time for simple things, where puristic randomness is not needed.

    • @BasPower12
      @BasPower12 10 місяців тому

      Do you have any advice for new beginners in C++ like me? You have 30 years of experience

  • @toonimation_official
    @toonimation_official 5 місяців тому

    Bro are you even a coder? Why you using light theme?

  • @Light.--
    @Light.-- 6 місяців тому

    Does not work, I got the same number every run

  • @BlueFireDudester
    @BlueFireDudester Рік тому

    Thank you, I just started learning C++ and holy sht rand() and srand suck.

  • @johnmcook1
    @johnmcook1 Рік тому

    1023 possible combinations of ten numbers should have ran in in a for loop 1023 with no duplicates

  • @-ryb1k3y24
    @-ryb1k3y24 5 місяців тому

    my iota 6:18 just doesnt work (im on c++ 22)

    • @-ryb1k3y24
      @-ryb1k3y24 5 місяців тому

      ok i found the solution u should add numeric library

  • @Orionus83
    @Orionus83 Рік тому

    6:40 to use std::ranges::shuffle you need include not .

  • @VoidloniXaarii
    @VoidloniXaarii Рік тому

    Thank you! Subscribed. Hope you one day do a vid on a random in a range but with a bias towards a value and maybe a way to control the strength of that bias

  • @Mykuss001us
    @Mykuss001us Рік тому

    Ok Help!!! Newbie here! Used the Uniform distribution for random generated number in a function, but I need that number for a "Nested For Loop"; for 1 to the (generated number). Getting a error code of no conversion possible to make the randomize number into a integer. How do I get the " dist(rd)" (generated number) converted to a number for use in a "for loop"??

    • @TheBuilder
      @TheBuilder  Рік тому

      clearly a conversion issue, I can't help if you don't post source...or ask chatgpt

  • @darcash1738
    @darcash1738 7 місяців тому

    Im getting some error that std::ranges has not been declared even though i did the #include thing correctly. Also, just started today, why arent we using std namespace here? isn't it always more convenient to do that?

    • @-ryb1k3y24
      @-ryb1k3y24 5 місяців тому

      its not efficient to use it for whole programm running it just takes much gpu for it to work

  • @RedStoneMatt
    @RedStoneMatt Рік тому +1

    Um, where is the part where you explain why these solutions are actually better than rand?

    • @TheBuilder
      @TheBuilder  Рік тому +1

      what is there to explain?

    • @RedStoneMatt
      @RedStoneMatt Рік тому +7

      @@TheBuilder in the title you tell to stop using rand, and in the video you give alternatives to it, but you didn't explain why should we use these alternatives instead of rand in the first place

    • @RedStoneMatt
      @RedStoneMatt Рік тому +1

      @@o0jjc951 I did, though it is irrelevant because this result happens because this guy didn't do it even properly
      you need to add "srand(time(NULL));" at the beginning to make the seed of your random generator be dependent of the current time so you get different results everytime
      but mere seconds later, he did add it later on and it did work, so where's the problem with the rand function? you are the one who didn't watch a minute of the video bro
      And what does he say next? "the problem is that ti's too simple and not flexible enough" just WHAT??
      It's too simple?? And not flexible enough?? It's a random number generator bro, what flexibility do you need???

    • @ernststravoblofeld
      @ernststravoblofeld Рік тому

      Because it's just something he heard someone say and thought it sounded smart. Rand works fine for most things.

    • @cpK054L
      @cpK054L Рік тому

      @@ernststravoblofeld srand will always be king one liner.

  • @robbeflot5428
    @robbeflot5428 7 місяців тому

    Oh no Light mode, It blinded me!!!

    • @TheBuilder
      @TheBuilder  7 місяців тому

      Your monitor is too bright

  • @mantvydaskazakevicius2121
    @mantvydaskazakevicius2121 6 місяців тому

    It keeps generating 1 when put in a function

  • @BasPower12
    @BasPower12 10 місяців тому

    Your C++ videos are amazing! They help me learn!

  • @codigodesenior3995
    @codigodesenior3995 Рік тому

    ... i was expecting a segment fault at the end...

  • @PetrosZoric
    @PetrosZoric 5 місяців тому

    Awful explanation.

  • @Volker-Dirr
    @Volker-Dirr Рік тому

    hmmm... I think you didn't understood that there are different RNG needed. There are a lot of programms that highly need always the same random numbers. So setting a seed is not a bug, setting a seed is a feature for them.
    First of all you need to think about what RNG do you need. Always the same? Always differnt? cryptographically secure? Does it need to pass special test? Do you need them fast? How many so you need? ...
    Depending on your answers you need to use different random number generators.

    • @TheBuilder
      @TheBuilder  Рік тому

      yes, but using rand in C++ isn't recommended

    • @Volker-Dirr
      @Volker-Dirr Рік тому

      @@TheBuilder Who doesn't recommend it and why is it not recommended?

    • @TheBuilder
      @TheBuilder  Рік тому

      generally its too simple for most tasks. you can read this reply, its fairly complete stackoverflow.com/questions/52869166/why-is-the-use-of-rand-considered-bad

    • @Volker-Dirr
      @Volker-Dirr Рік тому

      @@TheBuilder I read it. As you can see there are many pro and cons for rand() in that stackoverflow articel. In your video you selected only one argument, but that argument is depeding on your coding task. So you selected a "wrong" argument. In my opinion there is only one (strong) argument against rand(): rand() is an unspecified algorithm (So every operating system/compiler implemented it's own version. So you don't know what you get! (So in fact this is nearly the opposite of what you demonstrate in your video)

    • @Volker-Dirr
      @Volker-Dirr Рік тому

      @@TheBuilder Yes, it is not recommended, but in your video your argumentation is totaly wrong. If beginners watch your video, then they will totally missunderstand why it is not recommended. In fact you explain the opposite in your video. rand is not recommended, because users expect always the same random numbers, but as soon as there is a new compiler or and other operation system they migth get other numbers.

  • @daniel_lm8251
    @daniel_lm8251 Рік тому

    I get the same number everytime I run the code why?

    • @TheBuilder
      @TheBuilder  Рік тому

      it's explained in the video. you'd need to set a seed that changes between runs

  • @raydani8748
    @raydani8748 2 роки тому

    What's to stop the code outputting a ridiculously high number in the quadrillions, for example?

    • @TheBuilder
      @TheBuilder  2 роки тому

      With which example?

    • @RedStoneMatt
      @RedStoneMatt Рік тому

      If you're talking about rand(), it is limited to the size of an integer

  • @Mike_Rottchburns
    @Mike_Rottchburns Рік тому

    Thanks for making the right video

  • @filipposkollias
    @filipposkollias Місяць тому

    why dont you use using namespace std; so you dont have to write std:: all the time

  • @PKperformanceEU
    @PKperformanceEU Рік тому

    You should be using RDRAND or RDSEED