File: Range.pm

package info (click to toggle)
libmath-random-mt-auto-perl 6.23-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid, trixie
  • size: 576 kB
  • sloc: perl: 1,068; makefile: 3
file content (422 lines) | stat: -rw-r--r-- 10,042 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
package Math::Random::MT::Auto::Range; {

use strict;
use warnings;

our $VERSION = '6.23';
$VERSION = eval $VERSION;

use Scalar::Util 1.18;

# Declare ourself as a subclass
use Object::InsideOut 'Math::Random::MT::Auto' => [ ':!auto' ];


### Inside-out Object Attributes ###

# Object data is stored in these attribute hashes, and is keyed to the object
# by a unique ID that is stored in the object's scalar reference.
#
# These hashes are declared using the 'Field' attribute.

# Range information for our objects
my %type_of   :Field;  # Type of return value:  INTEGER or DOUBLE
my %low_for   :Field;  # Low end of the range
my %high_for  :Field;  # High end of the range
my %range_for :Field;  # 'Difference' between LOW and HIGH
                       #   (used for performance considerations)


### Inside-out Object Internal Subroutines ###

my %init_args :InitArgs = (
    'LOW' => {
        'REGEX'     => qr/^lo(?:w)?$/i,
        'MANDATORY' => 1,
        'TYPE'      => 'NUMBER',
    },
    'HIGH' => {
        'REGEX'     => qr/^hi(?:gh)?$/i,
        'MANDATORY' => 1,
        'TYPE'      => 'NUMBER',
    },
    'TYPE' => qr/^type$/i,   # Range type
);

# Object initializer
sub _init :Init
{
    my $self = $_[0];
    my $args = $_[1];   # Hash ref containing arguments from object
                        # constructor as specified by %init_args above

    # Default 'TYPE' to 'INTEGER' if 'LOW' and 'HIGH' are both integers.
    # Otherwise, default to 'DOUBLE'.
    if (! exists($$args{'TYPE'})) {
        my $lo = $$args{'LOW'};
        my $hi = $$args{'HIGH'};
        $$args{'TYPE'} = (($lo == int($lo)) && ($hi == int($hi)))
                         ? 'INTEGER'
                         : 'DOUBLE';
    }

    # Initialize object
    $self->set_range_type($$args{'TYPE'});
    $self->set_range($$args{'LOW'}, $$args{'HIGH'});
}


### Object Methods ###

# Sets numeric type random values
sub set_range_type
{
    my $self = shift;

    # Check argument
    my $type = $_[0];
    if (! defined($type) || $type !~ /^[ID]/i) {
        MRMA::Args->die(
            'caller_level' => (caller() eq __PACKAGE__) ? 2 : 0,
            'message'      => "Bad range type: $type",
            'Usage'        => q/Range type must be 'INTEGER' or 'DOUBLE'/);
    }

    $type_of{$$self} = ($type =~ /^I/i) ? 'INTEGER' : 'DOUBLE';
}


# Return current range type
sub get_range_type
{
    my $self = shift;
    return ($type_of{$$self});
}


# Set random number range
sub set_range
{
    my $self = shift;

    # Check for arguments
    my ($lo, $hi) = @_;
    if (! Scalar::Util::looks_like_number($lo) ||
        ! Scalar::Util::looks_like_number($hi))
    {
        MRMA::Args->die(
            'message'      => q/Bad range arguments/,
            'Usage'        => q/Range must be specified using 2 numeric arguments/);
    }

    # Ensure arguments are of the proper type
    if ($type_of{$$self} eq 'INTEGER') {
        $lo = int($lo);
        $hi = int($hi);
    } else {
        $lo = 0.0 + $lo;
        $hi = 0.0 + $hi;
    }
    # Make sure 'LOW' and 'HIGH' are not the same
    if ($lo == $hi) {
        MRMA::Args->die(
            'caller_level' => (caller() eq __PACKAGE__) ? 2 : 0,
            'message'      => q/Invalid arguments: LOW and HIGH are equal/,
            'Usage'        => q/The range must be a non-zero interval/);
    }
    # Ensure LOW < HIGH
    if ($lo > $hi) {
        ($lo, $hi) = ($hi, $lo);
    }

    # Set range parameters
    $low_for{$$self}  = $lo;
    $high_for{$$self} = $hi;
    if ($type_of{$$self} eq 'INTEGER') {
        $range_for{$$self} = ($high_for{$$self} - $low_for{$$self}) + 1;
    } else {
        $range_for{$$self} = $high_for{$$self} - $low_for{$$self};
    }
}


# Return object's random number range
sub get_range
{
    my $self = shift;
    return ($low_for{$$self}, $high_for{$$self});
}


# Return a random number of the configured type and within the configured
# range.
sub rrand
{
    my $self = $_[0];

    if ($type_of{$$self} eq 'INTEGER') {
        # Integer random number range [LOW, HIGH]
        return (($self->irand() % $range_for{$$self}) + $low_for{$$self});
    } else {
        # Floating-point random number range [LOW, HIGH)
        return ($self->rand($range_for{$$self}) + $low_for{$$self});
    }
}


### Overloading ###

sub as_string :Stringify :Numerify
{
    return ($_[0]->rrand());
}

sub bool :Boolify
{
    return ($_[0]->rrand() & 1);
}

sub array :Arrayify
{
    my $self  = $_[0];
    my $count = $_[1] || 1;

    my @ary;
    do {
        push(@ary, $self->rrand());
    } while (--$count > 0);

    return (\@ary);
}

sub _code :Codify
{
    my $self = $_[0];
    return (sub { $self->rrand(); });
}


### Serialization ###

# Support for ->dump() method
sub _dump :Dumper
{
    my $obj = shift;

    return ({
                'HIGH'  => $high_for{$$obj},
                'LOW'   => $low_for{$$obj},
                'TYPE'  => $type_of{$$obj}
            });
}

# Support for Object::InsideOut::pump()
sub _pump :Pumper
{
    my ($obj, $data) = @_;

    $obj->set_range_type($$data{'TYPE'});
    $obj->set_range($$data{'LOW'}, $$data{'HIGH'});
}

}  # End of package's lexical scope

1;

__END__

=head1 NAME

Math::Random::MT::Auto::Range - Range-valued PRNGs

=head1 SYNOPSIS

    use strict;
    use warnings;
    use Math::Random::MT::Auto::Range;

    # Integer random number range
    my $die = Math::Random::MT::Auto::Range->new(LO => 1, HI => 6);
    my $roll = $die->rrand();

    # Floating-point random number range
    my $compass = Math::Random::MT::Auto::Range->new(LO => 0, HI => 360,
                                                     TYPE => 'DOUBLE');
    my $course = $compass->rrand();

=head1 DESCRIPTION

This module creates range-valued pseudorandom number generators (PRNGs) that
return random values between two specified limits.

While useful in itself, the primary purpose of this module is to provide an
example of how to create subclasses of Math::Random::MT::Auto within
L<Object::InsideOut>'s inside-out object model.

=head1 MODULE DECLARATION

Add the following to the top of our application code:

    use strict;
    use warnings;
    use Math::Random::MT::Auto::Range;

This module is strictly OO, and does not export any functions or symbols.

=head1 METHODS

=over

=item Math::Random::MT::Auto::Range->new

Creates a new range-valued PRNG.

    my $prng = Math::Random::MT::Auto::Range->new( %options );

Available options are:

=over

=item 'LOW' => $num

=item 'HIGH' => $num

Sets the limits over which the values return by the PRNG will range.  These
arguments are mandatory, and C<LOW> must not be equal to C<HIGH>.

If the C<TYPE> for the PRNG is C<INTEGER>, then the range will be C<LOW> to
C<HIGH> inclusive (i.e., [LOW, HIGH]).  If C<DOUBLE>, then C<LOW> inclusive to
C<HIGH> exclusive (i.e., [LOW, HIGH)).

C<LO> and C<HI> can be used as synonyms for C<LOW> and C<HIGH>, respectively.

=item 'TYPE' => 'INTEGER'

=item 'TYPE' => 'DOUBLE'

Sets the type for the values returned from the PRNG.  If C<TYPE> is not
specified, it will default to C<INTEGER> if both C<LOW> and C<HIGH> are
integers.

=back

The options above are also supported using lowercase and mixed-case (e.g.,
'low', 'hi', 'Type', etc.).

Additionally, objects created with this package can take any of the options
supported by the L<Math::Random::MT::Auto> class, namely, C<STATE>, C<SEED>
and C<STATE>.

=item $obj->new

Creates a new PRNG in the same manner as
L</"Math::Random::MT::Auto::Range-E<gt>new">.

    my $prng2 = $prng1->new( %options );

=back

In addition to the methods describe below, the objects created by this package
inherit all the object methods provided by the L<Math::Random::MT::Auto>
class, including the C<->clone()> method.

=over

=item $obj->rrand

Returns a random number of the configured type within the configured range.

    my $rand = $prng->rrand();

If the C<TYPE> for the PRNG is C<INTEGER>, then the range will be C<LOW> to
C<HIGH> inclusive (i.e., [LOW, HIGH]).  If C<DOUBLE>, then C<LOW> inclusive to
C<HIGH> exclusive (i.e., [LOW, HIGH)).

=item $obj->set_range_type

Sets the numeric type for the random numbers returned by the PRNG.

    $prng->set_range_type('INTEGER');
      # or
    $prng->set_range_type('DOUBLE');

=item $obj->get_range_type

Returns the numeric type ('INTEGER' or 'DOUBLE') for the random numbers
returned by the PRNG.

    my $type = $prng->get_range_type();

=item $obj->set_range

Sets the limits for the PRNG's return value range.

    $prng->set_range($lo, $hi);

C<$lo> must not be equal to C<$hi>.

=item $obj->get_range

Returns a list of the PRNG's range limits.

    my ($lo, $hi) = $prng->get_range();

=back

=head1 INSIDE-OUT OBJECTS

Capabilities provided by L<Object::InsideOut> are supported by this modules.
See L<Math::Random::MT::Auto/"INSIDE-OUT OBJECTS"> for more information.

=head2 Coercion

Object coercion is supported in the same manner as documented in
See L<Math::Random::MT::Auto/"Coercion"> except that the underlying random
number method is C<-E<gt>rrand()>.

=head1 DIAGNOSTICS

=over

=item * Missing parameter: LOW

=item * Missing parameter: HIGH

The L<LOW and HIGH|/"'LOW' =E<gt> $num"> values for the range must be
specified to L<-E<gt>new()|/"Math::Random::MT::Auto::Range-E<gt>new">.

=item * Arg to ->set_range_type() must be 'INTEGER' or 'DOUBLE'

Self explanatory.

=item * ->range() requires two numeric args

Self explanatory.

=item * Invalid arguments: LOW and HIGH are equal

You cannot specify a range of zero width.

=back

This module will reverse the range limits if they are specified in the wrong
order (i.e., it makes sure that C<LOW < HIGH>).

=head1 SEE ALSO

L<Math::Random::MT::Auto>

L<Object::InsideOut>

=head1 AUTHOR

Jerry D. Hedden, S<E<lt>jdhedden AT cpan DOT orgE<gt>>

=head1 COPYRIGHT AND LICENSE

Copyright 2005 - 2009 Jerry D. Hedden. All rights reserved.

This program is free software; you can redistribute it and/or modify it under
the same terms as Perl itself.

=cut