home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / Pari.pm < prev    next >
Encoding:
Perl POD Document  |  2003-04-25  |  34.0 KB  |  1,179 lines

  1. =head1 NAME
  2.  
  3. C<Math::Pari> - Perl interface to PARI.
  4.  
  5. =head1 SYNOPSIS
  6.  
  7.   use Math::Pari;
  8.   $a = PARI 2;
  9.   print $a**10000;
  10.  
  11. or
  12.  
  13.   use Math::Pari qw(Mod);
  14.   $a = Mod(3,5);
  15.   print $a**10000;
  16.  
  17. =head1 DESCRIPTION
  18.  
  19. This package is a Perl interface to famous library PARI for
  20. numerical/scientific/number-theoretic calculations.  It allows use of
  21. most PARI functions as Perl functions, and (almost) seamless merging
  22. of PARI and Perl data. In what follows we suppose prior knowledge of
  23. what PARI is (see L<ftp://megrez.math.u-bordeaux.fr/pub/pari>, or
  24. L<Math::libPARI>).
  25.  
  26. =head1 EXPORTed functions
  27.  
  28. =over 4
  29.  
  30. =item DEFAULT
  31.  
  32. By default the package exports functions PARI(), PARIcol(), PARIvar(),
  33. PARImat() and PARImat_tr() which convert their argument(s) to a
  34. PARI object. (In fact PARI() is just an alias for C<new Math::Pari>).
  35. The function PARI() accepts following data as its arguments
  36.  
  37. =over 17
  38.  
  39. =item One integer
  40.  
  41. Is converted to a PARI integer.
  42.  
  43. =item One float
  44.  
  45. Is converted to a PARI float.
  46.  
  47. =item One string
  48.  
  49. Is executed as a PARI expresion (so should not contain whitespace).
  50.  
  51. =item PARI object
  52.  
  53. Is passed unchanged.
  54.  
  55. =item Reference to a Perl array
  56.  
  57. Each element is converted using the same rules, PARI vector-row with these
  58. elements is returned.
  59.  
  60. =item Several of above
  61.  
  62. The same as with a reference to array.
  63.  
  64. =back
  65.  
  66. =item Conflicts of rules in PARI()
  67.  
  68. In deciding what rule of the above to apply the preference is given to
  69. the uppermost choice of those available I<now>.  If none matches, then
  70. the string rule is used.  So C<PARI(1)> returns integer, C<PARI(1.)>
  71. returns float, C<PARI("1")> evaluates C<1> as a PARI expression (well,
  72. the result is the same as C<PARI(1)>, only slower).
  73.  
  74. Note that for Perl these data are synonimous, since Perl freely
  75. converts between integers, float and strings.  However, to PARI() only
  76. what the argument I<is now> is important.  If $v is C<1> in the Perl
  77. world, C<PARI($v)> may convert it to an integer, float, or to the
  78. result of evaluating the PARI program C<1> (all depending on how $v
  79. was created and accessed in Perl).
  80.  
  81. This is a fundamental limitation of creating an interface between two
  82. systems, both with polymorphic objects, but with subtly different
  83. semantic of the flavors of these objects.  In reality, however, this
  84. is rarely a problem.
  85.  
  86. =item PARIcol(), PARImat() and PARImat_tr()
  87.  
  88. PARIcol() behaves in the same way as PARI() unless given several
  89. arguments. In the latter case it returns a vector-column instead of
  90. a vector-row.
  91.  
  92. PARImat() constructs a matrix out of the given arguments. It will work
  93. if PARI() will construct a vector of vectors given the same arguments.
  94. The internal vectors become columns of the matrix.  PARImat_tr()
  95. behaves similarly, but the internal vectors become rows of the matrix.
  96.  
  97. Since PARI matrices are similar to vector-rows of vector-columns,
  98. PARImat() is quickier, but PARImat_tr() better corresponds to the PARI
  99. input and output forms of matrices:
  100.  
  101.   print PARImat    [[1,2], [3,4]];    # prints [1,3;2,4]
  102.   print PARImat_tr [[1,2], [3,4]];    # prints [1,2;3,4]
  103.  
  104. =item C<use> with arguments
  105.  
  106. If arguments are specified in the C<use Math::Pari> directive, the
  107. PARI functions appearing as arguments are exported in the caller
  108. context. In this case the function PARI() and friends is not exported,
  109. so if you need them, you should include them into export list
  110. explicitely, or include C<:DEFAULT> tag:
  111.  
  112.   use Math::Pari qw(factorint PARI);
  113.   use Math::Pari qw(:DEFAULT factorint);
  114.  
  115. or simply do it in two steps
  116.  
  117.   use Math::Pari;
  118.   use Math::Pari 'factorint';
  119.  
  120. The other tags recognized are C<:PARI>, C<:all>, C<prec=NUMBER>,
  121. number tags (e.g., C<:4>), overloaded constants tags (C<:int>,
  122. C<:float>, C<:hex>) and section names tags.  The number tags export
  123. functions from the PARI library from the given class (except for
  124. C<:PARI>, which exports all of the classes).  Tag C<:all> exports all of the
  125. exportable symbols and C<:PARI>.
  126.  
  127. Giving C<?> command to C<gp> (B<PARI> calculator) lists the following classes:
  128.  
  129.   1: Standard monadic or dyadic OPERATORS
  130.   2: CONVERSIONS and similar elementary functions
  131.   3: TRANSCENDENTAL functions
  132.   4: NUMBER THEORETICAL functions
  133.   5: Functions related to ELLIPTIC CURVES
  134.   6: Functions related to general NUMBER FIELDS
  135.   7: POLYNOMIALS and power series
  136.   8: Vectors, matrices, LINEAR ALGEBRA and sets
  137.   9: SUMS, products, integrals and similar functions
  138.   10: GRAPHIC functions
  139.   11: PROGRAMMING under GP
  140.  
  141. One can use section names instead of number tags.  Recognized names are
  142.  
  143.   :standard :conversions :transcendental :number :elliptic
  144.   :fields :polynomials :vectors :sums :graphic :programming
  145.  
  146. One can get the list of all of the functions accessible by C<Math::Pari>,
  147. or the accessible functions from the given section using listPari() function.
  148.  
  149. Starting from version 5.005 of Perl, three constant-overload tags are
  150. supported: C<:int>, C<:float>, C<:hex>.  If used, all the
  151. integer/float/hex-or-octal-or-binary literals in Perl will be automatically
  152. converted to became PARI objects.  For example,
  153.  
  154.   use Math::Pari ':int';
  155.   print 2**1000;
  156.  
  157. is equivalent to
  158.  
  159.   print PARI(2)**PARI(1000);
  160.  
  161. (The support for this Perl feature is buggy before the Perl version 5.005_57 -
  162. unless Perl uses mymalloc options; you can check for this with C<perl
  163. -V:usemymalloc>.)
  164.  
  165. =back
  166.  
  167. =head1 Available functions
  168.  
  169. =head2 Directly accessible from Perl
  170.  
  171. This package supports I<all> the functions from the PARI library with
  172. a I<signature> which can be recognized by Math::Pari.  This means that
  173. when you update the PARI library, the newly added functions will we
  174. available without any change to this package; only a recompile is
  175. needed.  In fact no recompile will be needed if you link libPARI
  176. dynamically (you need to modify the F<Makefile> manually to do
  177. this).
  178.  
  179. You can "reach" unsupported functions via going directly to PARI
  180. parser using the string flavor of PARI() function, as in
  181.  
  182.   3 + PARI('O(x^17)');
  183.  
  184. For some "unreachable" functions there is a special wrapper functions,
  185. such as C<O(variable,power)>).
  186.  
  187. The following functions are specific to GP calculator, thus are not
  188. available to Math::Pari in any way:
  189.  
  190.   default error extern input print print1 printp printp1
  191.   printtex quit read system whatnow write write1 writetex
  192.  
  193. whatnow() function is useless, since Math::Pari does not support the
  194. "compatibility" mode (with older PARI library).  The functionality of
  195. print(), write() and variants is available via automatic string
  196. translation, and pari_print() function and its variants (see L<Printout functions>).
  197.  
  198. default() is the only important function with functionality not
  199. supported by the current interface.  Note however, that three most
  200. important default() actions are supported by allocatemem(),
  201. setprimelimit(), setprecision() and setseriesprecision() functions.
  202. (When called without arguments, these functions return the current
  203. values.)
  204.  
  205. allocatemem($bytes) should not be called from inside Math::Pari
  206. functions (such as forprimes()).
  207.  
  208. =head2 Arguments
  209.  
  210. Arguments to PARI functions are automatically converted to C<long> or
  211. a PARI object depending on the signature of the actual library function.
  212. The arguments are I<forced> into the given type, so even if C<gp>
  213. rejects your code similar to
  214.  
  215.   func(2.5);            # func() takes a long in C
  216.  
  217. arguing that a particular argument should be of C<type T_INT> (i.e., a
  218. Pari integer), the corresponding code will work in C<Math::Pari>,
  219. since 2.5 is silently converted to C<long>, per the function
  220. signature.
  221.  
  222. =head2 Return values
  223.  
  224. PARI functions return a PARI object or a Perl's integer depending on
  225. what the actual library function returns.
  226.  
  227. =head2 Additional functions
  228.  
  229. Some PARI functions are available in C<gp> (i.e., in C<PARI>
  230. calculator) via infix notation only. In C<Math::Pari> these functions
  231. are available in functional notations too.  Some other convenience
  232. functions are also made available.
  233.  
  234. =over 5
  235.  
  236. =item Infix, prefix and postfix operations
  237.  
  238. are available under names
  239.  
  240.   gneg, gadd, gsub, gmul, gdiv, gdivent, gmod, gpui,
  241.   gle, gge, glt, ggt, geq, gne, gegal, gor, gand,
  242.   gcmp, gcmp0, gcmp1, gcmp_1.
  243.  
  244. C<gdivent> means euclidean quotient, C<gpui> is power, C<gegal> checks
  245. whether two objects are equal, C<gcmp> is applicable to two real
  246. numbers only, C<gcmp0>, C<gcmp1>, C<gcmp_1> compare with 0, 1 and -1
  247. correspondingly (see PARI user manual for details, or
  248. L<Math::libPARI>).  Note that all these functions are more readily
  249. available via operator overloading, so instead of
  250.  
  251.   gadd(gneg($x), $y)
  252.  
  253. one can write
  254.  
  255.   -$x+$y
  256.  
  257. (as far as overloading may be triggered, see L<overload>, so we assume
  258. that at least one of $x or $y is a PARI object).
  259.  
  260. =item Conversion functions
  261.  
  262.   pari2iv, pari2nv, pari2num, pari2pv, pari2bool
  263.  
  264. convert a PARI object to an integer, float, integer/float (whatever is
  265. better), string, and a boolean value correspondingly. Most the time
  266. you do not need these functions due to automatic conversions.
  267.  
  268. =item Printout functions
  269.  
  270.   pari_print, pari_pprint, pari_texprint
  271.  
  272. perform the same conversions to strings as their PARI counterparts,
  273. but do not print the result.  The difference of pari_print() with
  274. pari2pv() is the number of significant digits they output, and
  275. whitespace in the output.  pari2pv(), which is intended for
  276. "computer-readable strings", outputs as many digits as is supported by
  277. the current precision of the number; while pari_print(), which targets
  278. human-readable strings, takes into account the currently specified
  279. output precision too.
  280.  
  281. =item Constant functions
  282.  
  283. Some mathematical constants appear as function without arguments in
  284. PARI.  These functions are available in Math::Pari too.  If you export
  285. them as in
  286.  
  287.   use Math::Pari qw(:DEFAULT Pi I Euler);
  288.  
  289. they can be used as barewords in your program:
  290.  
  291.   $x = Pi ** Euler;
  292.  
  293. =item Low-level functions
  294.  
  295. For convenience of low-level PARI programmers some low-level functions
  296. are made available as well (all except type_name() and changevalue()
  297. are not exportable):
  298.  
  299.   typ($x)
  300.   lg($x)
  301.   lgef($x)
  302.   lgefint($x)
  303.   longword($x, $n)
  304.   type_name($x)
  305.   changevalue($name,$newvalue)
  306.  
  307. Here longword($x,$n) returns C<$n>-th word in the memory
  308. representation of $x (including non-code words).  type_name() differs
  309. from the PARI function type(): type() returns a PARI object, while
  310. type_name() returns a Perl string.  (PARI objects of string type
  311. behave very non-intuitive w.r.t. string comparison functions; remember
  312. that they are compared using lex() to I<the results of evaluation> of
  313. other argument of comparison!)
  314.  
  315. The function listPari($number) outputs a list of names of PARI
  316. functions in the section $number.  Use listPari(-1) to get the list
  317. across all of the sections.
  318.  
  319. =item Uncompatible functions
  320.  
  321.   O
  322.  
  323. Since implementing C<O(7**6)> would be very tedious, we provide a
  324. two-argument form C<O(7,6)> instead (meaning the same as C<O(7^6)> in
  325. PARI).  Note that with polynomials there is no problem like this one,
  326. both C<O($x,6)> and C<O($x**6)> work.
  327.  
  328.   ifact(n)
  329.  
  330. integer factorial functions, available from C<gp> as C<n!>.
  331.  
  332. =back
  333.  
  334. =head2 Looping functions
  335.  
  336. PARI has a big collection of functions which loops over some set.
  337. Such a function takes two I<special> arguments: loop variable, and the
  338. code to execute in the loop.
  339.  
  340. The code can be either a string (which contains PARI code to execute -
  341. thus should not contain whitespace), or a Perl code reference.  The
  342. loop variable can be a string giving the name of PARI variable (as in
  343.  
  344.   fordiv(28, 'j', 'a=a+j+j^2');
  345.  
  346. or
  347.  
  348.   $j= 'j';
  349.   fordiv(28, $j, 'a=a+j+j^2');
  350.  
  351. ), a PARI monomial (as in
  352.  
  353.   $j = PARI 'j';
  354.   fordiv(28, $j, sub { $a += $j + $j**2 });
  355.  
  356. ), or a "delayed Math::Pari variable" (as in
  357.  
  358.   $j = PARIvar 'j';
  359.   fordiv(28, $j, 'a=a+j+j^2');
  360.  
  361. ).  If none of these applies, as in
  362.  
  363.   my $j;    # Have this in a separate statement
  364.   fordiv(28, $j, sub { $a += $j + $j**2 });
  365.  
  366. then during the execution of the C<sub>, Math::Pari would autogenerate
  367. a PARI variable, and would put its value in $j; this value of $j is
  368. temporary only, the old contents of $j is restored when fordiv() returns.
  369.  
  370. Note that since you have no control over this name, you will not be
  371. able to use this variable from your PARI code; e.g.,
  372.  
  373.   $j = 7.8;
  374.   fordiv(28, $j, 'a=a+j+j^2');
  375.  
  376. will not make C<j> mirror $j (unless you explicitely set up C<j> to be
  377. a no-argument PARI function mirroring $j, see L<"Accessing Perl functions from PARI code">).
  378.  
  379. B<Caveats>.  There are 2 flavors of the "code" arguments
  380. (string/C<sub>), and 4 types of the "variable" arguments
  381. (string/monomial/C<PARIvar>/other).  However, not all 8 combinations
  382. make sense.  As we already explained, an "other" variable cannot work
  383. with a "string" code.
  384.  
  385. B<Useless musing alert! Do not read the rest of this section!> Do not
  386. use "string" variables with C<sub> code, and do not ask I<why>!
  387.  
  388. Additionally, the following code will not do what you expect
  389.  
  390.   $x = 0;
  391.   $j = PARI 'j';
  392.   fordiv(28, 'j', sub { $x += $j } );    # Use $j as a loop variable!
  393.  
  394. since the PARI function C<fordiv> I<localizes> the PARI variable C<j>
  395. inside the loop, but $j will still reference the old value; the old
  396. value is a monomial, not the index of the loop (which is an integer
  397. each time C<sub> is called).  The simplest workaround is not to use
  398. the above syntax (i.e., not mixing literal loop variable with Perl
  399. loop code, just using $j as the second argument to C<fordiv> is
  400. enough):
  401.  
  402.   $x = 0;
  403.   $j = PARI 'j';
  404.   fordiv(28, $j, sub { $x += $j } );
  405.  
  406. Alternately, one can make a I<delayed> variable $j which will always
  407. reference the same thing C<j> references in PARI I<now> by using
  408. C<PARIvar> constructor
  409.  
  410.   $x = 0;
  411.   $j = PARIvar 'j';
  412.   fordiv(28, 'j', sub { $x += $j } );
  413.  
  414. (This problem is similar to
  415.  
  416.   $ref = \$_;            # $$ref is going to be old value even after
  417.                 # localizing $_ in Perl's grep/map
  418.  
  419. not accessing localized values of $_ in the plain Perl.)
  420.  
  421. Another possible quirk is that
  422.  
  423.   fordiv(28, my $j, sub { $a += $j + $j**2 });
  424.  
  425. will not work too - by a different reason.  C<my> declarations change
  426. the I<meaning> of $j only I<after> the end of the current statement;
  427. thus $j inside C<sub> will access a I<different> variable $j
  428. (typically a non-lexical, global variable $j) than one you declared on this line.
  429.  
  430. =head2 Accessing Perl functions from PARI code
  431.  
  432. Use the same name inside PARI code:
  433.  
  434.   sub counter { $i += shift; }
  435.   $i = 145;
  436.   PARI 'k=5' ;
  437.   fordiv(28, 'j', 'k=k+counter(j)');
  438.   print PARI('k'), "\n";
  439.  
  440. prints
  441.  
  442.    984
  443.  
  444. Due to a difference in the semantic of
  445. variable-number-of-parameters-functions between PARI and Perl, if the
  446. Perl subroutine takes a variable number of arguments (via C<@> in the
  447. prototype or a missing prototype), up to 6 arguments are supported
  448. when this function is called from PARI.  If called from PARI with
  449. fewer arguments, the rest of arguments will be set to be integers C<PARI 0>.
  450.  
  451. Note also that no direct import of Perl variables is available yet
  452. (but you can write a function wrapper for this):
  453.  
  454.   sub getv () {$v}
  455.  
  456. There is an unsupported (and undocumented ;-) function for explicitely
  457. importing Perl functions into PARI, possibly with a different name,
  458. and possibly with explicitely specifying number of arguments.
  459.  
  460. =head1 PARI objects
  461.  
  462. Functions from PARI library may take as arguments and/or return values
  463. the objects of C type C<GEN>. In Perl these data are encapsulated into
  464. special kind of Perl variables: PARI objects. You can check for a
  465. variable C<$obj> to be a PARI object using
  466.  
  467.   ref $obj and $obj->isa('Math::Pari');
  468.  
  469. Most the time you do not need this due to automatic conversions and overloading.
  470.  
  471. =head1 PARI monomials and Perl barewords
  472.  
  473. If very lazy, one can code in Perl the same way one does it in PARI.
  474. Variables in PARI are denoted by barewords, as in C<x>, and in the
  475. default configuration (no warnings, no strict) Perl allows the same -
  476. up to some extent.  Do not do this, since there are many surprising problems.
  477.  
  478. Some bareletters denote Perl operators, like C<q>, C<x>, C<y>,
  479. C<s>. This can lead to errors in Perl parsing your expression. E.g.,
  480.  
  481.   print sin(tan(t))-tan(sin(t))-asin(atan(t))+atan(asin(t));
  482.  
  483. may parse OK after C<use Math::Pari qw(sin tan asin atan)>.  Why?
  484.  
  485. After importing, the word C<sin> will denote the PARI function sin(),
  486. not Perl operator sin().  The difference is subtle: the PARI function
  487. I<implicitly> forces its arguments to be converted PARI objects; it
  488. gets C<'t'> as the argument, which is a string, thus is converted to
  489. what C<t> denotes in PARI - a monomial.  While the Perl operator sin()
  490. grants overloading (i.e., it will call PARI function sin() if the
  491. argument is a PARI object), it does not I<force> its argument; given
  492. C<'t'> as argument, it converts it to what sin() understands, a float
  493. (producing C<0.>), so will give C<0.> as the answer.
  494.  
  495. However
  496.  
  497.   print sin(tan(y))-tan(sin(y))-asin(atan(y))+atan(asin(y));
  498.  
  499. would not compile. You should avoid lower-case barewords used as PARI
  500. variables, e.g., do
  501.  
  502.   $y = PARI 'y';
  503.   print sin(tan($y))-tan(sin($y))-asin(atan($y))+atan(asin($y));
  504.  
  505. to get
  506.  
  507.   -1/18*y^9+26/4725*y^11-41/1296*y^13+328721/16372125*y^15+O(y^16)
  508.  
  509. (BTW, it is a very good exercise to get the leading term by hand).
  510.  
  511. Well, the same advice again: do not use barewords anywhere in your program!
  512.  
  513. =head1 Overloading and automatic conversion
  514.  
  515. Whenever an arithmetic operation includes at least one PARI object,
  516. the other arguments are converted to a PARI object and the corresponding
  517. PARI library functions is used to implement the operation.  Currently
  518. the following arithmetic operations are overloaded:
  519.  
  520.   unary -
  521.   + - * / % ** abs cos sin exp log sqrt
  522.   << >>
  523.   <= == => <  >  != <=>
  524.   le eq ge lt gt ne cmp
  525.   | & ^ ~
  526.  
  527. Numeric comparison operations are converted to C<gcmp> and friends, string
  528. comparisons compare in lexicographical order using C<lex>.
  529.  
  530. Additionally, whenever a PARI object appears in a situation that requires integer,
  531. numeric, boolean or string data, it is converted to the corresponding
  532. type. Boolean conversion is subject to usual PARI pitfalls related to
  533. imprecise zeros (see documentation of C<gcmp0> in PARI reference).
  534.  
  535. For details on overloading, see L<overload>.
  536.  
  537. Note that a check for equality is subject to same pitfalls as in PARI
  538. due to imprecise values.  PARI may also refuse to compare data of
  539. different types for equality if it thinks this may lead to
  540. counterintuitive results.
  541.  
  542. Note also that in PARI the numeric ordering is not defined for some
  543. types of PARI objects.  For string comparison operations we use
  544. PARI-lexicographical ordering.
  545.  
  546. =head1 PREREQUISITES
  547.  
  548. =head2 Perl
  549.  
  550. In the versions of perl earlier than 5.003 overloading used a
  551. different interface, so you may need to convert C<use overload> line
  552. to C<%OVERLOAD>, or, better, upgrade.
  553.  
  554. =head2 PARI
  555.  
  556. Starting from version 2.0, this module comes without a PARI library included.
  557.  
  558. For the source of PARI library see
  559. L<ftp://megrez.math.u-bordeaux.fr/pub/pari>.
  560.  
  561. =head1 Perl vs. PARI: different syntax
  562.  
  563. Note that the PARI notations should be used in the string arguments to
  564. PARI() function, while the Perl notations should be used otherwise.
  565.  
  566. =over 4
  567.  
  568. =item C<^>
  569.  
  570. Power is denoted by C<**> in Perl.
  571.  
  572. =item C<\> and C<\/>
  573.  
  574. There are no such operators in Perl, use the word forms
  575. C<gdivent(x,y)> and C<gdivround(x,y)> instead.
  576.  
  577. =item C<~>
  578.  
  579. There is no postfix C<~> Perl operator.  Use mattranspose() instead.
  580.  
  581. =item C<'>
  582.  
  583. There is no postfix C<'> Perl operator.  Use deriv() instead.
  584.  
  585. =item C<!>
  586.  
  587. There is no postfix C<!> Perl operator.  Use factorial()/ifact() instead
  588. (returning a real or an integer correspondingly).
  589.  
  590. =item big integers
  591.  
  592. Perl converts big I<literal> integers to doubles if they could not be
  593. put into B<C> integers (the particular flavor can be found in the
  594. output of C<perl -V> in newer version of Perl, look for
  595. C<ivtype>/C<ivsize>).  If you want to input such an integer, use
  596.  
  597.   while ($x < PARI('12345678901234567890')) ...
  598.  
  599. instead of
  600.  
  601.   while ($x < 12345678901234567890) ...
  602.  
  603. Why?  Because conversion to double leads to precision loss (typically
  604. above 1e15, see L<perlnumber>), and you will get something like
  605. 12345678901234567168 otherwise.
  606.  
  607. Starting from version 5.005 of Perl, if the tag C<:int> is used on the
  608. 'use Math::Pari' line, all of the integer literals in Perl will be
  609. automatically converted to became PARI objects.  E.g.,
  610.  
  611.   use Math::Pari ':int';
  612.   print 2**1000;
  613.  
  614. is equivalent to
  615.  
  616.   print PARI(2)**PARI(1000);
  617.  
  618. Similarly, large integer literals do not lose precision.
  619.  
  620. This directive is lexically scoped.  There is a similar tag C<:hex>
  621. which affects hexadecimal, octal and binary constants.
  622.  
  623. =item doubles
  624.  
  625. Doubles in Perl are typically of precision approximately 15 digits
  626. (see L<perlnumber>).  When you use them as arguments to PARI
  627. functions, they are converted to PARI real variables, and due to
  628. intermediate 15-digits-to-binary conversion of Perl variables the
  629. result may be different than with the PARI many-digits-to-binary
  630. conversion.  E.g., C<PARI(0.01)> and C<PARI('0.01')> differ at 19-th
  631. place, as
  632.  
  633.   setprecision(38);
  634.   print pari_print(0.01),   "\n",
  635.         pari_print('0.01'), "\n";
  636.  
  637. shows.
  638.  
  639. Note that setprecision() changes the output format of pari_print() and
  640. friends, as well as the default internal precision.  The generic
  641. PARI===>string conversion does not take into account the output
  642. format, thus
  643.  
  644.   setprecision(38);
  645.   print PARI(0.01),       "\n",
  646.         PARI('0.01'),     "\n",
  647.         pari_print(0.01), "\n";
  648.  
  649. will print all the lines with different number of digits after the
  650. point: the first one with 22, since the double 0.01 was converted to a
  651. low-precision PARI object, the second one with 41, since internal form
  652. for precision 38 requires that many digits for representation, and the
  653. last one with 39 to have 38 significant digits.
  654.  
  655. Starting from version 5.005 of Perl, if the tag C<:float> is used on
  656. the C<use Math::Pari> line, all the float literals in Perl will be
  657. automatically converted to became PARI objects.  E.g.,
  658.  
  659.   use Math::Pari ':float';
  660.   print atan(1.);
  661.  
  662. is equivalent to
  663.  
  664.   print atan(PARI('1.'));
  665.  
  666. Similarly, large float literals do not lose precision.
  667.  
  668. This directive is lexically scoped.
  669.  
  670. =item array base
  671.  
  672. Arrays are 1-based in PARI, are 0-based in Perl.  So while array
  673. access is possible in Perl, you need to use different indices:
  674.  
  675.   $nf = PARI 'nf';    # assume that PARI variable nf contains a number field
  676.   $a = PARI('nf[7]');
  677.   $b = $nf->[6];
  678.  
  679. Now $a and $b contain the same value.
  680.  
  681. =item matrices
  682.  
  683. Note that C<PARImat([[...],...,[...])> constructor creates a matrix
  684. with specified columns, while in PARI the command C<[1,2,3;4,5,6]>
  685. creates a matrix with specified rows.  Use a convenience function
  686. PARImat_tr() which will transpose a matrix created by PARImat() to use
  687. the same order of elements as in PARI.
  688.  
  689. =item builtin perl functions
  690.  
  691. Some PARI functions, like C<length> and C<eval>, are Perl
  692. (semi-)reserved words.  To reach these functions, one should either
  693. import them:
  694.  
  695.   use Math::Pari qw(length eval);
  696.  
  697. or call them with prefix (like C<&length>) or the full name (like
  698. C<Math::Pari::length>).
  699.  
  700. =back
  701.  
  702. =head1 High-resolution graphics
  703.  
  704. If you have Term::Gnuplot Perl module installed, you may use high-resolution
  705. graphic primitives of B<PARI>.  Before the usage you need to establish
  706. a link between Math::Pari and Term::Gnuplot by calling link_gnuplot().
  707. You can change the output filehandle by calling set_plot_fh(), and
  708. output terminal by calling plotterm(), as in
  709.  
  710.     use Math::Pari qw(:graphic asin);
  711.  
  712.     open FH, '>out.tex' or die;
  713.     link_gnuplot();        # automatically loads Term::Gnuplot
  714.     set_plot_fh(\*FH);
  715.     plotterm('emtex');
  716.     ploth($x, .5, .999, sub {asin $x});
  717.     close FH or die;
  718.  
  719. =head1 libPARI documentation
  720.  
  721. libPARI documentation is included, see L<Math::libPARI>.  It is converted
  722. from Chapter 3 of B<PARI/GP> documentation by the F<gphelp> script of GP/PARI.
  723.  
  724. =head1 ENVIRONMENT
  725.  
  726. No environment variables are used.
  727.  
  728. =head1 BUGS
  729.  
  730. =over 5
  731.  
  732. =item *
  733.  
  734. A few of PARI functions are available indirectly only.
  735.  
  736. =item *
  737.  
  738. Using overloading constants with the Perl versions below 5.005_57 could lead to
  739. segfaults (at least without C<-D usemymalloc>), as in:
  740.  
  741.   use Math::Pari ':int';
  742.   for ( $i = 0; $i < 10 ; $i++ ) { print "$i\n" }
  743.  
  744. =item *
  745.  
  746. It may be possible that conversion of a Perl value which has both the
  747. integer slot and the floating slot set may create a PARI integer, even
  748. if the actual value is not an integer.
  749.  
  750. =item *
  751.  
  752. problems with refcounting of array elements and Mod().
  753.  
  754. Workaround: make the modulus live longer than the result of Mod().
  755. Until Perl version C<5.6.1>, one should exercise a special care so
  756. that the modulus goes out of scope on a different statement than the
  757. result:
  758.  
  759.   { my $modulus = 125;
  760.     { my $res = Mod(34, $modulus);
  761.       print $res;
  762.     }
  763.     $fake = 1;        # A (fake) statement here is required
  764.   }
  765.  
  766. Here $res is destructed before the C<$fake = 1> statement, $modulus is
  767. destructed before the first statement after the provided block.
  768. However, if you remove the C<$fake = 1> statement, both these
  769. variables are destructed on the first statement after the provided
  770. block (and in a wrong order!).
  771.  
  772. In C<5.6.1> declaring $modulus before $res is all that is needed to
  773. circumvent the same problem:
  774.  
  775.   { my $modulus = 125;
  776.     my $res = Mod(34, $modulus);
  777.     print $res;
  778.   }            # destruction will happen in a correct order.
  779.  
  780. Access to array elements may result in similar problems.  Hard to fix
  781. since in PARI the data is not refcounted.
  782.  
  783. =item *
  784.  
  785. Legacy implementations of dynalinking require the code of DLL to be
  786. compiled to be "position independent" code (PIC).  This slows down the
  787. execution, while allowing sharing the loaded copy of the DLL between
  788. different processes.  [On contemeporary architectures the same effect
  789. is allowed without the position-independent hack.]
  790.  
  791. Currently, PARI assembler files are not position-independent.  When
  792. compiled for the dynamic linking on legacy systems, this creates a DLL
  793. which cannot be shared between processes.  Some legacy systems are
  794. reported to recognize this situation, and load the DLL as a non-shared
  795. module.  However, there may be systems (are there?) on which this can
  796. cause some "problems".
  797.  
  798. Summary: if the dynaloading on your system requires some kind of C<-fPIC> flag, using "assembler" compiles (anything but C<machine=none>) *may* force you to do a static build (i.e., creation of a custom Perl executable with
  799.  
  800.  perl Makefile.PL static
  801.  make perl
  802.  make test_static
  803.  
  804. ).
  805.  
  806. =back
  807.  
  808. =head1 INITIALIZATION
  809.  
  810. When Math::Pari is loaded, it examines variables $Math::Pari::initmem
  811. and $Math::Pari::initprimes.  They specify up to which number the
  812. initial list of primes should be precalculated, and how large should
  813. be the arena for PARI calculations (in bytes).  (These values have
  814. safe defaults.)
  815.  
  816. Since setting these values before loading requires either a C<BEGIN>
  817. block, or postponing the loading (C<use> vs. C<require>), it may be
  818. more convenient to set them via Math::PariInit:
  819.  
  820.   use Math::PariInit qw( primes=12000000 stack=1e8 );
  821.  
  822. C<use Math::PariInit> also accepts arbitrary Math::Pari import directives,
  823. see L<Math::PariInit>.
  824.  
  825. These values may be changed at runtime too, via allocatemem() and
  826. setprimelimit(), with performance penalties for recalculation/reallocation.
  827.  
  828. =head1 AUTHOR
  829.  
  830. Ilya Zakharevich, I<perl-module-math-pari@ilyaz.org>
  831.  
  832. =cut
  833.  
  834. # $Id: Pari.pm,v 1.3 1994/11/25 23:40:52 ilya Exp ilya $
  835. package Math::Pari::Arr;
  836.  
  837. #sub TIEARRAY { $_[0] }
  838. sub STORE { die "Storing into array elements unsupported" }
  839.  
  840. package Math::Pari;
  841.  
  842. require Exporter;
  843. require DynaLoader;
  844. #use autouse Carp => 'croak';
  845.  
  846. @ISA = qw(Exporter DynaLoader);
  847. @Math::Pari::Ep::ISA = qw(Math::Pari);
  848.  
  849. # Items to export into callers namespace by default
  850. # (move infrequently used names to @EXPORT_OK below)
  851.  
  852. @EXPORT = qw(
  853. PARI PARIcol PARImat PARIvar PARImat_tr
  854. );
  855.  
  856. # Other items we are prepared to export if requested (may be extended during
  857. # ->import. )
  858. @EXPORT_OK = qw(
  859.   sv2pari sv2parimat pari2iv pari2nv pari2num pari2pv pari2bool loadPari _bool
  860.   listPari pari_print pari_pprint pari_texprint O ifact gdivent gdivround
  861.   changevalue set_plot_fh link_gnuplot setprecision setseriesprecision
  862.   setprimelimit allocatemem type_name
  863. );
  864.  
  865. use subs qw(
  866.    _gneg
  867.    _gadd
  868.    _gsub
  869.    _gmul
  870.    _gdiv
  871.    _gmod
  872.    _gpui
  873.    _gle
  874.    _gge
  875.    _glt
  876.    _ggt
  877.    _geq
  878.    _gne
  879.    _gcmp
  880.    _lex
  881.    _2bool
  882.    pari2pv
  883.    pari2num
  884.    _abs
  885.    _cos
  886.    _sin
  887.    _exp
  888.    _log
  889.    _sqrt
  890.    _gbitand
  891.    _gbitor
  892.    _gbitxor
  893.    _gbitneg
  894.    _to_int
  895.    _gbitshiftr
  896.    _gbitshiftl
  897. );        # Otherwise overload->import would complain...
  898.  
  899. my $two;
  900.  
  901. sub _shiftl {
  902.   my ($left,$right) = (shift,shift);
  903.   ($left,$right) = ($right, $left) if shift;
  904.   $left * $two**$right;
  905. }
  906.  
  907. sub _shiftr {
  908.   my ($left,$right) = (shift,shift);
  909.   ($left,$right) = ($right, $left) if shift;
  910.   floor($left / $two**$right);
  911. }
  912.  
  913. $initmem = $initmem || 4000000;        # How much memory for the stack
  914. $initprimes = $initprimes || 500000;    # Calculate primes up to this number
  915.  
  916. $VERSION = '2.010500';
  917.  
  918. bootstrap Math::Pari;
  919.  
  920. use overload qw(
  921.    neg _gneg
  922.    + _gadd
  923.    - _gsub
  924.    * _gmul
  925.    / _gdiv
  926.    % _gmod
  927.    ** _gpui
  928.    <= _gle
  929.    >= _gge
  930.    < _glt
  931.    > _ggt
  932.    == _geq
  933.    != _gne
  934.    <=> _gcmp
  935.    cmp _lex
  936.    bool _2bool
  937.    "" pari2pv
  938.    +0 pari2num
  939.    abs _abs
  940.    cos _cos
  941.    sin _sin
  942.    exp _exp
  943.    log _log
  944.    sqrt _sqrt
  945.    int _to_int
  946. );
  947.  
  948. if (pari_version_exp() >= 2000018) {
  949.   'overload'->import( qw(
  950.              | _gbitor
  951.              & _gbitand
  952.              ^ _gbitxor
  953.              ~ _gbitneg
  954.             ) );
  955. }
  956.  
  957. if (pari_version_exp() >= 2002001) {
  958.   'overload'->import( qw(
  959.              << _gbitshiftl
  960.              >> _gbitshiftr
  961.             ) );
  962. } else {
  963.   'overload'->import( qw(
  964.              << _shiftl
  965.              >> _shiftr
  966.             ) );
  967. }
  968.  
  969. sub AUTOLOAD {
  970.   $AUTOLOAD =~ /^(?:Math::Pari::)?(.*)/;
  971.   # warn "Autoloading $1...\n";
  972.   # exit 4 if $1 eq 'loadPari';
  973.   my $cv = loadPari($1);
  974.  
  975. #  goto &$cv;
  976. #  goto &$AUTOLOAD;
  977. #  &$cv;
  978.   &$1;
  979. #  &$AUTOLOAD;
  980. }
  981.  
  982. # Needed this guy to circumwent autoloading while no XS definition
  983.  
  984. #### sub DESTROY {}
  985.  
  986.  
  987. # sub AUTOLOAD {
  988. #     if ((caller(0))[4]) {
  989. #     $AutoLoader::AUTOLOAD = $AUTOLOAD;
  990. #     goto &AutoLoader::AUTOLOAD;
  991. #     }
  992. #     local($constname);
  993. #     ($constname = $AUTOLOAD) =~ s/.*:://;
  994. #     $val = constant($constname, @_ ? $_[0] : 0);
  995. #     if ($! != 0) {
  996. #     if ($! =~ /Invalid/) {
  997. #         $AutoLoader::AUTOLOAD = $AUTOLOAD;
  998. #         goto &AutoLoader::AUTOLOAD;
  999. #     }
  1000. #     else {
  1001. #         ($pack,$file,$line) = caller;
  1002. #         die "Your vendor has not defined Math::Pari macro $constname, used at $file line $line.
  1003. # ";
  1004. #     }
  1005. #     }
  1006. #     eval "sub $AUTOLOAD { $val }";
  1007. #     goto &$AUTOLOAD;
  1008. # }
  1009.  
  1010. # Preloaded methods go here.  Autoload methods go after __END__, and are
  1011. # processed by the autosplit program.
  1012.  
  1013. sub new {
  1014.   shift;
  1015.   if (@_>1) {my(@t)=@_;return sv2pari(\@t)}
  1016.   return sv2pari(shift);
  1017. }
  1018.  
  1019. ###sub PARI {new Math::Pari @_}
  1020.  
  1021. %names    = qw(
  1022.            1 standard
  1023.            2 conversions
  1024.            3 transcendental
  1025.            4 number
  1026.            5 elliptic
  1027.            6 fields
  1028.            7 polynomials
  1029.            8 vectors
  1030.            9 sums
  1031.            10 graphic
  1032.            11 programming
  1033.           );
  1034. @sections{values %names} = keys %names;
  1035.  
  1036. @converted{split /,\s+/, qq(buchimag, buchreal,
  1037.     buchgen, buchgenforcefu, buchgenfu, buchinit, buchinitforcefu, buchinitfu,
  1038.     plotstring, addhelp, kill)} = (1) x 100;
  1039.  
  1040. # Now even tested...
  1041. sub _cvt { PARI(shift) }
  1042. sub _hex_cvt {
  1043.   my $in = shift;
  1044.   my $mult = PARI(1);
  1045.   my $ret = 0;
  1046.   my $shift = 1<<(4*7);
  1047.  
  1048.   $in =~ s/^0([xb])?// or die;
  1049.   my $hex = $1;
  1050.   if ($hex and $1 eq 'b') {
  1051.     my $b = '0' x (15 * length($in) % 16) . $in;
  1052.     $hex = '';
  1053.     while ($b) {
  1054.       my $s = substr $b, 0, 16;
  1055.       substr($b, 0, 16) = '';
  1056.       $hex .= unpack 'H4', pack 'B16', $s;
  1057.     }
  1058.     $in = $hex;
  1059.   }
  1060.   $shift = 1<<(3*7) unless $hex;
  1061.   while ($in =~ s/([a-fA-F\d]{1,7})$//) {
  1062.     # In 5.6.0 hex() can return a floating number:
  1063.     my $part = int($hex ? hex $1 : oct $1);
  1064.  
  1065.     $ret += $part * $mult;
  1066.     $mult *= $shift;
  1067.   }
  1068.   die "Cannot hex '$in'" if length $in;
  1069.   return $ret;
  1070. }
  1071. %overloaded_const = ( 'int' => \&_cvt, float => \&_cvt, 'hex' => \&_hex_cvt);
  1072. %overloaded_const_word
  1073.   = ( 'int' => 'integer', float => 'float', 'hex' => 'binary');
  1074.  
  1075. sub import {
  1076.   my $p=shift;
  1077.   my @consts;            # Need to do it outside any block!
  1078.   @_ = map {
  1079.     if (/^:(?!DEFAULT)(.*)/) {
  1080.       my $tag = $1;
  1081.       my $sect = $tag;
  1082.       my @pre;
  1083.       $tag = -1, @pre = (@EXPORT_OK,@EXPORT) if ($tag eq 'all');
  1084.       $tag = -1 if ($tag eq 'PARI');
  1085.       $tag = $sections{$tag} if $tag !~ /^-?\d+$/ and exists $sections{$tag};
  1086.       push @pre, 'link_gnuplot', 'set_plot_fh' if $tag eq 10;
  1087.       if ($tag =~ /^prec=(\d+)$/) {
  1088.     setprecision($1);
  1089.     ();
  1090.       } elsif ($tag =~ /^(int|hex|float)$/) {
  1091.     die "Overloaded constants are not supported in this version of Perl"
  1092.       if $] < 5.004_69;
  1093.     push @const, $overloaded_const_word{$tag} => $overloaded_const{$tag};
  1094.     # print "Constants: $overloaded_const_word{$tag} => $overloaded_const{$tag} \n";
  1095.     ();
  1096.       } elsif (defined $tag and $tag =~ /^-?\d+$/) {
  1097.     (@pre, listPari($tag));
  1098.       } else {
  1099.     die "Unknown section '$sect' specified";
  1100.       }
  1101.     } else {
  1102.       ($_);
  1103.     }
  1104.   } @_;
  1105.  
  1106.   overload::constant(splice @const, 0, 2) while @const;
  1107.  
  1108.   # print "EXPORT_OK: @EXPORT_OK\n";
  1109.   push @EXPORT_OK,
  1110.       grep( ($_ ne ':DEFAULT'
  1111.          and not $export_ok{$_}++
  1112.          and (eval {loadPari($_), 1} or warn $@), !$@) ,
  1113.         @_);
  1114.   # Invalidate Exporter cache, so that new %EXPORT_OK is noticed:
  1115.   undef %EXPORT;
  1116.   # print "EXPORT_OK: @EXPORT_OK\n";
  1117.   &Exporter::export($p,(caller(0))[0],@_);
  1118. }
  1119.  
  1120. sub _can {            # Without taking into account inheritance...
  1121.   my ($obj, $meth) = (shift, shift);
  1122.   return \&$meth if defined &$meth;
  1123.   return \&$meth if eval {loadPari($meth), 1};
  1124.   return;
  1125. }
  1126.  
  1127. sub can {
  1128.   my ($obj, $meth) = (@_);
  1129.   my $f = $obj->SUPER::can($meth);
  1130.   return $f if defined $f;
  1131.   # There is no "usual" way to get the function; try loadPari()
  1132.   $f = eval { loadPari($meth) };
  1133.   return $f if defined $f;
  1134.   return;
  1135. }
  1136.  
  1137. sub O ($;$) {
  1138.   return PARI("O($_[0]^$_[1])") if @_ == 2;
  1139.   return PARI("O($_[0])") if typ($_[0]) == 10; # Poly
  1140.   Carp::croak("O(number**power) not implemented, use O(number,power) instead");
  1141. }
  1142.  
  1143. sub PARImat_tr {mattranspose(PARImat(@_))}
  1144. #sub string ($$) {
  1145. #  PARI (qq'string($_[0],"$_[1]")');
  1146. #}
  1147.  
  1148. sub installPerlFunction {my @a=@_; $a[0] = \&{$a[0]}; installPerlFunctionCV(@a)}
  1149.  
  1150. my $name;
  1151.  
  1152. for $name (keys %converted) {
  1153.   push @EXPORT_OK, $name;
  1154.   next if defined &$name;
  1155.   # string needs to format numbers to 8.3...
  1156.   if ($name eq 'addhelp' or $name eq 'plotstring') {
  1157.     *$name = sub { PARI ( qq($name($_[0],"$_[1]")) ) }
  1158.   } else {
  1159.     *$name = sub { local $"=','; PARI("$name(@_)") }
  1160.   }
  1161. }
  1162.  
  1163. @export_ok{@EXPORT_OK,@EXPORT} = (1) x (@EXPORT_OK + @EXPORT);
  1164.  
  1165. sub link_gnuplot {
  1166.     eval 'use Term::Gnuplot 0.56; 1' or die;
  1167.     int_set_term_ftable(Term::Gnuplot::get_term_ftable());
  1168. }
  1169.  
  1170. sub set_plot_fh {
  1171.   eval 'use Term::Gnuplot 0.4; 1' or die;
  1172.   Term::Gnuplot::set_gnuplot_fh(@_);
  1173. }
  1174.  
  1175. $two = PARI(2);
  1176.  
  1177. 1;
  1178. __END__
  1179.