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