3 # Copyright 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
5 # This file is part of the GNU MP Library.
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.
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.
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/.
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.]
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.
33 @ISA = qw(Exporter DynaLoader);
36 @EXPORT_OK = qw(version);
37 %EXPORT_TAGS = ('all' => [qw(
38 get_d get_d_2exp get_si get_str integer_p
41 Exporter::export_ok_tags('all');
44 bootstrap GMP $VERSION;
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.
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
59 my ($pre, $dummy, $pat, $rest);
61 while (($pre, $dummy, $pat, $rest) = ($fmt =~ /^((%%|[^%])*)(%[- +#.*hlLqv\d]*[bcdfeEgGinopsuxX])(.*)$/s)) {
65 my $pat2 = $pat; # $pat with "*"s expanded
66 my @params = (); # arguments per "*"s
67 while ($pat2 =~ /[*]/) {
73 if (UNIVERSAL::isa($_[0],"GMP::Mpz")) {
74 if ($pat2 !~ /[dioxX]$/) {
75 die "GMP::sprintf: unsupported output format for mpz: $pat2\n";
78 $out .= sprintf_internal ($pat2, shift);
80 } elsif (UNIVERSAL::isa($_[0],"GMP::Mpq")) {
81 if ($pat2 !~ /[dioxX]$/) {
82 die "GMP::sprintf: unsupported output format for mpq: $pat2\n";
85 $out .= sprintf_internal ($pat2, shift);
87 } elsif (UNIVERSAL::isa($_[0],"GMP::Mpf")) {
88 if ($pat2 !~ /[eEfgG]$/) {
89 die "GMP::sprintf: unsupported output format for mpf: $pat2\n";
92 $out .= sprintf_internal ($pat2, shift);
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];
101 $out .= sprintf $pat, @params, shift;
111 if (ref($_[0]) eq 'GLOB') {
112 my $h = Symbol::qualify_to_ref(shift, caller);
113 print $h GMP::sprintf(@_);
115 print STDOUT GMP::sprintf(@_);
126 GMP - Perl interface to the GNU Multiple Precision Arithmetic Library
138 This module provides access to GNU MP arbitrary precision integers,
139 rationals and floating point.
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.
144 use GMP::Mpz qw(gcd, lcm); # just these functions
145 use GMP::Mpq qw(:all); # everything in mpq
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.
154 use GMP::Mpz qw(:all);
156 my $b = mpz("0xFFFF");
157 my $c = mpz(1.5); # truncated
159 The following overloaded operators are available, and corresponding
160 assignment forms like C<+=>,
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
171 C</> and C<%> round towards zero (as per the C<tdiv> functions in GMP).
173 The following functions are available, behaving the same as the
174 corresponding GMP mpz functions,
180 bin, cdiv, cdiv_2exp, clrbit, combit, congruent_p, congruent_2exp_p,
181 divexact, divisible_p, divisible_2exp_p, even_p, fac, fdiv, fdiv_2exp, fib,
182 fib2, gcd, gcdext, hamdist, invert, jacobi, kronecker, lcm, lucnum, lucnum2,
183 mod, mpz_export, mpz_import, nextprime, odd_p, perfect_power_p,
184 perfect_square_p, popcount, powm, probab_prime_p, realloc, remove, root,
185 roote, scan0, scan1, setbit, sizeinbase, sqrtrem, tdiv, tdiv_2exp, tstbit
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
194 use GMP::Mpz qw(:all);
197 ($g, $x, $y) = gcdext ($a, $b);
198 print "gcd($a,$b) is $g, and $g == $a*$x + $b*$y\n";
200 C<mpz_import> and C<mpz_export> are so named to avoid the C<import> keyword.
201 Their parameters are as follows,
203 $z = mpz_import ($order, $size, $endian, $nails, $string);
204 $string = mpz_export ($order, $size, $endian, $nails, $z);
206 The order, size, endian and nails parameters are as per the corresponding C
207 functions. The string input for C<mpz_import> is interpreted as byte data
208 and must be a multiple of $size bytes. C<mpz_export> conversely returns a
209 string of byte data, which will be a multiple of $size bytes.
211 C<invert> returns the inverse, or undef if it doesn't exist. C<remove>
212 returns a remainder/multiplicity pair. C<root> returns the nth root, and
213 C<roote> returns a root/bool pair, the bool indicating whether the root is
214 exact. C<sqrtrem> and C<rootrem> return a root/remainder pair.
216 C<clrbit>, C<combit> and C<setbit> expect a variable which they can modify,
217 it doesn't make sense to pass a literal constant. Only the given variable
218 is modified, if other variables are referencing the same mpz object then a
219 new copy is made of it. If the variable isn't an mpz it will be coerced to
222 use GMP::Mpz qw(setbit);
223 setbit (123, 0); # wrong, don't pass a constant
226 setbit ($a, 0); # $a becomes 7, $b stays at 6
228 C<scan0> and C<scan1> return ~0 if no 0 or 1 bit respectively is found.
232 This class provides rationals with arbitrary precision numerators and
233 denominators. A new mpq can be constructed with C<mpq>. The initial value
234 can be an integer, float, string, mpz, mpq or mpf, or a pair of integers or
235 mpz's. No precision is lost when converting a float or mpf, the exact value
238 use GMP::Mpq qw(:all);
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
246 When a fraction is given, it should be in the canonical form specified in
247 the GMP manual, which is denominator positive, no common factors, and zero
248 always represented as 0/1. If not then C<canonicalize> can be called to put
249 it in that form. For example,
251 use GMP::Mpq qw(:all);
252 $q = mpq(21,15); # eek! common factor 3
253 canonicalize($q); # get rid of it
255 The following overloaded operators are available, and corresponding
256 assignment forms like C<+=>,
262 + - * / E<lt>E<lt> E<gt>E<gt> ** ! E<lt> E<lt>= == != E<gt> E<gt>=
267 The following functions are available,
277 C<inv> calculates 1/q, as per the corresponding GMP function. C<num> and
278 C<den> return an mpz copy of the numerator or denominator respectively. In
279 the future C<num> and C<den> might give lvalues so the original mpq can be
280 modified through them, but this is not done currently.
284 This class provides arbitrary precision floating point numbers. The
285 mantissa is an arbitrary user-selected precision and the exponent is a fixed
286 size (one machine word).
288 A new mpf can be constructed with C<mpf>. The initial value can be an
289 integer, float, string, mpz, mpq or mpf. The second argument specifies the
290 desired precision in bits, or if omitted then the default precision is used.
292 use GMP::Mpf qw(:all);
294 $b = mpf(-7.5); # default precision
295 $c = mpf(1.5, 500); # 500 bits precision
296 $d = mpf("1.0000000000000001");
298 The following overloaded operators are available, with the corresponding
299 assignment forms like C<+=>,
305 + - * / E<lt>E<lt> E<gt>E<gt> ** ! E<lt> E<lt>= == != E<gt> E<gt>=
306 E<lt>=E<gt> abs not sqrt
310 The following functions are available, behaving the same as the
311 corresponding GMP mpf functions,
317 ceil, floor, get_default_prec, get_prec, mpf_eq, set_default_prec, set_prec,
322 C<mpf_eq> is so named to avoid clashing with the perl C<eq> operator.
324 C<set_prec> expects a variable which it can modify, it doesn't make sense to
325 pass a literal constant. Only the given variable is modified, if other
326 variables are referencing the same mpf object then a new copy is made of it.
327 If the variable isn't an mpf it will be coerced to one.
329 Results are the same precision as inputs, or if two mpf's are given to a
330 binary operator then the precision of the first is used. For example,
332 use GMP::Mpf qw(mpf);
335 $c = $a + $b; # gives 100 bits precision
337 Mpf to string conversion via "" or the usual string contexts uses C<$#> the
338 same as normal float to string conversions, or defaults to C<%.g> if C<$#>
339 is not defined. C<%.g> means all significant digits in the selected
344 The following functions are available in the GMP class,
350 fits_slong_p, get_d, get_d_2exp, get_si, get_str, integer_p, printf, sgn,
355 C<get_d_2exp> accepts any integer, string, float, mpz, mpq or mpf operands
356 and returns a float and an integer exponent,
358 ($dbl, $exp) = get_d_2exp (mpf ("3.0"));
359 # dbl is 0.75, exp is 2
361 C<get_str> takes an optional second argument which is the base, defaulting
362 to decimal. A negative base means upper case, as per the C functions. For
363 integer, integer string, mpz or mpq operands a string is returned.
366 use GMP::Mpq qw(:all);
367 print get_str(mpq(-5,8)),"\n"; # -5/8
368 print get_str(255,16),"\n"; # ff
370 For float, float strings or mpf operands, C<get_str> accepts an optional
371 third parameter being how many digits to produce, defaulting to 0 which
372 means all digits. (Only as many digits as can be accurately represented by
373 the float precision are ever produced though.) A string/exponent pair is
374 returned, as per the C mpf_get_str function. For example,
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
385 C<printf> and C<sprintf> allow formatted output of GMP types. mpz and mpq
386 values can be used with integer conversions (d, o, x, X) and mpf with float
387 conversions (f, e, E, g, G). All the standard perl printf features are
388 available too. For example,
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);
395 In perl 5.6.1 it doesn't seem to work to export C<printf>, the plain builtin
396 C<printf> is reached unless calls are C<&printf()> style. Explicit use of
397 C<GMP::printf> is suggested. C<sprintf> doesn't suffer this problem.
400 use GMP::Mpq qw(mpq);
401 $s = sprintf "%x", mpq(15,16);
403 C<version> is not exported by default or by tag :all, calling it as
404 C<GMP::version()> is recommended. It returns the GMP library version
405 string, which is not to be confused with the module version number.
407 The other GMP module functions behave as per the corresponding GMP routines,
408 and accept any integer, string, float, mpz, mpq or mpf. For example,
411 use GMP::Mpz qw(mpz);
413 print sgn($z); # gives 1
415 Because each of GMP::Mpz, GMP::Mpq and GMP::Mpf is a sub-class of GMP,
416 C<-E<gt>> style calls work too.
419 use GMP::Mpq qw(mpf);
421 if ($q->integer_p()) # false
426 This class provides objects holding an algorithm and state for random number
427 generation. C<randstate> creates a new object, for example,
429 use GMP::Rand qw(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);
436 With no parameters this corresponds to the C function
437 C<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'
439 corresponds to C<gmp_randinit_lc_2exp>, and 'mt' corresponds to
440 C<gmp_randinit_mt>. Or when passed another randstate object, a copy of that
443 'lc_2exp_size' can fail if the requested size is bigger than the internal
444 table provides for, in which case undef is returned. The maximum size
445 currently supported is 128. The other forms always succeed.
447 A 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
449 Time::HiRes::time() might be adequate, depending on the application.
453 Random numbers can be generated with the following functions,
459 mpf_urandomb, mpz_rrandomb, mpz_urandomb, mpz_urandomm,
460 gmp_urandomb_ui, gmp_urandomm_ui
464 Each constructs a new mpz or mpf and with a distribution per the
465 corresponding GMP function. For example,
467 use GMP::Rand (:all);
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
477 Arguments to operators and functions are converted as necessary to the
478 appropriate type. For instance C<**> requires an unsigned integer exponent,
479 and an mpq argument will be converted, so long as it's an integer in the
484 $p = mpz(3) ** mpq(45); # allowed, 45 is an integer
486 It's an error if a conversion to an integer or mpz would cause any
487 truncation. For example,
490 $p = mpz(3) + 1.25; # not allowed
491 $p = mpz(3) + mpz(1.25); # allowed, explicit truncation
493 Comparisons, however, accept any combination of operands and are always done
494 exactly. For example,
497 print mpz(3) < 3.1; # true
499 Variables used on the left of an assignment operator like C<+=> are subject
500 to coercion too. An integer, float or string will change type when an mpz,
501 mpq or mpf is applied to it. For example,
505 $a += mpz(1234); # $a becomes an mpz
509 The rule for binary operators in the C<overload> mechanism is that if both
510 operands are class objects then the method from the first is used. This
511 determines the result type when mixing GMP classes. For example,
519 print $q+$f; # gives an mpq
520 print $f+$z; # gives an mpf
521 print $z+$f; # not allowed, would lose precision
525 A special tag C<:constants> is recognised in the module exports list. It
526 doesn't select any functions, but indicates that perl constants should be
527 GMP objects. This can only be used on one of GMP::Mpz, GMP::Mpq or GMP::Mpf
528 at any one time, since they apply different rules.
530 GMP::Mpz will treat constants as mpz's if they're integers, or ordinary
531 floats if not. For example,
533 use GMP::Mpz qw(:constants);
534 print 764861287634126387126378128,"\n"; # an mpz
535 print 1.25,"\n"; # a float
537 GMP::Mpq is similar, treating integers as mpq's and leaving floats to the
538 normal perl handling. Something like 3/4 is read as two integer mpq's and a
539 division, but that's fine since it gives the intended fraction.
541 use GMP::Mpq qw(:constants);
542 print 3/4,"\n"; # an mpq
543 print 1.25,"\n"; # a float
545 GMP::Mpf will treat all constants as mpf's using the default precision.
546 BEGIN blocks can be used to set that precision while the code is parsed.
549 use GMP::Mpf qw(:constants);
550 BEGIN { GMP::Mpf::set_default_prec(256); }
552 BEGIN { GMP::Mpf::set_default_prec(64); }
555 A similar special tag :noconstants is recognised to turn off the constants
556 feature. For example,
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
563 All three 'integer', 'binary' and 'float' constant methods are captured.
564 'float' is captured even for GMP::Mpz and GMP::Mpq since perl by default
565 treats integer strings as floats if they don't fit a plain integer.
569 GMP manual, L<perl>, L<overload>.
573 In perl 5.005_03 on i386 FreeBSD, the overloaded constants sometimes provoke
574 seg faults. Don't know if that's a perl bug or a GMP module bug, though it
575 does seem to go bad before reaching anything in GMP.xs.
577 There's no way to specify an arbitrary base when converting a string to an
578 mpz (or mpq or mpf), only hex or octal with 0x or 0 (for mpz and mpq, but
581 These modules are not reentrant or thread safe, due to the implementation of
584 Returning a new object from the various functions is convenient, but
585 assignment versions could avoid creating new objects. Perhaps they could be
586 named after the C language functions, eg. mpq_inv($q,$q);
588 It'd be good if C<num> and C<den> gave lvalues so the underlying mpq could
591 C<printf> could usefully accept %b for mpz, mpq and mpf, and perhaps %x for
594 C<get_str> returning different style values for integer versus float is a
595 bit unfortunate. With mpz, mpq and mpf objects there's no doubt what it
596 will do, but on a plain scalar its action depends on whether the scalar was
597 promoted to a float at any stage, and then on the GMP module rules about
598 using the integer or float part.
602 In usual perl object style, an mpz is a reference to an object blessed into
603 class C<GMP::Mpz>. The object holds a pointer to the C language C<mpz_t>
604 structure. Similarly for mpq, mpf and randstate.
606 A free list of mpz and mpq values is kept to avoid repeated initializing and
607 clearing when objects are created and destroyed. This aims to help speed,
608 but it's not clear whether it's really needed.
610 mpf doesn't use a free list because the precision of new objects can be
613 No interface to C<mpf_set_prec_raw> is provided. It wouldn't be very useful
614 since there's no way to make an operation store its result in a particular
615 object. The plain C<set_prec> is useful though, for truncating to a lower
616 precision, or as a sort of directive that subsequent calculations involving
617 that variable should use a higher precision.
619 The overheads of perl dynamic typing (operator dispatch, operand type
620 checking or coercion) will mean this interface is slower than using C
623 Some assertion checking is available as a compile-time option.
627 Copyright 2001, 2002, 2003, 2004 Free Software Foundation, Inc.
629 This file is part of the GNU MP Library.
631 The GNU MP Library is free software; you can redistribute it and/or modify
632 it under the terms of the GNU Lesser General Public License as published
633 by the Free Software Foundation; either version 3 of the License, or (at
634 your option) any later version.
636 The GNU MP Library is distributed in the hope that it will be useful, but
637 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
638 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
639 License for more details.
641 You should have received a copy of the GNU Lesser General Public License
642 along with the GNU MP Library. If not, see http://www.gnu.org/licenses/.
647 # perl-indent-level: 2