xref: /netbsd-src/external/lgpl3/gmp/dist/demos/perl/GMP.pm (revision 6a493d6bc668897c91594964a732d38505b70cbb)
1# GMP perl module
2
3# Copyright 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
4#
5# This file is part of the GNU MP Library.
6#
7# The GNU MP Library is free software; you can redistribute it and/or modify
8# it under the terms of the GNU Lesser General Public License as published
9# by the Free Software Foundation; either version 3 of the License, or (at
10# your option) any later version.
11#
12# The GNU MP Library is distributed in the hope that it will be useful, but
13# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
15# License for more details.
16#
17# You should have received a copy of the GNU Lesser General Public License
18# along with the GNU MP Library.  If not, see http://www.gnu.org/licenses/.
19
20# [Note: The above copyright notice is repeated in the documentation section
21# below, in order to get it into man pages etc generated by the various pod
22# conversions.  When changing, be sure to update below too.]
23
24
25# This code is designed to work with perl 5.005, so it and the sub-packages
26# aren't as modern as they could be.
27
28package GMP;
29
30require Symbol;
31require Exporter;
32require DynaLoader;
33@ISA = qw(Exporter DynaLoader);
34
35@EXPORT = qw();
36@EXPORT_OK = qw(version);
37%EXPORT_TAGS = ('all' => [qw(
38                             get_d get_d_2exp get_si get_str integer_p
39                             printf sgn sprintf)],
40		'constants' => [()]);
41Exporter::export_ok_tags('all');
42
43$VERSION = '2.00';
44bootstrap GMP $VERSION;
45
46
47# The format string is cut up into "%" specifiers so GMP types can be
48# passed to GMP::sprintf_internal.  Any "*"s are interpolated before
49# calling sprintf_internal, which saves worrying about variable
50# argument lists there.
51#
52# Because sprintf_internal is only called after the conversion and
53# operand have been checked there won't be any crashes from a bad
54# format string.
55#
56sub sprintf {
57  my $fmt = shift;
58  my $out = '';
59  my ($pre, $dummy, $pat, $rest);
60
61  while (($pre, $dummy, $pat, $rest) = ($fmt =~ /^((%%|[^%])*)(%[- +#.*hlLqv\d]*[bcdfeEgGinopsuxX])(.*)$/s)) {
62
63    $out .= $pre;
64
65    my $pat2 = $pat;    # $pat with "*"s expanded
66    my @params = ();    # arguments per "*"s
67    while ($pat2 =~ /[*]/) {
68      my $arg = shift;
69      $pat2 =~ s/[*]/$arg/;
70      push @params, $arg;
71    }
72
73    if (UNIVERSAL::isa($_[0],"GMP::Mpz")) {
74      if ($pat2 !~ /[dioxX]$/) {
75	die "GMP::sprintf: unsupported output format for mpz: $pat2\n";
76      }
77      $pat2 =~ s/(.)$/Z$1/;
78      $out .= sprintf_internal ($pat2, shift);
79
80    } elsif (UNIVERSAL::isa($_[0],"GMP::Mpq")) {
81      if ($pat2 !~ /[dioxX]$/) {
82	die "GMP::sprintf: unsupported output format for mpq: $pat2\n";
83      }
84      $pat2 =~ s/(.)$/Q$1/;
85      $out .= sprintf_internal ($pat2, shift);
86
87    } elsif (UNIVERSAL::isa($_[0],"GMP::Mpf")) {
88      if ($pat2 !~ /[eEfgG]$/) {
89	die "GMP::sprintf: unsupported output format for mpf: $pat2\n";
90      }
91      $pat2 =~ s/(.)$/F$1/;
92      $out .= sprintf_internal ($pat2, shift);
93
94    } elsif ($pat =~ /n$/) {
95      # do it this way so h, l or V type modifiers are respected, and use a
96      # dummy variable to avoid a warning about discarding the value
97      my $dummy = sprintf "%s$pat", $out, $_[0];
98      shift;
99
100    } else {
101      $out .= sprintf $pat, @params, shift;
102    }
103
104    $fmt = $rest;
105  }
106  $out .= $fmt;
107  return $out;
108}
109
110sub printf {
111  if (ref($_[0]) eq 'GLOB') {
112    my $h = Symbol::qualify_to_ref(shift, caller);
113    print $h GMP::sprintf(@_);
114  } else {
115    print STDOUT GMP::sprintf(@_);
116  }
117}
118
1191;
120__END__
121
122
123
124=head1 NAME
125
126GMP - Perl interface to the GNU Multiple Precision Arithmetic Library
127
128=head1 SYNOPSIS
129
130    use GMP;
131    use GMP::Mpz;
132    use GMP::Mpq;
133    use GMP::Mpf;
134    use GMP::Rand;
135
136=head1 DESCRIPTION
137
138This module provides access to GNU MP arbitrary precision integers,
139rationals and floating point.
140
141No functions are exported from these packages by default, but can be
142selected in the usual way, or the tag :all for everything.
143
144    use GMP::Mpz qw(gcd, lcm);   # just these functions
145    use GMP::Mpq qw(:all);       # everything in mpq
146
147=head2 GMP::Mpz
148
149This class provides arbitrary precision integers.  A new mpz can be
150constructed with C<mpz>.  The initial value can be an integer, float,
151string, mpz, mpq or mpf.  Floats, mpq and mpf will be automatically
152truncated to an integer.
153
154    use GMP::Mpz qw(:all);
155    my $a = mpz(123);
156    my $b = mpz("0xFFFF");
157    my $c = mpz(1.5);       # truncated
158
159The following overloaded operators are available, and corresponding
160assignment forms like C<+=>,
161
162=over 4
163
164=item
165
166+ - * / % E<lt>E<lt> E<gt>E<gt> ** & | ^ ! E<lt> E<lt>= == != E<gt> E<gt>=
167E<lt>=E<gt> abs not sqrt
168
169=back
170
171C</> and C<%> round towards zero (as per the C<tdiv> functions in GMP).
172
173The following functions are available, behaving the same as the
174corresponding GMP mpz functions,
175
176=over 4
177
178=item
179
180bin, cdiv, cdiv_2exp, clrbit, combit, congruent_p, congruent_2exp_p,
181divexact, divisible_p, divisible_2exp_p, even_p, fac, fdiv, fdiv_2exp, fib,
182fib2, gcd, gcdext, hamdist, invert, jacobi, kronecker, lcm, lucnum, lucnum2,
183mod, mpz_export, mpz_import, nextprime, odd_p, perfect_power_p,
184perfect_square_p, popcount, powm, probab_prime_p, realloc, remove, root,
185roote, scan0, scan1, setbit, sizeinbase, sqrtrem, tdiv, tdiv_2exp, tstbit
186
187=back
188
189C<cdiv>, C<fdiv> and C<tdiv> and their C<2exp> variants return a
190quotient/remainder pair.  C<fib2> returns a pair F[n] and F[n-1], similarly
191C<lucnum2>.  C<gcd> and C<lcm> accept a variable number of arguments (one or
192more).  C<gcdext> returns a triplet of gcd and two cofactors, for example
193
194    use GMP::Mpz qw(:all);
195    $a = 7257;
196    $b = 10701;
197    ($g, $x, $y) = gcdext ($a, $b);
198    print "gcd($a,$b) is $g, and $g == $a*$x + $b*$y\n";
199
200C<mpz_import> and C<mpz_export> are so named to avoid the C<import> keyword.
201Their parameters are as follows,
202
203    $z = mpz_import ($order, $size, $endian, $nails, $string);
204    $string = mpz_export ($order, $size, $endian, $nails, $z);
205
206The order, size, endian and nails parameters are as per the corresponding C
207functions.  The string input for C<mpz_import> is interpreted as byte data
208and must be a multiple of $size bytes.  C<mpz_export> conversely returns a
209string of byte data, which will be a multiple of $size bytes.
210
211C<invert> returns the inverse, or undef if it doesn't exist.  C<remove>
212returns a remainder/multiplicity pair.  C<root> returns the nth root, and
213C<roote> returns a root/bool pair, the bool indicating whether the root is
214exact.  C<sqrtrem> and C<rootrem> return a root/remainder pair.
215
216C<clrbit>, C<combit> and C<setbit> expect a variable which they can modify,
217it doesn't make sense to pass a literal constant.  Only the given variable
218is modified, if other variables are referencing the same mpz object then a
219new copy is made of it.  If the variable isn't an mpz it will be coerced to
220one.  For instance,
221
222    use GMP::Mpz qw(setbit);
223    setbit (123, 0);  # wrong, don't pass a constant
224    $a = mpz(6);
225    $b = $a;
226    setbit ($a, 0);   # $a becomes 7, $b stays at 6
227
228C<scan0> and C<scan1> return ~0 if no 0 or 1 bit respectively is found.
229
230=head2 GMP::Mpq
231
232This class provides rationals with arbitrary precision numerators and
233denominators.  A new mpq can be constructed with C<mpq>.  The initial value
234can be an integer, float, string, mpz, mpq or mpf, or a pair of integers or
235mpz's.  No precision is lost when converting a float or mpf, the exact value
236is retained.
237
238    use GMP::Mpq qw(:all);
239    $a = mpq();              # zero
240    $b = mpq(0.5);           # gives 1/2
241    $b = mpq(14);            # integer 14
242    $b = mpq(3,4);           # fraction 3/4
243    $b = mpq("7/12");        # fraction 7/12
244    $b = mpq("0xFF/0x100");  # fraction 255/256
245
246When a fraction is given, it should be in the canonical form specified in
247the GMP manual, which is denominator positive, no common factors, and zero
248always represented as 0/1.  If not then C<canonicalize> can be called to put
249it in that form.  For example,
250
251    use GMP::Mpq qw(:all);
252    $q = mpq(21,15);   # eek! common factor 3
253    canonicalize($q);  # get rid of it
254
255The following overloaded operators are available, and corresponding
256assignment forms like C<+=>,
257
258=over 4
259
260=item
261
262+ - * / E<lt>E<lt> E<gt>E<gt> ** ! E<lt> E<lt>= == != E<gt> E<gt>=
263E<lt>=E<gt> abs not
264
265=back
266
267The following functions are available,
268
269=over 4
270
271=item
272
273den, inv, num
274
275=back
276
277C<inv> calculates 1/q, as per the corresponding GMP function.  C<num> and
278C<den> return an mpz copy of the numerator or denominator respectively.  In
279the future C<num> and C<den> might give lvalues so the original mpq can be
280modified through them, but this is not done currently.
281
282=head2 GMP::Mpf
283
284This class provides arbitrary precision floating point numbers.  The
285mantissa is an arbitrary user-selected precision and the exponent is a fixed
286size (one machine word).
287
288A new mpf can be constructed with C<mpf>.  The initial value can be an
289integer, float, string, mpz, mpq or mpf.  The second argument specifies the
290desired precision in bits, or if omitted then the default precision is used.
291
292    use GMP::Mpf qw(:all);
293    $a = mpf();         # zero
294    $b = mpf(-7.5);     # default precision
295    $c = mpf(1.5, 500); # 500 bits precision
296    $d = mpf("1.0000000000000001");
297
298The following overloaded operators are available, with the corresponding
299assignment forms like C<+=>,
300
301=over 4
302
303=item
304
305+ - * / E<lt>E<lt> E<gt>E<gt> ** ! E<lt> E<lt>= == != E<gt> E<gt>=
306E<lt>=E<gt> abs not sqrt
307
308=back
309
310The following functions are available, behaving the same as the
311corresponding GMP mpf functions,
312
313=over 4
314
315=item
316
317ceil, floor, get_default_prec, get_prec, mpf_eq, set_default_prec, set_prec,
318trunc
319
320=back
321
322C<mpf_eq> is so named to avoid clashing with the perl C<eq> operator.
323
324C<set_prec> expects a variable which it can modify, it doesn't make sense to
325pass a literal constant.  Only the given variable is modified, if other
326variables are referencing the same mpf object then a new copy is made of it.
327If the variable isn't an mpf it will be coerced to one.
328
329Results are the same precision as inputs, or if two mpf's are given to a
330binary operator then the precision of the first is used.  For example,
331
332    use GMP::Mpf qw(mpf);
333    $a = mpf(2.0, 100);
334    $b = mpf(2.0, 500);
335    $c = $a + $b;         # gives 100 bits precision
336
337Mpf to string conversion via "" or the usual string contexts uses C<$#> the
338same as normal float to string conversions, or defaults to C<%.g> if C<$#>
339is not defined.  C<%.g> means all significant digits in the selected
340precision.
341
342=head2 GMP class
343
344The following functions are available in the GMP class,
345
346=over 4
347
348=item
349
350fits_slong_p, get_d, get_d_2exp, get_si, get_str, integer_p, printf, sgn,
351sprintf, version
352
353=back
354
355C<get_d_2exp> accepts any integer, string, float, mpz, mpq or mpf operands
356and returns a float and an integer exponent,
357
358    ($dbl, $exp) = get_d_2exp (mpf ("3.0"));
359    # dbl is 0.75, exp is 2
360
361C<get_str> takes an optional second argument which is the base, defaulting
362to decimal.  A negative base means upper case, as per the C functions.  For
363integer, integer string, mpz or mpq operands a string is returned.
364
365    use GMP qw(:all);
366    use GMP::Mpq qw(:all);
367    print get_str(mpq(-5,8)),"\n";      # -5/8
368    print get_str(255,16),"\n";         # ff
369
370For float, float strings or mpf operands, C<get_str> accepts an optional
371third parameter being how many digits to produce, defaulting to 0 which
372means all digits.  (Only as many digits as can be accurately represented by
373the float precision are ever produced though.)  A string/exponent pair is
374returned, as per the C mpf_get_str function.  For example,
375
376    use GMP qw(:all);
377    use GMP::Mpf qw(:all);
378    ($s, $e) = get_str(111.111111111, 10, 4);
379    printf ".$se$e\n";                  # .1111e3
380    ($s, $e) = get_str(1.625, 10);
381    print "0.$s*10^$e\n";               # 0.1625*10^1
382    ($s, $e) = get_str(mpf(2)**20, 16);
383    printf ".%s@%x\n", $s, $e;          # .1@14
384
385C<printf> and C<sprintf> allow formatted output of GMP types.  mpz and mpq
386values can be used with integer conversions (d, o, x, X) and mpf with float
387conversions (f, e, E, g, G).  All the standard perl printf features are
388available too.  For example,
389
390    use GMP::Mpz qw(mpz);
391    use GMP::Mpf qw(mpf);
392    GMP::printf ("%d %d %s", 123, mpz(2)**128, 'foo');
393    GMP::printf STDERR "%.40f", mpf(1.234);
394
395In perl 5.6.1 it doesn't seem to work to export C<printf>, the plain builtin
396C<printf> is reached unless calls are C<&printf()> style.  Explicit use of
397C<GMP::printf> is suggested.  C<sprintf> doesn't suffer this problem.
398
399    use GMP qw(sprintf);
400    use GMP::Mpq qw(mpq);
401    $s = sprintf "%x", mpq(15,16);
402
403C<version> is not exported by default or by tag :all, calling it as
404C<GMP::version()> is recommended.  It returns the GMP library version
405string, which is not to be confused with the module version number.
406
407The other GMP module functions behave as per the corresponding GMP routines,
408and accept any integer, string, float, mpz, mpq or mpf.  For example,
409
410    use GMP qw(:all);
411    use GMP::Mpz qw(mpz);
412    $z = mpz(123);
413    print sgn($z);    # gives 1
414
415Because each of GMP::Mpz, GMP::Mpq and GMP::Mpf is a sub-class of GMP,
416C<-E<gt>> style calls work too.
417
418    use GMP qw(:all);
419    use GMP::Mpq qw(mpf);
420    $q = mpq(-5,7);
421    if ($q->integer_p())   # false
422      ...
423
424=head2 GMP::Rand
425
426This class provides objects holding an algorithm and state for random number
427generation.  C<randstate> creates a new object, for example,
428
429    use GMP::Rand qw(randstate);
430    $r = randstate();
431    $r = randstate('lc_2exp_size', 64);
432    $r = randstate('lc_2exp', 43840821, 1, 32);
433    $r = randstate('mt');
434    $r = randstate($another_r);
435
436With no parameters this corresponds to the C function
437C<gmp_randinit_default>, and is a compromise between speed and randomness.
438'lc_2exp_size' corresponds to C<gmp_randinit_lc_2exp_size>, 'lc_2exp'
439corresponds to C<gmp_randinit_lc_2exp>, and 'mt' corresponds to
440C<gmp_randinit_mt>.  Or when passed another randstate object, a copy of that
441object is made.
442
443'lc_2exp_size' can fail if the requested size is bigger than the internal
444table provides for, in which case undef is returned.  The maximum size
445currently supported is 128.  The other forms always succeed.
446
447A randstate can be seeded with an integer or mpz, using the C<seed> method.
448/dev/random might be a good source of randomness, or time() or
449Time::HiRes::time() might be adequate, depending on the application.
450
451    $r->seed(time()));
452
453Random numbers can be generated with the following functions,
454
455=over 4
456
457=item
458
459mpf_urandomb, mpz_rrandomb, mpz_urandomb, mpz_urandomm,
460gmp_urandomb_ui, gmp_urandomm_ui
461
462=back
463
464Each constructs a new mpz or mpf and with a distribution per the
465corresponding GMP function.  For example,
466
467    use GMP::Rand (:all);
468    $r = randstate();
469    $a = mpz_urandomb($r,256);         # uniform mpz, 256 bits
470    $b = mpz_urandomm($r,mpz(3)**100); # uniform mpz, 0 to 3**100-1
471    $c = mpz_rrandomb($r,1024);        # special mpz, 1024 bits
472    $f = mpf_urandomb($r,128);         # uniform mpf, 128 bits, 0<=$f<1
473    $f = gmp_urandomm_ui($r,56);       # uniform int, 0 to 55
474
475=head2 Coercion
476
477Arguments to operators and functions are converted as necessary to the
478appropriate type.  For instance C<**> requires an unsigned integer exponent,
479and an mpq argument will be converted, so long as it's an integer in the
480appropriate range.
481
482    use GMP::Mpz (mpz);
483    use GMP::Mpq (mpq);
484    $p = mpz(3) ** mpq(45);   # allowed, 45 is an integer
485
486It's an error if a conversion to an integer or mpz would cause any
487truncation.  For example,
488
489    use GMP::Mpz (mpz);
490    $p = mpz(3) + 1.25;       # not allowed
491    $p = mpz(3) + mpz(1.25);  # allowed, explicit truncation
492
493Comparisons, however, accept any combination of operands and are always done
494exactly.  For example,
495
496    use GMP::Mpz (mpz);
497    print mpz(3) < 3.1;       # true
498
499Variables used on the left of an assignment operator like C<+=> are subject
500to coercion too.  An integer, float or string will change type when an mpz,
501mpq or mpf is applied to it.  For example,
502
503    use GMP::Mpz (mpz);
504    $a = 1;
505    $a += mpz(1234);   # $a becomes an mpz
506
507=head2 Overloading
508
509The rule for binary operators in the C<overload> mechanism is that if both
510operands are class objects then the method from the first is used.  This
511determines the result type when mixing GMP classes.  For example,
512
513    use GMP::Mpz (mpz);
514    use GMP::Mpq (mpq);
515    use GMP::Mpf (mpf);
516    $z = mpz(123);
517    $q = mpq(3,2);
518    $f = mpf(1.375)
519    print $q+$f;     # gives an mpq
520    print $f+$z;     # gives an mpf
521    print $z+$f;     # not allowed, would lose precision
522
523=head2 Constants
524
525A special tag C<:constants> is recognised in the module exports list.  It
526doesn't select any functions, but indicates that perl constants should be
527GMP objects.  This can only be used on one of GMP::Mpz, GMP::Mpq or GMP::Mpf
528at any one time, since they apply different rules.
529
530GMP::Mpz will treat constants as mpz's if they're integers, or ordinary
531floats if not.  For example,
532
533    use GMP::Mpz qw(:constants);
534    print 764861287634126387126378128,"\n";   # an mpz
535    print 1.25,"\n";                          # a float
536
537GMP::Mpq is similar, treating integers as mpq's and leaving floats to the
538normal perl handling.  Something like 3/4 is read as two integer mpq's and a
539division, but that's fine since it gives the intended fraction.
540
541    use GMP::Mpq qw(:constants);
542    print 3/4,"\n";    # an mpq
543    print 1.25,"\n";   # a float
544
545GMP::Mpf will treat all constants as mpf's using the default precision.
546BEGIN blocks can be used to set that precision while the code is parsed.
547For example,
548
549    use GMP::Mpf qw(:constants);
550    BEGIN { GMP::Mpf::set_default_prec(256); }
551    print 1/3;
552    BEGIN { GMP::Mpf::set_default_prec(64); }
553    print 5/7;
554
555A similar special tag :noconstants is recognised to turn off the constants
556feature.  For example,
557
558    use GMP::Mpz qw(:constants);
559    print 438249738748174928193,"\n";   # an mpz
560    use GMP::Mpz qw(:noconstants);
561    print 438249738748174928193,"\n";   # now a float
562
563All three 'integer', 'binary' and 'float' constant methods are captured.
564'float' is captured even for GMP::Mpz and GMP::Mpq since perl by default
565treats integer strings as floats if they don't fit a plain integer.
566
567=head1 SEE ALSO
568
569GMP manual, L<perl>, L<overload>.
570
571=head1 BUGS
572
573In perl 5.005_03 on i386 FreeBSD, the overloaded constants sometimes provoke
574seg faults.  Don't know if that's a perl bug or a GMP module bug, though it
575does seem to go bad before reaching anything in GMP.xs.
576
577There's no way to specify an arbitrary base when converting a string to an
578mpz (or mpq or mpf), only hex or octal with 0x or 0 (for mpz and mpq, but
579not for mpf).
580
581These modules are not reentrant or thread safe, due to the implementation of
582the XSUBs.
583
584Returning a new object from the various functions is convenient, but
585assignment versions could avoid creating new objects.  Perhaps they could be
586named after the C language functions, eg. mpq_inv($q,$q);
587
588It'd be good if C<num> and C<den> gave lvalues so the underlying mpq could
589be manipulated.
590
591C<printf> could usefully accept %b for mpz, mpq and mpf, and perhaps %x for
592mpf too.
593
594C<get_str> returning different style values for integer versus float is a
595bit unfortunate.  With mpz, mpq and mpf objects there's no doubt what it
596will do, but on a plain scalar its action depends on whether the scalar was
597promoted to a float at any stage, and then on the GMP module rules about
598using the integer or float part.
599
600=head1 INTERNALS
601
602In usual perl object style, an mpz is a reference to an object blessed into
603class C<GMP::Mpz>.  The object holds a pointer to the C language C<mpz_t>
604structure.  Similarly for mpq, mpf and randstate.
605
606A free list of mpz and mpq values is kept to avoid repeated initializing and
607clearing when objects are created and destroyed.  This aims to help speed,
608but it's not clear whether it's really needed.
609
610mpf doesn't use a free list because the precision of new objects can be
611different each time.
612
613No interface to C<mpf_set_prec_raw> is provided.  It wouldn't be very useful
614since there's no way to make an operation store its result in a particular
615object.  The plain C<set_prec> is useful though, for truncating to a lower
616precision, or as a sort of directive that subsequent calculations involving
617that variable should use a higher precision.
618
619The overheads of perl dynamic typing (operator dispatch, operand type
620checking or coercion) will mean this interface is slower than using C
621directly.
622
623Some assertion checking is available as a compile-time option.
624
625=head1 COPYRIGHT
626
627Copyright 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
628
629This file is part of the GNU MP Library.
630
631The GNU MP Library is free software; you can redistribute it and/or modify
632it under the terms of the GNU Lesser General Public License as published
633by the Free Software Foundation; either version 3 of the License, or (at
634your option) any later version.
635
636The GNU MP Library is distributed in the hope that it will be useful, but
637WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
638or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
639License for more details.
640
641You should have received a copy of the GNU Lesser General Public License
642along with the GNU MP Library.  If not, see http://www.gnu.org/licenses/.
643
644=cut
645
646# Local variables:
647# perl-indent-level: 2
648# fill-column: 76
649# End:
650