1Math::BigRat(3)       User Contributed Perl Documentation      Math::BigRat(3)
2
3
4

NAME

6       Math::BigRat - arbitrary size rational number math package
7

SYNOPSIS

9           use Math::BigRat;
10
11           my $x = Math::BigRat->new('3/7'); $x += '5/9';
12
13           print $x->bstr(), "\n";
14           print $x ** 2, "\n";
15
16           my $y = Math::BigRat->new('inf');
17           print "$y ", ($y->is_inf ? 'is' : 'is not'), " infinity\n";
18
19           my $z = Math::BigRat->new(144); $z->bsqrt();
20

DESCRIPTION

22       Math::BigRat complements Math::BigInt and Math::BigFloat by providing
23       support for arbitrary big rational numbers.
24
25   MATH LIBRARY
26       You can change the underlying module that does the low-level math
27       operations by using:
28
29           use Math::BigRat try => 'GMP';
30
31       Note: This needs Math::BigInt::GMP installed.
32
33       The following would first try to find Math::BigInt::Foo, then
34       Math::BigInt::Bar, and when this also fails, revert to
35       Math::BigInt::Calc:
36
37           use Math::BigRat try => 'Foo,Math::BigInt::Bar';
38
39       If you want to get warned when the fallback occurs, replace "try" with
40       "lib":
41
42           use Math::BigRat lib => 'Foo,Math::BigInt::Bar';
43
44       If you want the code to die instead, replace "try" with "only":
45
46           use Math::BigRat only => 'Foo,Math::BigInt::Bar';
47

METHODS

49       Any methods not listed here are derived from Math::BigFloat (or
50       Math::BigInt), so make sure you check these two modules for further
51       information.
52
53       new()
54               $x = Math::BigRat->new('1/3');
55
56           Create a new Math::BigRat object. Input can come in various forms:
57
58               $x = Math::BigRat->new(123);                            # scalars
59               $x = Math::BigRat->new('inf');                          # infinity
60               $x = Math::BigRat->new('123.3');                        # float
61               $x = Math::BigRat->new('1/3');                          # simple string
62               $x = Math::BigRat->new('1 / 3');                        # spaced
63               $x = Math::BigRat->new('1 / 0.1');                      # w/ floats
64               $x = Math::BigRat->new(Math::BigInt->new(3));           # BigInt
65               $x = Math::BigRat->new(Math::BigFloat->new('3.1'));     # BigFloat
66               $x = Math::BigRat->new(Math::BigInt::Lite->new('2'));   # BigLite
67
68               # You can also give D and N as different objects:
69               $x = Math::BigRat->new(
70                       Math::BigInt->new(-123),
71                       Math::BigInt->new(7),
72                    );                      # => -123/7
73
74       numerator()
75               $n = $x->numerator();
76
77           Returns a copy of the numerator (the part above the line) as signed
78           BigInt.
79
80       denominator()
81               $d = $x->denominator();
82
83           Returns a copy of the denominator (the part under the line) as
84           positive BigInt.
85
86       parts()
87               ($n, $d) = $x->parts();
88
89           Return a list consisting of (signed) numerator and (unsigned)
90           denominator as BigInts.
91
92       dparts()
93           Returns the integer part and the fraction part.
94
95       fparts()
96           Returns the smallest possible numerator and denominator so that the
97           numerator divided by the denominator gives back the original value.
98           For finite numbers, both values are integers. Mnemonic: fraction.
99
100       numify()
101               my $y = $x->numify();
102
103           Returns the object as a scalar. This will lose some data if the
104           object cannot be represented by a normal Perl scalar (integer or
105           float), so use "as_int()" or "as_float()" instead.
106
107           This routine is automatically used whenever a scalar is required:
108
109               my $x = Math::BigRat->new('3/1');
110               @array = (0, 1, 2, 3);
111               $y = $array[$x];                # set $y to 3
112
113       as_int()
114       as_number()
115               $x = Math::BigRat->new('13/7');
116               print $x->as_int(), "\n";               # '1'
117
118           Returns a copy of the object as BigInt, truncated to an integer.
119
120           "as_number()" is an alias for "as_int()".
121
122       as_float()
123               $x = Math::BigRat->new('13/7');
124               print $x->as_float(), "\n";             # '1'
125
126               $x = Math::BigRat->new('2/3');
127               print $x->as_float(5), "\n";            # '0.66667'
128
129           Returns a copy of the object as BigFloat, preserving the accuracy
130           as wanted, or the default of 40 digits.
131
132           This method was added in v0.22 of Math::BigRat (April 2008).
133
134       as_hex()
135               $x = Math::BigRat->new('13');
136               print $x->as_hex(), "\n";               # '0xd'
137
138           Returns the BigRat as hexadecimal string. Works only for integers.
139
140       as_bin()
141               $x = Math::BigRat->new('13');
142               print $x->as_bin(), "\n";               # '0x1101'
143
144           Returns the BigRat as binary string. Works only for integers.
145
146       as_oct()
147               $x = Math::BigRat->new('13');
148               print $x->as_oct(), "\n";               # '015'
149
150           Returns the BigRat as octal string. Works only for integers.
151
152       from_hex()
153               my $h = Math::BigRat->from_hex('0x10');
154
155           Create a BigRat from a hexadecimal number in string form.
156
157       from_oct()
158               my $o = Math::BigRat->from_oct('020');
159
160           Create a BigRat from an octal number in string form.
161
162       from_bin()
163               my $b = Math::BigRat->from_bin('0b10000000');
164
165           Create a BigRat from an binary number in string form.
166
167       bnan()
168               $x = Math::BigRat->bnan();
169
170           Creates a new BigRat object representing NaN (Not A Number).  If
171           used on an object, it will set it to NaN:
172
173               $x->bnan();
174
175       bzero()
176               $x = Math::BigRat->bzero();
177
178           Creates a new BigRat object representing zero.  If used on an
179           object, it will set it to zero:
180
181               $x->bzero();
182
183       binf()
184               $x = Math::BigRat->binf($sign);
185
186           Creates a new BigRat object representing infinity. The optional
187           argument is either '-' or '+', indicating whether you want infinity
188           or minus infinity.  If used on an object, it will set it to
189           infinity:
190
191               $x->binf();
192               $x->binf('-');
193
194       bone()
195               $x = Math::BigRat->bone($sign);
196
197           Creates a new BigRat object representing one. The optional argument
198           is either '-' or '+', indicating whether you want one or minus one.
199           If used on an object, it will set it to one:
200
201               $x->bone();                 # +1
202               $x->bone('-');              # -1
203
204       length()
205               $len = $x->length();
206
207           Return the length of $x in digits for integer values.
208
209       digit()
210               print Math::BigRat->new('123/1')->digit(1);     # 1
211               print Math::BigRat->new('123/1')->digit(-1);    # 3
212
213           Return the N'ths digit from X when X is an integer value.
214
215       bnorm()
216               $x->bnorm();
217
218           Reduce the number to the shortest form. This routine is called
219           automatically whenever it is needed.
220
221       bfac()
222               $x->bfac();
223
224           Calculates the factorial of $x. For instance:
225
226               print Math::BigRat->new('3/1')->bfac(), "\n";   # 1*2*3
227               print Math::BigRat->new('5/1')->bfac(), "\n";   # 1*2*3*4*5
228
229           Works currently only for integers.
230
231       bround()/round()/bfround()
232           Are not yet implemented.
233
234       bmod()
235               $x->bmod($y);
236
237           Returns $x modulo $y. When $x is finite, and $y is finite and non-
238           zero, the result is identical to the remainder after floored
239           division (F-division). If, in addition, both $x and $y are
240           integers, the result is identical to the result from Perl's %
241           operator.
242
243       bmodinv()
244               $x->bmodinv($mod);          # modular multiplicative inverse
245
246           Returns the multiplicative inverse of $x modulo $mod. If
247
248               $y = $x -> copy() -> bmodinv($mod)
249
250           then $y is the number closest to zero, and with the same sign as
251           $mod, satisfying
252
253               ($x * $y) % $mod = 1 % $mod
254
255           If $x and $y are non-zero, they must be relative primes, i.e.,
256           "bgcd($y, $mod)==1". '"NaN"' is returned when no modular
257           multiplicative inverse exists.
258
259       bmodpow()
260               $num->bmodpow($exp,$mod);           # modular exponentiation
261                                                   # ($num**$exp % $mod)
262
263           Returns the value of $num taken to the power $exp in the modulus
264           $mod using binary exponentiation.  "bmodpow" is far superior to
265           writing
266
267               $num ** $exp % $mod
268
269           because it is much faster - it reduces internal variables into the
270           modulus whenever possible, so it operates on smaller numbers.
271
272           "bmodpow" also supports negative exponents.
273
274               bmodpow($num, -1, $mod)
275
276           is exactly equivalent to
277
278               bmodinv($num, $mod)
279
280       bneg()
281               $x->bneg();
282
283           Used to negate the object in-place.
284
285       is_one()
286               print "$x is 1\n" if $x->is_one();
287
288           Return true if $x is exactly one, otherwise false.
289
290       is_zero()
291               print "$x is 0\n" if $x->is_zero();
292
293           Return true if $x is exactly zero, otherwise false.
294
295       is_pos()/is_positive()
296               print "$x is >= 0\n" if $x->is_positive();
297
298           Return true if $x is positive (greater than or equal to zero),
299           otherwise false. Please note that '+inf' is also positive, while
300           'NaN' and '-inf' aren't.
301
302           "is_positive()" is an alias for "is_pos()".
303
304       is_neg()/is_negative()
305               print "$x is < 0\n" if $x->is_negative();
306
307           Return true if $x is negative (smaller than zero), otherwise false.
308           Please note that '-inf' is also negative, while 'NaN' and '+inf'
309           aren't.
310
311           "is_negative()" is an alias for "is_neg()".
312
313       is_int()
314               print "$x is an integer\n" if $x->is_int();
315
316           Return true if $x has a denominator of 1 (e.g. no fraction parts),
317           otherwise false. Please note that '-inf', 'inf' and 'NaN' aren't
318           integer.
319
320       is_odd()
321               print "$x is odd\n" if $x->is_odd();
322
323           Return true if $x is odd, otherwise false.
324
325       is_even()
326               print "$x is even\n" if $x->is_even();
327
328           Return true if $x is even, otherwise false.
329
330       bceil()
331               $x->bceil();
332
333           Set $x to the next bigger integer value (e.g. truncate the number
334           to integer and then increment it by one).
335
336       bfloor()
337               $x->bfloor();
338
339           Truncate $x to an integer value.
340
341       bint()
342               $x->bint();
343
344           Round $x towards zero.
345
346       bsqrt()
347               $x->bsqrt();
348
349           Calculate the square root of $x.
350
351       broot()
352               $x->broot($n);
353
354           Calculate the N'th root of $x.
355
356       badd()
357               $x->badd($y);
358
359           Adds $y to $x and returns the result.
360
361       bmul()
362               $x->bmul($y);
363
364           Multiplies $y to $x and returns the result.
365
366       bsub()
367               $x->bsub($y);
368
369           Subtracts $y from $x and returns the result.
370
371       bdiv()
372               $q = $x->bdiv($y);
373               ($q, $r) = $x->bdiv($y);
374
375           In scalar context, divides $x by $y and returns the result. In list
376           context, does floored division (F-division), returning an integer
377           $q and a remainder $r so that $x = $q * $y + $r. The remainer
378           (modulo) is equal to what is returned by "$x->bmod($y)".
379
380       binv()
381               $x->binv();
382
383           Inverse of $x.
384
385       bdec()
386               $x->bdec();
387
388           Decrements $x by 1 and returns the result.
389
390       binc()
391               $x->binc();
392
393           Increments $x by 1 and returns the result.
394
395       copy()
396               my $z = $x->copy();
397
398           Makes a deep copy of the object.
399
400           Please see the documentation in Math::BigInt for further details.
401
402       bstr()/bsstr()
403               my $x = Math::BigRat->new('8/4');
404               print $x->bstr(), "\n";             # prints 1/2
405               print $x->bsstr(), "\n";            # prints 1/2
406
407           Return a string representing this object.
408
409       bcmp()
410               $x->bcmp($y);
411
412           Compares $x with $y and takes the sign into account.  Returns -1,
413           0, 1 or undef.
414
415       bacmp()
416               $x->bacmp($y);
417
418           Compares $x with $y while ignoring their sign. Returns -1, 0, 1 or
419           undef.
420
421       beq()
422               $x -> beq($y);
423
424           Returns true if and only if $x is equal to $y, and false otherwise.
425
426       bne()
427               $x -> bne($y);
428
429           Returns true if and only if $x is not equal to $y, and false
430           otherwise.
431
432       blt()
433               $x -> blt($y);
434
435           Returns true if and only if $x is equal to $y, and false otherwise.
436
437       ble()
438               $x -> ble($y);
439
440           Returns true if and only if $x is less than or equal to $y, and
441           false otherwise.
442
443       bgt()
444               $x -> bgt($y);
445
446           Returns true if and only if $x is greater than $y, and false
447           otherwise.
448
449       bge()
450               $x -> bge($y);
451
452           Returns true if and only if $x is greater than or equal to $y, and
453           false otherwise.
454
455       blsft()/brsft()
456           Used to shift numbers left/right.
457
458           Please see the documentation in Math::BigInt for further details.
459
460       band()
461               $x->band($y);               # bitwise and
462
463       bior()
464               $x->bior($y);               # bitwise inclusive or
465
466       bxor()
467               $x->bxor($y);               # bitwise exclusive or
468
469       bnot()
470               $x->bnot();                 # bitwise not (two's complement)
471
472       bpow()
473               $x->bpow($y);
474
475           Compute $x ** $y.
476
477           Please see the documentation in Math::BigInt for further details.
478
479       blog()
480               $x->blog($base, $accuracy);         # logarithm of x to the base $base
481
482           If $base is not defined, Euler's number (e) is used:
483
484               print $x->blog(undef, 100);         # log(x) to 100 digits
485
486       bexp()
487               $x->bexp($accuracy);        # calculate e ** X
488
489           Calculates two integers A and B so that A/B is equal to "e ** $x",
490           where "e" is Euler's number.
491
492           This method was added in v0.20 of Math::BigRat (May 2007).
493
494           See also "blog()".
495
496       bnok()
497               $x->bnok($y);               # x over y (binomial coefficient n over k)
498
499           Calculates the binomial coefficient n over k, also called the
500           "choose" function. The result is equivalent to:
501
502               ( n )      n!
503               | - |  = -------
504               ( k )    k!(n-k)!
505
506           This method was added in v0.20 of Math::BigRat (May 2007).
507
508       config()
509               Math::BigRat->config("trap_nan" => 1);      # set
510               $accu = Math::BigRat->config("accuracy");   # get
511
512           Set or get configuration parameter values. Read-only parameters are
513           marked as RO. Read-write parameters are marked as RW. The following
514           parameters are supported.
515
516               Parameter       RO/RW   Description
517                                       Example
518               ============================================================
519               lib             RO      Name of the math backend library
520                                       Math::BigInt::Calc
521               lib_version     RO      Version of the math backend library
522                                       0.30
523               class           RO      The class of config you just called
524                                       Math::BigRat
525               version         RO      version number of the class you used
526                                       0.10
527               upgrade         RW      To which class numbers are upgraded
528                                       undef
529               downgrade       RW      To which class numbers are downgraded
530                                       undef
531               precision       RW      Global precision
532                                       undef
533               accuracy        RW      Global accuracy
534                                       undef
535               round_mode      RW      Global round mode
536                                       even
537               div_scale       RW      Fallback accuracy for div, sqrt etc.
538                                       40
539               trap_nan        RW      Trap NaNs
540                                       undef
541               trap_inf        RW      Trap +inf/-inf
542                                       undef
543

NUMERIC LITERALS

545       After "use Math::BigRat ':constant'" all numeric literals in the given
546       scope are converted to "Math::BigRat" objects. This conversion happens
547       at compile time. Every non-integer is convert to a NaN.
548
549       For example,
550
551           perl -MMath::BigRat=:constant -le 'print 2**150'
552
553       prints the exact value of "2**150". Note that without conversion of
554       constants to objects the expression "2**150" is calculated using Perl
555       scalars, which leads to an inaccurate result.
556
557       Please note that strings are not affected, so that
558
559           use Math::BigRat qw/:constant/;
560
561           $x = "1234567890123456789012345678901234567890"
562                   + "123456789123456789";
563
564       does give you what you expect. You need an explicit Math::BigRat->new()
565       around at least one of the operands. You should also quote large
566       constants to prevent loss of precision:
567
568           use Math::BigRat;
569
570           $x = Math::BigRat->new("1234567889123456789123456789123456789");
571
572       Without the quotes Perl first converts the large number to a floating
573       point constant at compile time, and then converts the result to a
574       Math::BigRat object at run time, which results in an inaccurate result.
575
576   Hexadecimal, octal, and binary floating point literals
577       Perl (and this module) accepts hexadecimal, octal, and binary floating
578       point literals, but use them with care with Perl versions before
579       v5.32.0, because some versions of Perl silently give the wrong result.
580       Below are some examples of different ways to write the number decimal
581       314.
582
583       Hexadecimal floating point literals:
584
585           0x1.3ap+8         0X1.3AP+8
586           0x1.3ap8          0X1.3AP8
587           0x13a0p-4         0X13A0P-4
588
589       Octal floating point literals (with "0" prefix):
590
591           01.164p+8         01.164P+8
592           01.164p8          01.164P8
593           011640p-4         011640P-4
594
595       Octal floating point literals (with "0o" prefix) (requires v5.34.0):
596
597           0o1.164p+8        0O1.164P+8
598           0o1.164p8         0O1.164P8
599           0o11640p-4        0O11640P-4
600
601       Binary floating point literals:
602
603           0b1.0011101p+8    0B1.0011101P+8
604           0b1.0011101p8     0B1.0011101P8
605           0b10011101000p-2  0B10011101000P-2
606

BUGS

608       Please report any bugs or feature requests to "bug-math-bigrat at
609       rt.cpan.org", or through the web interface at
610       <https://rt.cpan.org/Ticket/Create.html?Queue=Math-BigRat> (requires
611       login).  We will be notified, and then you'll automatically be notified
612       of progress on your bug as I make changes.
613

SUPPORT

615       You can find documentation for this module with the perldoc command.
616
617           perldoc Math::BigRat
618
619       You can also look for information at:
620
621       •   GitHub
622
623           <https://github.com/pjacklam/p5-Math-BigRat>
624
625       •   RT: CPAN's request tracker
626
627           <https://rt.cpan.org/Dist/Display.html?Name=Math-BigRat>
628
629       •   MetaCPAN
630
631           <https://metacpan.org/release/Math-BigRat>
632
633       •   CPAN Testers Matrix
634
635           <http://matrix.cpantesters.org/?dist=Math-BigRat>
636
637       •   CPAN Ratings
638
639           <https://cpanratings.perl.org/dist/Math-BigRat>
640

LICENSE

642       This program is free software; you may redistribute it and/or modify it
643       under the same terms as Perl itself.
644

SEE ALSO

646       bigrat, Math::BigFloat and Math::BigInt as well as the backends
647       Math::BigInt::FastCalc, Math::BigInt::GMP, and Math::BigInt::Pari.
648

AUTHORS

650       •   Tels <http://bloodgate.com/> 2001-2009.
651
652       •   Maintained by Peter John Acklam <pjacklam@gmail.com> 2011-
653
654
655
656perl v5.36.0                      2022-07-22                   Math::BigRat(3)
Impressum