📄 gmp.pm
字号:
C<mpf_eq> is so named to avoid clashing with the perl C<eq> operator.C<set_prec> expects a variable which it can modify, it doesn't make sense topass a literal constant. Only the given variable is modified, if othervariables are referencing the same mpf object then a new copy is made of it.If the variable isn't an mpf it will be coerced to one.Results are the same precision as inputs, or if two mpf's are given to abinary operator then the precision of the first is used. For example, use GMP::Mpf qw(mpf); $a = mpf(2.0, 100); $b = mpf(2.0, 500); $c = $a + $b; # gives 100 bits precisionMpf to string conversion via "" or the usual string contexts uses C<$#> thesame as normal float to string conversions, or defaults to C<%.g> if C<$#>is not defined. C<%.g> means all significant digits in the selectedprecision.=head2 GMP classThe following functions are available in the GMP class,=over 4=itemfits_slong_p, get_d, get_d_2exp, get_si, get_str, integer_p, printf, sgn,sprintf, version=backC<get_d_2exp> accepts any integer, string, float, mpz, mpq or mpf operandsand returns a float and an integer exponent, ($dbl, $exp) = get_d_2exp (mpf ("3.0")); # dbl is 0.75, exp is 2C<get_str> takes an optional second argument which is the base, defaultingto decimal. A negative base means upper case, as per the C functions. Forinteger, integer string, mpz or mpq operands a string is returned. use GMP qw(:all); use GMP::Mpq qw(:all); print get_str(mpq(-5,8)),"\n"; # -5/8 print get_str(255,16),"\n"; # ffFor float, float strings or mpf operands, C<get_str> accepts an optionalthird parameter being how many digits to produce, defaulting to 0 whichmeans all digits. (Only as many digits as can be accurately represented bythe float precision are ever produced though.) A string/exponent pair isreturned, as per the C mpf_get_str function. For example, use GMP qw(:all); use GMP::Mpf qw(:all); ($s, $e) = get_str(111.111111111, 10, 4); printf ".$se$e\n"; # .1111e3 ($s, $e) = get_str(1.625, 10); print "0.$s*10^$e\n"; # 0.1625*10^1 ($s, $e) = get_str(mpf(2)**20, 16); printf ".%s@%x\n", $s, $e; # .1@14C<printf> and C<sprintf> allow formatted output of GMP types. mpz and mpqvalues can be used with integer conversions (d, o, x, X) and mpf with floatconversions (f, e, E, g, G). All the standard perl printf features areavailable too. For example, use GMP::Mpz qw(mpz); use GMP::Mpf qw(mpf); GMP::printf ("%d %d %s", 123, mpz(2)**128, 'foo'); GMP::printf STDERR "%.40f", mpf(1.234);In perl 5.6.1 it doesn't seem to work to export C<printf>, the plain builtinC<printf> is reached unless calls are C<&printf()> style. Explicit use ofC<GMP::printf> is suggested. C<sprintf> doesn't suffer this problem. use GMP qw(sprintf); use GMP::Mpq qw(mpq); $s = sprintf "%x", mpq(15,16);C<version> is not exported by default or by tag :all, calling it asC<GMP::version()> is recommended. It returns the GMP library versionstring, which is not to be confused with the module version number.The other GMP module functions behave as per the corresponding GMP routines,and accept any integer, string, float, mpz, mpq or mpf. For example, use GMP qw(:all); use GMP::Mpz qw(mpz); $z = mpz(123); print sgn($z); # gives 1Because each of GMP::Mpz, GMP::Mpq and GMP::Mpf is a sub-class of GMP,C<-E<gt>> style calls work too. use GMP qw(:all); use GMP::Mpq qw(mpf); $q = mpq(-5,7); if ($q->integer_p()) # false ...=head2 GMP::RandThis class provides objects holding an algorithm and state for random numbergeneration. C<randstate> creates a new object, for example, use GMP::Rand qw(randstate); $r = randstate(); $r = randstate('lc_2exp_size', 64); $r = randstate('lc_2exp', 43840821, 1, 32);With no parameters this corresponds to the C functionC<gmp_randinit_default>, and is a compromise between speed and randomness.'lc_2exp_size' corresponds to C<gmp_randinit_lc_2exp_size>, and 'lc_2exp'corresponds to C<gmp_randinit_lc_2exp>.'lc_2exp_size' can fail if the requested size is bigger than the internaltable provides for, in which case undef is returned. The maximum sizecurrently supported is 128. The other forms always succeed.A randstate can be seeded with an integer or mpz, using the C<seed> method./dev/random might be a good source of randomness, or time() orTime::HiRes::time() might be adequate, depending on the application. $r->seed(time()));Random numbers can be generated with the following functions,=over 4=itemmpf_urandomb, mpz_rrandomb, mpz_urandomb, mpz_urandomm=backEach constructs a new mpz or mpf and with a distribution per thecorresponding GMP function. For example, use GMP::Rand (:all); $r = randstate(); $a = mpz_urandomb($r,256); # uniform mpz, 256 bits $b = mpz_urandomm($r,mpz(3)**100); # uniform mpz, 0 to 3**100-1 $c = mpz_rrandomb($r,1024); # special mpz, 1024 bits $f = mpf_urandomb($r,128); # uniform mpf, 128 bits, 0<=$f<1=head2 CoercionArguments to operators and functions are converted as necessary to theappropriate type. For instance C<**> requires an unsigned integer exponent,and an mpq argument will be converted, so long as it's an integer in theapropriate range. use GMP::Mpz (mpz); use GMP::Mpq (mpq); $p = mpz(3) ** mpq(45); # allowed, 45 is an integerIt's an error if a conversion to an integer or mpz would cause anytruncation. For example, use GMP::Mpz (mpz); $p = mpz(3) + 1.25; # not allowed $p = mpz(3) + mpz(1.25); # allowed, explicit truncationComparisons, however, accept any combination of operands and are always doneexactly. For example, use GMP::Mpz (mpz); print mpz(3) < 3.1; # trueVariables used on the left of an assignment operator like C<+=> are subjectto coercion too. An integer, float or string will change type when an mpz,mpq or mpf is applied to it. For example, use GMP::Mpz (mpz); $a = 1; $a += mpz(1234); # $a becomes an mpz=head2 OverloadingThe rule for binary operators in the C<overload> mechanism is that if bothoperands are class objects then the method from the first is used. Thisdetermines the result type when mixing GMP classes. For example, use GMP::Mpz (mpz); use GMP::Mpq (mpq); use GMP::Mpf (mpf); $z = mpz(123); $q = mpq(3,2); $f = mpf(1.375) print $q+$f; # gives an mpq print $f+$z; # gives an mpf print $z+$f; # not allowed, would lose precision=head2 ConstantsA special tag C<:constants> is recognised in the module exports list. Itdoesn't select any functions, but indicates that perl constants should beGMP objects. This can only be used on one of GMP::Mpz, GMP::Mpq or GMP::Mpfat any one time, since they apply different rules.GMP::Mpz will treat constants as mpz's if they're integers, or ordinaryfloats if not. For example, use GMP::Mpz qw(:constants); print 764861287634126387126378128,"\n"; # an mpz print 1.25,"\n"; # a floatGMP::Mpq is similar, treating integers as mpq's and leaving floats to thenormal perl handling. Something like 3/4 is read as two integer mpq's and adivision, but that's fine since it gives the intended fraction. use GMP::Mpq qw(:constants); print 3/4,"\n"; # an mpq print 1.25,"\n"; # a floatGMP::Mpf will treat all constants as mpf's using the default precision.BEGIN blocks can be used to set that precision while the code is parsed.For example, use GMP::Mpf qw(:constants); BEGIN { GMP::Mpf::set_default_prec(256); } print 1/3; BEGIN { GMP::Mpf::set_default_prec(64); } print 5/7;A similar special tag :noconstants is recognised to turn off the constantsfeature. For example, use GMP::Mpz qw(:constants); print 438249738748174928193,"\n"; # an mpz use GMP::Mpz qw(:noconstants); print 438249738748174928193,"\n"; # now a floatAll three 'integer', 'binary' and 'float' constant methods are captured.'float' is captured even for GMP::Mpz and GMP::Mpq since perl by defaulttreats integer strings as floats if they don't fit a plain integer.=head1 SEE ALSOGMP manual, L<perl>, L<overload>.=head1 BUGSIn perl 5.005_03 on i386 FreeBSD, the overloaded constants sometimes provokeseg faults. Don't know if that's a perl bug or a GMP module bug, though itdoes seem to go bad before reaching anything in GMP.xs.There's no way to specify an arbitrary base when converting a string to anmpz (or mpq or mpf), only hex or octal with 0x or 0 (for mpz and mpq, butnot for mpf).These modules are not reentrant or thread safe, due to the implementation ofthe XSUBs.Returning a new object from the various functions is convenient, butassignment versions could avoid creating new objects. Perhaps they could benamed after the C language functions, eg. mpq_inv($q,$q);It'd be good if C<num> and C<den> gave lvalues so the underlying mpq couldbe manipulated.C<printf> could usefully accept %b for mpz, mpq and mpf, and perhaps %x formpf too.C<get_str> returning different style values for integer versus float is abit unfortunate. With mpz, mpq and mpf objects there's no doubt what itwill do, but on a plain scalar its action depends on whether the scalar waspromoted to a float at any stage, and then on the GMP module rules aboutusing the integer or float part.=head1 INTERNALSIn usual perl object style, an mpz is a reference to an object blessed intoclass C<GMP::Mpz>. The object holds a pointer to the C language C<mpz_t>structure. Similarly for mpq, mpf and randstate.A free list of mpz and mpq values is kept to avoid repeated initializing andclearing when objects are created and destroyed. This aims to help speed,but it's not clear whether it's really needed.mpf doesn't use a free list because the precision of new objects can bedifferent each time.No interface to C<mpf_set_prec_raw> is provided. It wouldn't be very usefulsince there's no way to make an operation store its result in a particularobject. The plain C<set_prec> is useful though, for truncating to a lowerprecision, or as a sort of directive that subsequent calculations involvingthat variable should use a higher precision.The overheads of perl dynamic typing (operator dispatch, operand typechecking or coercion) will mean this interface is slower than using Cdirectly.Some assertion checking is available as a compile-time option.=head1 COPYRIGHTCopyright 2001, 2002, 2003, 2004 Free Software Foundation, Inc.This file is part of the GNU MP Library.The GNU MP Library is free software; you can redistribute it and/or modifyit under the terms of the GNU Lesser General Public License as publishedby the Free Software Foundation; either version 2.1 of the License, or (atyour option) any later version.The GNU MP Library is distributed in the hope that it will be useful, butWITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITYor FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General PublicLicense for more details.You should have received a copy of the GNU Lesser General Public Licensealong with the GNU MP Library; see the file COPYING.LIB. If not, write tothe Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,MA 02111-1307, USA.=cut# Local variables:# perl-indent-level: 2# fill-column: 76# End:
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -