1Pari(3) User Contributed Perl Documentation Pari(3)
2
3
4
6 Math::Pari - Perl interface to PARI.
7
9 use Math::Pari;
10 $a = PARI 2;
11 print $a**10000;
12
13 or
14
15 use Math::Pari qw(Mod);
16 $a = Mod(3,5);
17 print $a**10000;
18
20 This package is a Perl interface to famous library PARI for
21 numerical/scientific/number-theoretic calculations. It allows use of
22 most PARI functions as Perl functions, and (almost) seamless merging of
23 PARI and Perl data. In what follows we suppose prior knowledge of what
24 PARI is (see <ftp://megrez.math.u-bordeaux.fr/pub/pari>, or
25 Math::libPARI).
26
28 DEFAULT
29 By default the package exports functions PARI(), PARIcol(),
30 PARIvar(), PARImat(), PARImat_tr() and parse_as_gp() which convert
31 their argument(s) to a PARI object. (In fact PARI() is just an
32 alias for "new Math::Pari"). The function PARI() accepts following
33 data as its arguments
34
35 One integer Is converted to a PARI integer.
36
37 One float Is converted to a PARI float.
38
39 One string Is executed as a PARI expression (so should not
40 contain whitespace).
41
42 PARI object Is passed unchanged.
43
44 Reference to a Perl array
45 Each element is converted using the same rules,
46 PARI vector-row with these elements is returned.
47
48 Several of above The same as with a reference to array.
49
50 Conflicts of rules in PARI()
51 In deciding what rule of the above to apply the preference is given
52 to the uppermost choice of those available now. If none matches,
53 then the string rule is used. So PARI(1) returns integer,
54 "PARI(1.)" returns float, "PARI("1")" evaluates 1 as a PARI
55 expression (well, the result is the same as PARI(1), only slower).
56
57 Note that for Perl these data are synonymous, since Perl freely
58 converts between integers, float and strings. However, to PARI()
59 only what the argument is now is important. If $v is 1 in the Perl
60 world, "PARI($v)" may convert it to an integer, float, or to the
61 result of evaluating the PARI program 1 (all depending on how $v
62 was created and accessed in Perl).
63
64 This is a fundamental limitation of creating an interface between
65 two systems, both with polymorphic objects, but with subtly
66 different semantic of the flavors of these objects. In reality,
67 however, this is rarely a problem.
68
69 PARIcol(), PARImat() and PARImat_tr()
70 PARIcol() behaves in the same way as PARI() unless given several
71 arguments. In the latter case it returns a vector-column instead of
72 a vector-row.
73
74 PARImat() constructs a matrix out of the given arguments. It will
75 work if PARI() will construct a vector of vectors given the same
76 arguments. The internal vectors become columns of the matrix.
77 PARImat_tr() behaves similarly, but the internal vectors become
78 rows of the matrix.
79
80 Since PARI matrices are similar to vector-rows of vector-columns,
81 PARImat() is quicker, but PARImat_tr() better corresponds to the
82 PARI input and output forms of matrices:
83
84 print PARImat [[1,2], [3,4]]; # prints [1,3;2,4]
85 print PARImat_tr [[1,2], [3,4]]; # prints [1,2;3,4]
86
87 parse_as_gp()
88 Did you notice that when taking a string, PARI() requires that
89 there is no whitespace there (outside of string constants)? This
90 is exactly as the "PARI" library parses strings. However, to
91 simplify human interaction, the "gp" calculator allows whitespace,
92 comments, breaking into multiple lines, many independent
93 expressions (such as function definitions).
94
95 We do not include the corresponding C code from the calculator, but
96 provide a Perl clone. It supports whitespace, "\\"- and "/*
97 */"-comments, and, for multi-line arguments, it supports line
98 continuation via trailing "\", trailing binary ops, comma, opening
99 parenthesis/bracket; moreover, group of lines in "{}" are joined
100 into one line. (Additionally, "\q" and "\p" are recognized, as
101 well as trailing allocatemem(). "\e" is tolerated.)
102
103 Keep in mind that this is just a convenience function, and no
104 attempt was performed to make it particularly quick. Moreover, the
105 PARI user functions (or maybe it is better to call them user
106 macros?) are currently not automatically importable into Perl, so
107 to access functions defined in parse_as_gp()' argument may be
108 awkward. (The temporary fix is to use a temporary convenience
109 function __wrap_PARI_macro():
110
111 parse_as_gp <<EOP;
112 add2(x) = x + 2
113 EOP
114 *add2 = Math::Pari::__wrap_PARI_macro 'add2';
115 print add2(17);
116
117 but keep in mind that the generated this way wrapper is also not
118 designed to be quick.)
119
120 With the optional second argument 'quote', it would return an
121 unevaluated array of strings instead of the result of evaluation.
122 Special strings "\q" etc. are replaced by references to appropriate
123 (undocumented) Perl subroutines.
124
125 With the optional third argument 'echo', would "echo" the commands
126 (preceded by "? ") before execution. With "TRUE" optional fourth
127 argument (command counter), would "echo" the result too (preceded
128 by "%C = ", with "C" being the command counter, which is
129 incremented).
130
131 "use" with arguments
132 If arguments are specified in the "use Math::Pari" directive, the
133 PARI functions appearing as arguments are exported in the caller
134 context. In this case the function PARI() and friends is not
135 exported, so if you need them, you should include them into export
136 list explicitly, or include ":DEFAULT" tag:
137
138 use Math::Pari qw(factorint PARI);
139 use Math::Pari qw(:DEFAULT factorint);
140
141 or simply do it in two steps
142
143 use Math::Pari;
144 use Math::Pari 'factorint';
145
146 The other recognized tags are ":PARI", ":all", "prec=NUMBER",
147 overloaded constants tags (":int", ":float", ":hex") and "section
148 names" tags.
149
150 Additionally, the number tags (e.g., ":4") export functions from
151 the PARI library from the given "section" (moreover, ":PARI"
152 exports all of the "sections"). Tag ":all" exports all of the
153 exportable symbols and ":PARI".
154
155 With older versions of PARI, giving "?" command to "gp" (the PARI
156 calculator) lists the following sections:
157
158 1: Standard monadic or dyadic OPERATORS
159 2: CONVERSIONS and similar elementary functions
160 3: TRANSCENDENTAL functions
161 4: NUMBER THEORETICAL functions
162 5: Functions related to ELLIPTIC CURVES
163 6: Functions related to general NUMBER FIELDS
164 7: POLYNOMIALS and power series
165 8: Vectors, matrices, LINEAR ALGEBRA and sets
166 9: SUMS, products, integrals and similar functions
167 10: GRAPHIC functions
168 11: PROGRAMMING under GP
169
170 Starting with GP/PARI version 2.9.0, this list depends
171 significantly on this version; for backward compatibility, we
172 follow this older list of section numbers (to avoid confusion,
173 better use symbolic names below). For compatibility, we assign
174 arbitrary numbers to newer sections:
175
176 100: L-FUNCTIONS
177 101: MODULAR SYMBOLS
178 102: Associative and central simple ALGEBRAS
179 103: functions related to COMBINATORICS
180 104: MODULAR FORMS
181
182 One can use section names instead of number tags. Recognized names
183 are
184
185 :standard :conversions :transcendental :number :elliptic
186 :fields :polynomials :vectors :sums :graphic :programming
187 :l_functions :modular_symb :algebras :combinatorics :modular
188
189 One can get the list of all of the functions accessible by
190 "Math::Pari", or the accessible functions from the given section
191 using listPari() function.
192
193 Starting from version 5.005 of Perl, three constant-overload tags
194 are supported: ":int", ":float", ":hex". If used, all the
195 integer/float/hex-or-octal-or-binary literals in Perl will be
196 automatically converted to became PARI objects. For example,
197
198 use Math::Pari ':int';
199 print 2**1000;
200
201 is equivalent to
202
203 print PARI(2)**PARI(1000);
204
205 (The support for this Perl feature is buggy before the Perl version
206 5.005_57 - unless Perl uses mymalloc options; you can check for
207 this with "perl -V:usemymalloc".) Note also that (at least with
208 some versions of Perl) one should enable ':float' for conversion of
209 long integer literals (Perl may consider them as floats, since they
210 won't fit into Perl integers); note that it is PARI which
211 determines which PARI subtype is assigned to each such literal:
212
213 use Math::Pari ':float', 'type_name';
214 print type_name 22222222222222222222222;
215
216 prints "t_INT".
217
219 Directly accessible from Perl
220 This package supports all the functions from the PARI library with a
221 signature which can be recognized by Math::Pari. This means that when
222 you update the PARI library, the newly added functions will we
223 available without any change to this package; only a recompile is
224 needed. In fact no recompile will be needed if you link libPARI
225 dynamically (you need to modify the Makefile manually to do this).
226
227 You can "reach" unsupported functions via going directly to PARI parser
228 using the string flavor of PARI() function, as in
229
230 3 + PARI('O(x^17)');
231
232 For some "unreachable" functions there is a special wrapper functions,
233 such as "O(variable,power)").
234
235 The following functions are specific to GP calculator, thus are not
236 available to Math::Pari in any way:
237
238 default error extern input print print1 printp printp1
239 printtex quit read system whatnow write write1 writetex
240
241 whatnow() function is useless, since Math::Pari does not support the
242 "compatibility" mode (with older PARI library). The functionality of
243 print(), write() and variants is available via automatic string
244 translation, and pari_print() function and its variants (see "Printout
245 functions").
246
247 default() is the only important function with functionality not
248 supported by the current interface. Note however, that four most
249 important default() actions are supported by allocatemem(),
250 setprimelimit(), setprecision() and setseriesprecision() functions.
251 (When called without arguments, these functions return the current
252 values.)
253
254 allocatemem($bytes) should not be called from inside Math::Pari
255 functions (such as forprimes()).
256
257 Arguments
258 Arguments to PARI functions are automatically converted to "long" or a
259 PARI object depending on the signature of the actual library function.
260 The arguments are forced into the given type, so even if "gp" rejects
261 your code similar to
262
263 func(2.5); # func() takes a long in C
264
265 arguing that a particular argument should be of "type T_INT" (i.e., a
266 Pari integer), the corresponding code will work in "Math::Pari", since
267 2.5 is silently converted to "long", per the function signature.
268
269 Return values
270 PARI functions return a PARI object or a Perl's integer depending on
271 what the actual library function returns.
272
273 Additional functions
274 Some PARI functions are available in "gp" (i.e., in "PARI" calculator)
275 via infix notation only. In "Math::Pari" these functions are available
276 in functional notations too. Some other convenience functions are also
277 made available.
278
279 Infix, prefix and postfix operations
280 are available under names
281
282 gneg, gadd, gsub, gmul, gdiv, gdivent, gmod, gpui,
283 gle, gge, glt, ggt, geq, gne, gegal, gor, gand,
284 gcmp, gcmp0, gcmp1, gcmp_1.
285
286 "gdivent" means euclidean quotient, "gpui" is power, "gegal"
287 checks whether two objects are equal, "gcmp" is applicable to two
288 real numbers only, "gcmp0", "gcmp1", "gcmp_1" compare with 0, 1
289 and -1 correspondingly (see PARI user manual for details, or
290 Math::libPARI). Note that all these functions are more readily
291 available via operator overloading, so instead of
292
293 gadd(gneg($x), $y)
294
295 one can write
296
297 -$x+$y
298
299 (as far as overloading may be triggered, see overload, so we
300 assume that at least one of $x or $y is a PARI object).
301
302 Conversion functions
303 pari2iv, pari2nv, pari2num, pari2pv, pari2bool
304
305 convert a PARI object to an integer, float, integer/float
306 (whatever is better), string, and a boolean value correspondingly.
307 Most the time you do not need these functions due to automatic
308 conversions.
309
310 Printout functions
311 pari_print, pari_pprint, pari_texprint
312
313 perform the same conversions to strings as their PARI
314 counterparts, but do not print the result. The difference of
315 pari_print() with pari2pv() is the number of significant digits
316 they output, and whitespace in the output. pari2pv(), which is
317 intended for "computer-readable strings", outputs as many digits
318 as is supported by the current precision of the number; while
319 pari_print(), which targets human-readable strings, takes into
320 account the currently specified output precision too.
321
322 Constant functions
323 Some mathematical constants appear as function without arguments
324 in PARI. These functions are available in Math::Pari too. If you
325 export them as in
326
327 use Math::Pari qw(:DEFAULT Pi I Euler);
328
329 they can be used as barewords in your program:
330
331 $x = Pi ** Euler;
332
333 Low-level functions
334 For convenience of low-level PARI programmers some low-level
335 functions are made available as well (all except type_name() and
336 changevalue() are not exportable):
337
338 typ($x)
339 lg($x)
340 lgef($x)
341 lgefint($x)
342 longword($x, $n)
343 type_name($x)
344 changevalue($name,$newvalue)
345
346 Here longword($x,$n) returns $n-th word in the memory
347 representation of $x (including non-code words). type_name()
348 differs from the PARI function type(): type() returns a PARI
349 object, while type_name() returns a Perl string. (PARI objects of
350 string type behave very non-intuitive w.r.t. string comparison
351 functions; remember that they are compared using lex() to the
352 results of evaluation of other argument of comparison!)
353
354 The function listPari($number) outputs a list of names of PARI
355 functions in the section $number. Use listPari(-1) to get the
356 list across all of the sections. (_listPari() behaves likewise,
357 with the version-specific section numbers.)
358
359 Uncompatible functions
360 O
361
362 Since implementing "O(7**6)" would be very tedious, we provide a
363 two-argument form "O(7,6)" instead (meaning the same as "O(7^6)"
364 in PARI). Note that with polynomials there is no problem like
365 this one, both "O($x,6)" and "O($x**6)" work.
366
367 ifact(n)
368
369 integer factorial functions, available from "gp" as "n!".
370
371 Looping functions
372 PARI has a big collection of functions which loops over some set. Such
373 a function takes two special arguments: loop variable, and the code to
374 execute in the loop.
375
376 The code can be either a string (which contains PARI code to execute -
377 thus should not contain whitespace), or a Perl code reference. The
378 loop variable can be a string giving the name of PARI variable (as in
379
380 fordiv(28, 'j', 'a=a+j+j^2');
381
382 or
383
384 $j= 'j';
385 fordiv(28, $j, 'a=a+j+j^2');
386
387 ), a PARI monomial (as in
388
389 $j = PARI 'j';
390 fordiv(28, $j, sub { $a += $j + $j**2 });
391
392 ), or a "delayed Math::Pari variable" (as in
393
394 $j = PARIvar 'j';
395 fordiv(28, $j, 'a=a+j+j^2');
396
397 ). If none of these applies, as in
398
399 my $j; # Have this in a separate statement
400 fordiv(28, $j, sub { $a += $j + $j**2 });
401
402 then during the execution of the "sub", Math::Pari would autogenerate a
403 PARI variable, and would put its value in $j; this value of $j is
404 temporary only, the old contents of $j is restored when fordiv()
405 returns.
406
407 Note that since you have no control over this name, you will not be
408 able to use this variable from your PARI code; e.g.,
409
410 $j = 7.8;
411 fordiv(28, $j, 'a=a+j+j^2');
412
413 will not make "j" mirror $j (unless you explicitly set up "j" to be a
414 no-argument PARI function mirroring $j, see "Accessing Perl functions
415 from PARI code").
416
417 Caveats. There are 2 flavors of the "code" arguments (string/"sub"),
418 and 4 types of the "variable" arguments
419 (string/monomial/"PARIvar"/other). However, not all 8 combinations
420 make sense. As we already explained, an "other" variable cannot work
421 with a "string" code.
422
423 Useless musing alert! Do not read the rest of this section! Do not use
424 "string" variables with "sub" code, and do not ask why!
425
426 Additionally, the following code will not do what you expect
427
428 $x = 0;
429 $j = PARI 'j';
430 fordiv(28, 'j', sub { $x += $j } ); # Use $j as a loop variable!
431
432 since the PARI function "fordiv" localizes the PARI variable "j" inside
433 the loop, but $j will still reference the old value; the old value is a
434 monomial, not the index of the loop (which is an integer each time
435 "sub" is called). The simplest workaround is not to use the above
436 syntax (i.e., not mixing literal loop variable with Perl loop code,
437 just using $j as the second argument to "fordiv" is enough):
438
439 $x = 0;
440 $j = PARI 'j';
441 fordiv(28, $j, sub { $x += $j } );
442
443 Alternately, one can make a delayed variable $j which will always
444 reference the same thing "j" references in PARI now by using "PARIvar"
445 constructor
446
447 $x = 0;
448 $j = PARIvar 'j';
449 fordiv(28, 'j', sub { $x += $j } );
450
451 (This problem is similar to
452
453 $ref = \$_; # $$ref is going to be old value even after
454 # localizing $_ in Perl's grep/map
455
456 not accessing localized values of $_ in the plain Perl.)
457
458 Another possible quirk is that
459
460 fordiv(28, my $j, sub { $a += $j + $j**2 });
461
462 will not work too - by a different reason. "my" declarations change
463 the meaning of $j only after the end of the current statement; thus $j
464 inside "sub" will access a different variable $j (typically a non-
465 lexical, global variable $j) than one you declared on this line.
466
467 Accessing Perl functions from PARI code
468 Use the same name inside PARI code:
469
470 sub counter { $i += shift; }
471 $i = 145;
472 PARI 'k=5' ;
473 fordiv(28, 'j', 'k=k+counter(j)');
474 print PARI('k'), "\n";
475
476 prints
477
478 984
479
480 Due to a difference in the semantic of variable-number-of-parameters-
481 functions between PARI and Perl, if the Perl subroutine takes a
482 variable number of arguments (via "@" in the prototype or a missing
483 prototype), up to 6 arguments are supported when this function is
484 called from PARI. If called from PARI with fewer arguments, the rest
485 of arguments will be set to be integers "PARI 0".
486
487 Note also that no direct import of Perl variables is available yet (but
488 you can write a function wrapper for this):
489
490 sub getv () {$v}
491
492 There is an unsupported (and undocumented ;-) function for explicitly
493 importing Perl functions into PARI, possibly with a different name, and
494 possibly with explicitly specifying number of arguments.
495
497 Functions from PARI library may take as arguments and/or return values
498 the objects of C type "GEN". In Perl these data are encapsulated into
499 special kind of Perl variables: PARI objects. You can check for a
500 variable $obj to be a PARI object using
501
502 ref $obj and $obj->isa('Math::Pari');
503
504 Most the time you do not need this due to automatic conversions and
505 overloading.
506
508 If very lazy, one can code in Perl the same way one does it in PARI.
509 Variables in PARI are denoted by barewords, as in "x", and in the
510 default configuration (no warnings, no strict) Perl allows the same -
511 up to some extent. Do not do this, since there are many surprising
512 problems.
513
514 Some bareletters denote Perl operators, like "q", "x", "y", "s". This
515 can lead to errors in Perl parsing your expression. E.g.,
516
517 print sin(tan(t))-tan(sin(t))-asin(atan(t))+atan(asin(t));
518
519 may parse OK after "use Math::Pari qw(sin tan asin atan)". Why?
520
521 After importing, the word "sin" will denote the PARI function sin(),
522 not Perl operator sin(). The difference is subtle: the PARI function
523 implicitly forces its arguments to be converted PARI objects; it gets
524 't' as the argument, which is a string, thus is converted to what "t"
525 denotes in PARI - a monomial. While the Perl operator sin() grants
526 overloading (i.e., it will call PARI function sin() if the argument is
527 a PARI object), it does not force its argument; given 't' as argument,
528 it converts it to what sin() understands, a float (producing 0.), so
529 will give 0. as the answer.
530
531 However
532
533 print sin(tan(y))-tan(sin(y))-asin(atan(y))+atan(asin(y));
534
535 would not compile. You should avoid lower-case barewords used as PARI
536 variables, e.g., do
537
538 $y = PARI 'y';
539 print sin(tan($y))-tan(sin($y))-asin(atan($y))+atan(asin($y));
540
541 to get
542
543 -1/18*y^9+26/4725*y^11-41/1296*y^13+328721/16372125*y^15+O(y^16)
544
545 (BTW, it is a very good exercise to get the leading term by hand).
546
547 Well, the same advice again: do not use barewords anywhere in your
548 program!
549
551 Whenever an arithmetic operation includes at least one PARI object, the
552 other arguments are converted to a PARI object and the corresponding
553 PARI library functions is used to implement the operation. Currently
554 the following arithmetic operations are overloaded:
555
556 unary -
557 + - * / % ** abs cos sin exp log sqrt
558 << >>
559 <= == => < > != <=>
560 le eq ge lt gt ne cmp
561 | & ^ ~
562
563 Numeric comparison operations are converted to "gcmp" and friends,
564 string comparisons compare in lexicographical order using "lex".
565
566 Additionally, whenever a PARI object appears in a situation that
567 requires integer, numeric, boolean or string data, it is converted to
568 the corresponding type. Boolean conversion is subject to usual PARI
569 pitfalls related to imprecise zeros (see documentation of "gcmp0" in
570 PARI reference).
571
572 For details on overloading, see overload.
573
574 Note that a check for equality is subject to same pitfalls as in PARI
575 due to imprecise values. PARI may also refuse to compare data of
576 different types for equality if it thinks this may lead to
577 counterintuitive results.
578
579 Note also that in PARI the numeric ordering is not defined for some
580 types of PARI objects. For string comparison operations we use PARI-
581 lexicographical ordering.
582
584 Perl
585 In the versions of perl earlier than 5.003 overloading used a different
586 interface, so you may need to convert "use overload" line to %OVERLOAD,
587 or, better, upgrade.
588
589 PARI
590 Starting from version 2.0, this module comes without a PARI library
591 included.
592
593 For the source of PARI library see
594 <ftp://megrez.math.u-bordeaux.fr/pub/pari>.
595
597 Note that the PARI notations should be used in the string arguments to
598 PARI() function, while the Perl notations should be used otherwise.
599
600 "^" Power is denoted by "**" in Perl.
601
602 "\" and "\/"
603 There are no such operators in Perl, use the word forms
604 "gdivent(x,y)" and "gdivround(x,y)" instead.
605
606 "~" There is no postfix "~" Perl operator. Use mattranspose() instead.
607
608 "'" There is no postfix "'" Perl operator. Use deriv() instead.
609
610 "!" There is no postfix "!" Perl operator. Use factorial()/ifact()
611 instead (returning a real or an integer correspondingly).
612
613 big integers
614 Perl converts big literal integers to doubles if they could not be
615 put into C integers (the particular flavor can be found in the
616 output of "perl -V" in newer version of Perl, look for
617 "ivtype"/"ivsize"). If you want to input such an integer, use
618
619 while ($x < PARI('12345678901234567890')) ...
620
621 instead of
622
623 while ($x < 12345678901234567890) ...
624
625 Why? Because conversion to double leads to precision loss
626 (typically above 1e15, see perlnumber), and you will get something
627 like 12345678901234567168 otherwise.
628
629 Starting from version 5.005 of Perl, if the tag ":int" is used on
630 the 'use Math::Pari' line, all of the integer literals in Perl will
631 be automatically converted to became PARI objects. E.g.,
632
633 use Math::Pari ':int';
634 print 2**1000;
635
636 is equivalent to
637
638 print PARI(2)**PARI(1000);
639
640 Similarly, large integer literals do not lose precision.
641
642 This directive is lexically scoped. There is a similar tag ":hex"
643 which affects hexadecimal, octal and binary constants. One may
644 also need to use tag ":float" for auto-conversion of large integer
645 literals which Perl considers as floating point literals (see
646 ""use" with arguments" for details).
647
648 doubles
649 Doubles in Perl are typically of precision approximately 15 digits
650 (see perlnumber). When you use them as arguments to PARI
651 functions, they are converted to PARI real variables, and due to
652 intermediate 15-digits-to-binary conversion of Perl variables the
653 result may be different than with the PARI many-digits-to-binary
654 conversion. E.g., "PARI(0.01)" and "PARI('0.01')" differ at 19-th
655 place, as
656
657 setprecision(38);
658 print pari_print(0.01), "\n",
659 pari_print('0.01'), "\n";
660
661 shows.
662
663 Note that setprecision() changes the output format of pari_print()
664 and friends, as well as the default internal precision. The
665 generic PARI===>string conversion does not take into account the
666 output format, thus
667
668 setprecision(38);
669 print PARI(0.01), "\n",
670 PARI('0.01'), "\n",
671 pari_print(0.01), "\n";
672
673 will print all the lines with different number of digits after the
674 point: the first one with 22, since the double 0.01 was converted
675 to a low-precision PARI object, the second one with 41, since
676 internal form for precision 38 requires that many digits for
677 representation, and the last one with 39 to have 38 significant
678 digits.
679
680 Starting from version 5.005 of Perl, if the tag ":float" is used on
681 the "use Math::Pari" line, all the float literals in Perl will be
682 automatically converted to became PARI objects. E.g.,
683
684 use Math::Pari ':float';
685 print atan(1.);
686
687 is equivalent to
688
689 print atan(PARI('1.'));
690
691 Similarly, large float literals do not lose precision.
692
693 This directive is lexically scoped.
694
695 array base
696 Arrays are 1-based in PARI, are 0-based in Perl. So while array
697 access is possible in Perl, you need to use different indices:
698
699 $nf = PARI 'nf'; # assume that PARI variable nf contains a number field
700 $a = PARI('nf[7]');
701 $b = $nf->[6];
702
703 Now $a and $b contain the same value.
704
705 matrices
706 Note that "PARImat([[...],...,[...])" constructor creates a matrix
707 with specified columns, while in PARI the command "[1,2,3;4,5,6]"
708 creates a matrix with specified rows. Use a convenience function
709 PARImat_tr() which will transpose a matrix created by PARImat() to
710 use the same order of elements as in PARI.
711
712 builtin perl functions
713 Some PARI functions, like "length" and "eval", are Perl
714 (semi-)reserved words. To reach these functions, one should either
715 import them:
716
717 use Math::Pari qw(length eval);
718
719 or call them with prefix (like &length) or the full name (like
720 "Math::Pari::length").
721
723 If you have Term::Gnuplot Perl module installed, you may use high-
724 resolution graphic primitives of PARI. Before the usage you need to
725 establish a link between Math::Pari and Term::Gnuplot by calling
726 link_gnuplot(). You can change the output filehandle by calling
727 set_plot_fh(), and output terminal by calling plotterm(), as in
728
729 use Math::Pari qw(:graphic asin);
730
731 link_gnuplot(); # automatically loads Term::Gnuplot
732 plotterm('emtex');
733 plot_outfile_set('out.tex'); # better do after plotterm()
734 ploth($x, .5, .999, sub {asin $x});
735 close FH or die;
736
738 libPARI documentation is included, see Math::libPARI. It is converted
739 from Chapter 3 of PARI/GP documentation by the gphelp script of
740 GP/PARI.
741
743 No environment variables are used.
744
746 • A few of PARI functions are available indirectly only.
747
748 • Using overloading constants with the Perl versions below 5.005_57
749 could lead to segfaults (at least without "-D usemymalloc"), as
750 in:
751
752 use Math::Pari ':int';
753 for ( $i = 0; $i < 10 ; $i++ ) { print "$i\n" }
754
755 • It may be possible that conversion of a Perl value which has both
756 the integer slot and the floating slot set may create a PARI
757 integer, even if the actual value is not an integer.
758
759 • problems with refcounting of array elements and Mod().
760
761 Workaround: make the modulus live longer than the result of Mod().
762 Until Perl version 5.6.1, one should exercise a special care so
763 that the modulus goes out of scope on a different statement than
764 the result:
765
766 { my $modulus = 125;
767 { my $res = Mod(34, $modulus);
768 print $res;
769 }
770 $fake = 1; # A (fake) statement here is required
771 }
772
773 Here $res is destructed before the "$fake = 1" statement, $modulus
774 is destructed before the first statement after the provided block.
775 However, if you remove the "$fake = 1" statement, both these
776 variables are destructed on the first statement after the provided
777 block (and in a wrong order!).
778
779 In 5.6.1 declaring $modulus before $res is all that is needed to
780 circumvent the same problem:
781
782 { my $modulus = 125;
783 my $res = Mod(34, $modulus);
784 print $res;
785 } # destruction will happen in a correct order.
786
787 Access to array elements may result in similar problems. Hard to
788 fix since in PARI the data is not refcounted.
789
790 • Legacy implementations of dynalinking require the code of DLL to
791 be compiled to be "position independent" code (PIC). This slows
792 down the execution, while allowing sharing the loaded copy of the
793 DLL between different processes. [On contemporary architectures
794 the same effect is allowed without the position-independent hack.]
795
796 Currently, PARI assembler files are not position-independent.
797 When compiled for the dynamic linking on legacy systems, this
798 creates a DLL which cannot be shared between processes. Some
799 legacy systems are reported to recognize this situation, and load
800 the DLL as a non-shared module. However, there may be systems
801 (are there?) on which this can cause some "problems".
802
803 Summary: if the dynaloading on your system requires some kind of
804 "-fPIC" flag, using "assembler" compiles (anything but
805 "machine=none") *may* force you to do a static build (i.e.,
806 creation of a custom Perl executable with
807
808 perl Makefile.PL static
809 make perl
810 make test_static
811
812 ).
813
814 • isprime() is a misnomer before PARI version 2.3!
815
816 In older versions of PARI, the one-argument variant of the
817 function isprime() is actually checking for probable primes.
818 Moreover, it has certain problems.
819
820 POSSIBLE WORKAROUND (not needed for newer PARI): before version
821 2.3 of PARI, to get probability of misdetecting a prime below
822 1e-12, call isprime() twice; below 1e-18, call it 3 times; etc.
823 (The algorithm is probabilistic, and the implementation is such
824 that the result depends on which calls to isprime() were performed
825 ealier.)
826
827 The problems: first, while the default algorithm (before version
828 2.3) gives practically acceptable results in non-adversarial
829 situations, the worst-case behaviour is significantly worse than
830 the average behaviour. The algorithm is looking for so-called
831 "witnesses" (with up to 10 tries) among random integers; usually,
832 witnesses are abundant. However, there are non-prime numbers for
833 which the fraction of witnesses is close to the theoretical
834 minimum, 0.75; with 10 random tries, the probability of missing a
835 witness for such numbers is close to 1e-6. (The known worst-case
836 numbers M have phi(M)/4 non-witnesses, with M=P(2P-1), prime P,
837 2P-1 and 4|P+1; the proportion of such numbers near K is expected
838 to be const/sqrt(K)log(K)^2. Note that numbers which have more
839 than about 5% non-witnesses may also be candidates for false
840 positives. Conjecturally, they are of the form (aD+1)(bD+1) with
841 a<b, ab <= const, prime aD+1, and bD+1, and D not divisible by
842 high power of 2 (above a=1, b=2 and D is odd); the proportion of
843 such numbers may have a similar asymptotic const/sqrt(K)log(K)^2.)
844
845 Second, the random number generator is "reset to known state" when
846 PARI library is initialized. That means that the behaviour is
847 actually predictable if one knows which calls to isprime() are
848 performed; an adversary can find non-primes M which will trigger a
849 false positive exactly on the Nth call to isprime(M) (for
850 particular values of N). With enough computing resources, one can
851 find non-primes M for which N is relatively small (with M about
852 1e9, one can achieve N as low as 1000). Compare with similar (but
853 less abundant) examples for simpler algorithm, Carmichael numbers
854 <http://en.wikipedia.org/wiki/Carmichael_numbers>; see also
855 numbers with big proportion of non-witnesses
856 <http://oeis.org/A090659> and numbers with many non-witnesses
857 <http://oeis.org/A141768>, and the conjecture about proportion
858 <http://web.archive.org/web/*/http://www.ma.iup.edu/MAA/proceedings/vol1/higgins.pdf>.
859
860 See the discussion of isprime()
861 <https://rt.cpan.org/Public/Bug/Display.html?id=93652>.
862
864 When Math::Pari is loaded, it examines variables $Math::Pari::initmem
865 and $Math::Pari::initprimes. They specify up to which number the
866 initial list of primes should be precalculated, and how large should be
867 the arena for PARI calculations (in bytes). (These values have safe
868 defaults.)
869
870 Since setting these values before loading requires either a "BEGIN"
871 block, or postponing the loading ("use" vs. "require"), it may be more
872 convenient to set them via Math::PariInit:
873
874 use Math::PariInit qw( primes=12000000 stack=1e8 );
875
876 "use Math::PariInit" also accepts arbitrary Math::Pari import
877 directives, see Math::PariInit.
878
879 These values may be changed at runtime too, via allocatemem() and
880 setprimelimit(), with performance penalties for
881 recalculation/reallocation.
882
884 Ilya Zakharevich, ilyaz@cpan.org
885
886
887
888perl v5.34.1 2022-03-30 Pari(3)