Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Random Number Generator

by perlaintdead (Scribe)
on Aug 19, 2013 at 21:36 UTC ( [id://1050090]=perlmeditation: print w/replies, xml ) Need Help??

How do you like my RNG?

#!/usr/bin/perl use warnings; use strict; use Time::HiRes qw ( usleep ); $| = 1; print "number of digits: "; my $num = <STDIN>; chomp $num; if($num < 1){ print "grirrrrr. You can't do that! Number must be 1 or greater!!! +\n"; exit(0); } print randmiz0r($num); sub randmiz0r{ my $digCount = shift; my $digCountChanging = $digCount + 1; #offset for first subtractio +n my $results = ""; for(my $i = 0;$i < $digCount;$i++){ my $randInput = 1 . (0 x ($digCountChanging - 1)); #retreave the last diggit my @prepLastDig = split //, &randmore($randInput); my $lastDig = pop @prepLastDig; $results = $lastDig . $results; #sleep because rand funct is time based usleep( int rand int rand 10000 ); # sleep for microseconds } if($results =~ m/^0/){ $results = catchStartZero($results); #numbers like 0345 don't +exist } return $results . "\n"; } sub randmore{ my $r = shift; my $oddCatch = $r % 2; $r = $r - $oddCatch; return (int (rand $r) + int (rand $r)); } sub catchStartZero{ my $removeZero = shift; $removeZero =~ s/^0//; my $notZero = 0; #confusing but nessisary until($notZero ne "0"){ $notZero = randmiz0r(1); chomp $notZero; #a \n is returned with randmiz0r() } return $notZero . $removeZero; }

Replies are listed 'Best First'.
Re: Random Number Generator
by Eily (Monsignor) on Aug 19, 2013 at 22:53 UTC

    # [...] rand funct is time based
    Well ... it might be. The random function has to be initialized with something randomish like the time (but it can also be the position of the mouse, or how much it has moved since start up, the mean typing speed of the user in milliseconds when he entered his password, etc ...), but initialization is only done once. You can check rand's documentation, which tells that srand is called, unless it has already been done. So after your first rand, the time does not change anything. You are actually just wasting time there.

    Do not call srand() multiple times in your program unless you know exactly what you're doing and why you're doing it. [...]. Just do it once at the top of your program, or you won't get random numbers out of rand()!
    This means that you should probably trust rand to be random enough for you, and not try to affect its behavior by messing with it. srand's documentation advises you to have a look at Math::TrulyRandom if you think rand does not do its work properly.

    Using rand until you have a number that fits your expectation isn't a very good idea either, that's wasting time again. If you want to make sure you have a number that's n digit long, without leading 0, you could just do :

    my $n = 10; my $lastDigits = int rand(10**($n-1)); my $firstDigit = 1+int(rand(9)); my $number = $firstDigit.$lastDigits; print $number;

      I was actually researching this issue recently. It turns out that by default, Perl calls srand() with /dev/random (or an equivalent on your platform). Timestamps aren't involved. See util.c and search for Perl_seed.


      "There is no shame in being self-taught, only in not trying to learn in the first place." -- Atrus, Myst: The Book of D'ni.

Re: Random Number Generator
by RichardK (Parson) on Aug 20, 2013 at 10:10 UTC

    What made you think the rand function is time based?

    Try adding srand(1000) to the start of your code and see what happens. You're just wasting time with those usleeps.

    Designing a good random number generator isn't easy, so it's better to use one of the RNG modules that has been properly tested. see rand for some suggestions.

    The maths behind random number generators and their proper testing is really interesting and well worth some study, if you have the time.

Re: Random Number Generator
by BrowserUk (Patriarch) on Aug 19, 2013 at 21:55 UTC
    How do you like my RNG?

    Not much.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Random Number Generator
by Laurent_R (Canon) on Aug 23, 2013 at 21:08 UTC

    Donald Knuth's celebrated masterwork, "The Art of Computer programming", vol. 2 (semi-numerical algorithms), has 193 pages on random numbers in my edition (3rd). You might guess from that that this is a pretty complicated and tricky subject. I would submit that you don't try to do better than existing packages before you've read and understood most of this material (or equivalent from other really authoritative sources).

Re: Random Number Generator
by perlaintdead (Scribe) on Aug 19, 2013 at 23:06 UTC

    I original set out to just make an RNG to fit a certain length of chars but i though i would try to make it a bit more random. Thanks for the suggestions.

Re: Random Number Generator
by perlaintdead (Scribe) on Aug 24, 2013 at 06:29 UTC

    yeah. I didn't think it was a simple subject; I just Thought I'd have so fun with the rand function. It's not for a business or anything.


    Also I'm playing around with my next iteration of this (which is basically non existent anymore sense so much of my old code is flawed).

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlmeditation [id://1050090]
Approved by BrowserUk
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2024-03-29 09:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found