Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Sampling From a Histogram Distribution

by davido (Archbishop)
on Jan 06, 2014 at 03:58 UTC ( #1069449=note: print w/replies, xml ) Need Help??


in reply to Sampling From a Histogram Distribution

Another approach: Use Bytes::Random::Secure's string_from method. Supply it with the following "bag" string: "aaaaoooooooooooooooooooppppppppppccccc", and draw as many random characters as you need. The distribution will be appropriately weighted.

Update: Here's how it would look. I'm not convinced that I care for it aesthetically, but the randomness is high quality, and the source is well tested.

use Bytes::Random::Secure; my $rng = Bytes::Random::Secure->new( NonBlocking => 1 ); my %weight = ( apples => 4, oranges => 19, pairs => 10, peaches => 5 ) +; my %map = ( qw/ apples a oranges o pairs p peaches c / ); my %rmap = reverse %map; my $bag = join '', map { ( $map{$_} ) x $weight{$_} } keys %weight; print $rmap{$rng->string_from($bag,1)}, $_% 8 == 0 ? "\n" : "\t" for 1 .. 100; print "\n";

Sample output:

$ ./mytest.pl pairs oranges oranges oranges pairs apples oranges + apples oranges pairs oranges oranges pairs peaches peaches + apples peaches pairs oranges oranges oranges pairs oranges + oranges peaches peaches peaches oranges oranges peaches oran +ges oranges ... and so on ...

When that module was created, it was an intentional design decision that duplicate characters in the "bag" string would increase the weighting of those characters.


Dave

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1069449]
help
Chatterbox?
[vedagiri89]: hi all! i need your help
[vedagiri89]: i'm facing this issue: Attempt to reload DynaLoader.pm aborted.\ nCompilation failed in require at /usr/lib64/perl5/ vendor_perl//APR. pm line 19.\nBEGIN failed--compilatio n aborted at /usr/lib64/perl5/ vendor_perl//APR. pm line 19.
[vedagiri89]: how do fix this issue
[choroba]: This usually happens when you have more than one version of Perl, and you mix the libraries
[hippo]: Which O/S?
[vedagiri89]: i have searched many forum...not getting resolutions
[vedagiri89]: centos

How do I use this? | Other CB clients
Other Users?
Others studying the Monastery: (7)
As of 2018-06-19 11:15 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?



    Results (113 votes). Check out past polls.

    Notices?