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

Поделиться
HTML-код
  • Опубликовано: 27 янв 2025

Комментарии • 122

  • @RedStoneMatt
    @RedStoneMatt 2 года назад +269

    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 года назад +2

      ye lol

    • @jasmintea8825
      @jasmintea8825 2 года назад

      W

    • @appleturdpie
      @appleturdpie Год назад +16

      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.

  • @SamoshiBG
    @SamoshiBG 2 года назад +87

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

    • @davidjohnston4240
      @davidjohnston4240 2 года назад

      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 2 года назад

      @@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...

  • @cno9984
    @cno9984 2 года назад +21

    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.

  • @peligros13
    @peligros13 2 года назад +63

    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  2 года назад +9

      Good tip

    • @davidjohnston4240
      @davidjohnston4240 2 года назад +3

      ​@@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 2 года назад +2

      @@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 2 года назад

      @@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 2 года назад

      @@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 😂"

  • @biskitpagla
    @biskitpagla 2 года назад +25

    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.

  • @dibyojyotibhattacherjee4279
    @dibyojyotibhattacherjee4279 2 года назад +18

    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 2 года назад

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

  • @aenapoeka
    @aenapoeka 2 года назад +6

    Straight to the point and zero useless bullshit, nice.

  • @BasPower12
    @BasPower12 Год назад

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

  • @Orionus83
    @Orionus83 Год назад

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

  • @kirestus
    @kirestus 3 месяца назад

    this is way better than my solution, which was to make a deck of cards and then use 1+rand(time(0))%2 to basically get a coin flip, if its 1 it goes i cut it from the list and put it in the front if its 2 it gets cut from the list and put at the end, then i run that 200 times and get what seems to be random

  • @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

  • @kanardia
    @kanardia Год назад +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 Год назад

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

  • @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

  • @PKua007
    @PKua007 2 года назад +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 года назад +2

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

    • @TheBuilder
      @TheBuilder  2 года назад

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

  • @treyquattro
    @treyquattro 2 месяца назад

    you should be passing NULL into srand. nullptr is a C++ value of nullptr_t type. Sure, they're virtually always going to equate to the same zero rvalue, but the definitions could be changed and then you'd break functionality. So while it may seem correct or convenient to pass nullptr into C functions from C++, you should abide by the defined interface.

  • @its4theer
    @its4theer 7 месяцев назад +1

    this makes alot of assumtion about the viewer knowledge.

    • @TheBuilder
      @TheBuilder  7 месяцев назад

      like what?

    • @its4theer
      @its4theer 7 месяцев назад +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  7 месяцев назад

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

    • @its4theer
      @its4theer 7 месяцев назад

      @@TheBuilder I will thanks ❤️

  • @stephenhowe4107
    @stephenhowe4107 2 года назад

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

    • @TheBuilder
      @TheBuilder  2 года назад +1

      probably included by iostream. libraries can include other libraries

    • @Kamion008-xu6ie
      @Kamion008-xu6ie 8 месяцев назад

      already included by the compiler

    • @stephenhowe4107
      @stephenhowe4107 8 месяцев назад

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

  • @Vili69420
    @Vili69420 2 года назад +2

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

    • @TheBuilder
      @TheBuilder  2 года назад +1

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

    • @Vili69420
      @Vili69420 2 года назад

      @@TheBuilder oh lol :v

  • @darcash1738
    @darcash1738 11 месяцев назад

    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 9 месяцев назад

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

  • @-ryb1k3y24
    @-ryb1k3y24 9 месяцев назад

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

    • @-ryb1k3y24
      @-ryb1k3y24 9 месяцев назад

      ok i found the solution u should add numeric library

  • @choupapi9643
    @choupapi9643 2 года назад +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  2 года назад +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

  • @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

  • @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 2 года назад

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

  • @BlueFireDudester
    @BlueFireDudester Год назад

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

  • @cykon69
    @cykon69 3 месяца назад

    it always spits out the same number for me, even though i've made everything exactly like in the vid

  • @mantvydaskazakevicius2121
    @mantvydaskazakevicius2121 10 месяцев назад

    It keeps generating 1 when put in a function

  • @islam_095._
    @islam_095._ Год назад

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

  • @johnmcook1
    @johnmcook1 Год назад

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

  • @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

  • @Mike_Rottchburns
    @Mike_Rottchburns 2 года назад

    Thanks for making the right video

  • @kenoldavid
    @kenoldavid 2 года назад +1

    I wish I could give this a double like 👍

  • @RedStoneMatt
    @RedStoneMatt 2 года назад +1

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

    • @TheBuilder
      @TheBuilder  2 года назад +1

      what is there to explain?

    • @RedStoneMatt
      @RedStoneMatt 2 года назад +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 2 года назад +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 2 года назад

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

    • @cpK054L
      @cpK054L 2 года назад

      @@ernststravoblofeld srand will always be king one liner.

  • @Light.--
    @Light.-- 10 месяцев назад

    Does not work, I got the same number every run

  • @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.

  • @djthdinsessions
    @djthdinsessions 2 года назад +1

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

    • @coe9900
      @coe9900 2 года назад

      So what to use?

    • @djthdinsessions
      @djthdinsessions 2 года назад

      @@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

  • @codigodesenior3995
    @codigodesenior3995 2 года назад

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

  • @toonimation_official
    @toonimation_official 9 месяцев назад

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

  • @robbeflot5428
    @robbeflot5428 11 месяцев назад

    Oh no Light mode, It blinded me!!!

    • @TheBuilder
      @TheBuilder  11 месяцев назад

      Your monitor is too bright

  • @filipposkollias
    @filipposkollias 6 месяцев назад

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

    • @TheBuilder
      @TheBuilder  Месяц назад

      If I do I'd get comments telling me it's bad practice

  • @ismailgharbiyeh7743
    @ismailgharbiyeh7743 11 месяцев назад

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

  • @PetrosZoric
    @PetrosZoric 9 месяцев назад

    Awful explanation.

  • @PKperformanceEU
    @PKperformanceEU Год назад

    You should be using RDRAND or RDSEED