lib/Peta/NN/RNG.pm

filter: Statementstmt 100% 19 / 19 Branchbran 100% 2 / 2 Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 6 / 6 Podpod 100% 5 / 5 totaltotal 100% 32 / 32 CC 4 SCAR 6.4
CC
4
Cov
100%
new
3.0
shuffle
2.0
BEGIN
1.0
CRAP 1.9
« blib/lib/Peta/NN/Layer/Embed.pm ↑ Summary lib/Peta/NN/Backend/PDL.pm »
1 package Peta::NN::RNG;
2 # ABSTRACT: seeded random numbers that are the same on every perl
3  
4 # A small seeded generator of our own, not perl's rand(): initial weights and
5 # the shuffle order must be the same on every perl and every run, or a trained
6 # model cannot be reproduced and test thresholds cannot be exact.
7  
8 28 ▶use v5.36;
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 28 our $VERSION = '0.2610090';
11  
12 28 my $MODULUS = 2_147_483_647; # 2**31 - 1, the Park-Miller "minimal standard"
13 28 my $MULTIPLIER = 48_271; # state * multiplier stays below 2**47: exact in an IV
14 28 my $TWO_PI = 6.283185307179586;
15  
16 220 ▶sub new ($class, $seed = 1) {
Subroutine new: called CC=3 SCAR=11.0
Pod documented
17 220 my $state = int($seed) % $MODULUS;
18 220 ▶ $state = 1 if $state <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $state <= 0 1 219 220
19 220 return bless { state => $state }, $class;
20 }
21  
22 # Uniform in the open interval (0, 1).
23 1265475 ▶sub uniform ($self) {
Subroutine uniform: called CC=1 SCAR=0.0
Pod documented
24 1265475 $self->{state} = ($self->{state} * $MULTIPLIER) % $MODULUS;
25 1265475 return $self->{state} / $MODULUS;
26 }
27  
28 # Uniform integer in 0 .. $n-1.
29 1127020 ▶sub below ($self, $n) {
Subroutine below: called CC=1 SCAR=0.0
Pod documented
30 1127020 return int($self->uniform * $n);
31 }
32  
33 # Standard normal, Box-Muller.
34 33423 ▶sub normal ($self) {
Subroutine normal: called CC=1 SCAR=0.0
Pod documented
35 33423 return sqrt(-2 * log($self->uniform)) * cos($TWO_PI * $self->uniform);
36 }
37  
38 # Fisher-Yates, in place.
39 5173 ▶sub shuffle ($self, $list) {
Subroutine shuffle: called CC=2 SCAR=6.9
Pod documented
40 5173 for my $i (reverse 1 .. $#$list) {
41 996460 my $j = $self->below($i + 1);
42 996460 @$list[$i, $j] = @$list[$j, $i];
43 }
44 5173 return $list;
45 }
46  
47 28 1;
48  
49 __END__
« blib/lib/Peta/NN/Layer/Embed.pm ↑ Summary lib/Peta/NN/Backend/PDL.pm »