1# -*- coding: utf-8-unix -*- 2 3package Math::BigInt; 4 5# 6# "Mike had an infinite amount to do and a negative amount of time in which 7# to do it." - Before and After 8# 9 10# The following hash values are used: 11# value: unsigned int with actual value (as a Math::BigInt::Calc or similar) 12# sign : +, -, NaN, +inf, -inf 13# _a : accuracy 14# _p : precision 15 16# Remember not to take shortcuts ala $xs = $x->{value}; $LIB->foo($xs); since 17# underlying lib might change the reference! 18 19use 5.006001; 20use strict; 21use warnings; 22 23use Carp qw< carp croak >; 24use Scalar::Util qw< blessed >; 25 26our $VERSION = '1.999830'; 27$VERSION =~ tr/_//d; 28 29require Exporter; 30our @ISA = qw(Exporter); 31our @EXPORT_OK = qw(objectify bgcd blcm); 32 33# Inside overload, the first arg is always an object. If the original code had 34# it reversed (like $x = 2 * $y), then the third parameter is true. 35# In some cases (like add, $x = $x + 2 is the same as $x = 2 + $x) this makes 36# no difference, but in some cases it does. 37 38# For overloaded ops with only one argument we simple use $_[0]->copy() to 39# preserve the argument. 40 41# Thus inheritance of overload operators becomes possible and transparent for 42# our subclasses without the need to repeat the entire overload section there. 43 44use overload 45 46 # overload key: with_assign 47 48 '+' => sub { $_[0] -> copy() -> badd($_[1]); }, 49 50 '-' => sub { my $c = $_[0] -> copy(); 51 $_[2] ? $c -> bneg() -> badd($_[1]) 52 : $c -> bsub($_[1]); }, 53 54 '*' => sub { $_[0] -> copy() -> bmul($_[1]); }, 55 56 '/' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bdiv($_[0]) 57 : $_[0] -> copy() -> bdiv($_[1]); }, 58 59 '%' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bmod($_[0]) 60 : $_[0] -> copy() -> bmod($_[1]); }, 61 62 '**' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bpow($_[0]) 63 : $_[0] -> copy() -> bpow($_[1]); }, 64 65 '<<' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> blsft($_[0]) 66 : $_[0] -> copy() -> blsft($_[1]); }, 67 68 '>>' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> brsft($_[0]) 69 : $_[0] -> copy() -> brsft($_[1]); }, 70 71 # overload key: assign 72 73 '+=' => sub { $_[0] -> badd($_[1]); }, 74 75 '-=' => sub { $_[0] -> bsub($_[1]); }, 76 77 '*=' => sub { $_[0] -> bmul($_[1]); }, 78 79 '/=' => sub { scalar $_[0] -> bdiv($_[1]); }, 80 81 '%=' => sub { $_[0] -> bmod($_[1]); }, 82 83 '**=' => sub { $_[0] -> bpow($_[1]); }, 84 85 '<<=' => sub { $_[0] -> blsft($_[1]); }, 86 87 '>>=' => sub { $_[0] -> brsft($_[1]); }, 88 89# 'x=' => sub { }, 90 91# '.=' => sub { }, 92 93 # overload key: num_comparison 94 95 '<' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> blt($_[0]) 96 : $_[0] -> blt($_[1]); }, 97 98 '<=' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> ble($_[0]) 99 : $_[0] -> ble($_[1]); }, 100 101 '>' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bgt($_[0]) 102 : $_[0] -> bgt($_[1]); }, 103 104 '>=' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bge($_[0]) 105 : $_[0] -> bge($_[1]); }, 106 107 '==' => sub { $_[0] -> beq($_[1]); }, 108 109 '!=' => sub { $_[0] -> bne($_[1]); }, 110 111 # overload key: 3way_comparison 112 113 '<=>' => sub { my $cmp = $_[0] -> bcmp($_[1]); 114 defined($cmp) && $_[2] ? -$cmp : $cmp; }, 115 116 'cmp' => sub { $_[2] ? "$_[1]" cmp $_[0] -> bstr() 117 : $_[0] -> bstr() cmp "$_[1]"; }, 118 119 # overload key: str_comparison 120 121# 'lt' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrlt($_[0]) 122# : $_[0] -> bstrlt($_[1]); }, 123# 124# 'le' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrle($_[0]) 125# : $_[0] -> bstrle($_[1]); }, 126# 127# 'gt' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrgt($_[0]) 128# : $_[0] -> bstrgt($_[1]); }, 129# 130# 'ge' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrge($_[0]) 131# : $_[0] -> bstrge($_[1]); }, 132# 133# 'eq' => sub { $_[0] -> bstreq($_[1]); }, 134# 135# 'ne' => sub { $_[0] -> bstrne($_[1]); }, 136 137 # overload key: binary 138 139 '&' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> band($_[0]) 140 : $_[0] -> copy() -> band($_[1]); }, 141 142 '&=' => sub { $_[0] -> band($_[1]); }, 143 144 '|' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bior($_[0]) 145 : $_[0] -> copy() -> bior($_[1]); }, 146 147 '|=' => sub { $_[0] -> bior($_[1]); }, 148 149 '^' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bxor($_[0]) 150 : $_[0] -> copy() -> bxor($_[1]); }, 151 152 '^=' => sub { $_[0] -> bxor($_[1]); }, 153 154# '&.' => sub { }, 155 156# '&.=' => sub { }, 157 158# '|.' => sub { }, 159 160# '|.=' => sub { }, 161 162# '^.' => sub { }, 163 164# '^.=' => sub { }, 165 166 # overload key: unary 167 168 'neg' => sub { $_[0] -> copy() -> bneg(); }, 169 170# '!' => sub { }, 171 172 '~' => sub { $_[0] -> copy() -> bnot(); }, 173 174# '~.' => sub { }, 175 176 # overload key: mutators 177 178 '++' => sub { $_[0] -> binc() }, 179 180 '--' => sub { $_[0] -> bdec() }, 181 182 # overload key: func 183 184 'atan2' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> batan2($_[0]) 185 : $_[0] -> copy() -> batan2($_[1]); }, 186 187 'cos' => sub { $_[0] -> copy() -> bcos(); }, 188 189 'sin' => sub { $_[0] -> copy() -> bsin(); }, 190 191 'exp' => sub { $_[0] -> copy() -> bexp($_[1]); }, 192 193 'abs' => sub { $_[0] -> copy() -> babs(); }, 194 195 'log' => sub { $_[0] -> copy() -> blog(); }, 196 197 'sqrt' => sub { $_[0] -> copy() -> bsqrt(); }, 198 199 'int' => sub { $_[0] -> copy() -> bint(); }, 200 201 # overload key: conversion 202 203 'bool' => sub { $_[0] -> is_zero() ? '' : 1; }, 204 205 '""' => sub { $_[0] -> bstr(); }, 206 207 '0+' => sub { $_[0] -> numify(); }, 208 209 '=' => sub { $_[0] -> copy(); }, 210 211 ; 212 213############################################################################## 214# global constants, flags and accessory 215 216# These vars are public, but their direct usage is not recommended, use the 217# accessor methods instead 218 219our $round_mode = 'even'; # one of 'even', 'odd', '+inf', '-inf', 'zero', 'trunc' or 'common' 220our $accuracy = undef; 221our $precision = undef; 222our $div_scale = 40; 223our $upgrade = undef; # default is no upgrade 224our $downgrade = undef; # default is no downgrade 225 226# These are internally, and not to be used from the outside at all 227 228our $_trap_nan = 0; # are NaNs ok? set w/ config() 229our $_trap_inf = 0; # are infs ok? set w/ config() 230 231my $nan = 'NaN'; # constants for easier life 232 233# Module to do the low level math. 234 235my $DEFAULT_LIB = 'Math::BigInt::Calc'; 236my $LIB; 237 238# Has import() been called yet? Needed to make "require" work. 239 240my $IMPORT = 0; 241 242############################################################################## 243# the old code had $rnd_mode, so we need to support it, too 244 245our $rnd_mode = 'even'; 246 247sub TIESCALAR { 248 my ($class) = @_; 249 bless \$round_mode, $class; 250} 251 252sub FETCH { 253 return $round_mode; 254} 255 256sub STORE { 257 $rnd_mode = $_[0]->round_mode($_[1]); 258} 259 260BEGIN { 261 # tie to enable $rnd_mode to work transparently 262 tie $rnd_mode, 'Math::BigInt'; 263 264 # set up some handy alias names 265 *as_int = \&as_number; 266 *is_pos = \&is_positive; 267 *is_neg = \&is_negative; 268} 269 270############################################################################### 271# Configuration methods 272############################################################################### 273 274sub round_mode { 275 my $self = shift; 276 my $class = ref($self) || $self || __PACKAGE__; 277 278 if (@_) { # setter 279 my $m = shift; 280 croak("The value for 'round_mode' must be defined") 281 unless defined $m; 282 croak("Unknown round mode '$m'") 283 unless $m =~ /^(even|odd|\+inf|\-inf|zero|trunc|common)$/; 284 no strict 'refs'; 285 ${"${class}::round_mode"} = $m; 286 } 287 288 else { # getter 289 no strict 'refs'; 290 my $m = ${"${class}::round_mode"}; 291 defined($m) ? $m : $round_mode; 292 } 293} 294 295sub upgrade { 296 no strict 'refs'; 297 # make Class->upgrade() work 298 my $self = shift; 299 my $class = ref($self) || $self || __PACKAGE__; 300 # need to set new value? 301 if (@_ > 0) { 302 return ${"${class}::upgrade"} = $_[0]; 303 } 304 ${"${class}::upgrade"}; 305} 306 307sub downgrade { 308 no strict 'refs'; 309 # make Class->downgrade() work 310 my $self = shift; 311 my $class = ref($self) || $self || __PACKAGE__; 312 # need to set new value? 313 if (@_ > 0) { 314 return ${"${class}::downgrade"} = $_[0]; 315 } 316 ${"${class}::downgrade"}; 317} 318 319sub div_scale { 320 my $self = shift; 321 my $class = ref($self) || $self || __PACKAGE__; 322 323 if (@_) { # setter 324 my $ds = shift; 325 croak("The value for 'div_scale' must be defined") unless defined $ds; 326 croak("The value for 'div_scale' must be positive") unless $ds > 0; 327 $ds = $ds -> numify() if defined(blessed($ds)); 328 no strict 'refs'; 329 ${"${class}::div_scale"} = $ds; 330 } 331 332 else { # getter 333 no strict 'refs'; 334 my $ds = ${"${class}::div_scale"}; 335 defined($ds) ? $ds : $div_scale; 336 } 337} 338 339sub accuracy { 340 # $x->accuracy($a); ref($x) $a 341 # $x->accuracy(); ref($x) 342 # Class->accuracy(); class 343 # Class->accuracy($a); class $a 344 345 my $x = shift; 346 my $class = ref($x) || $x || __PACKAGE__; 347 348 no strict 'refs'; 349 if (@_ > 0) { 350 my $a = shift; 351 if (defined $a) { 352 $a = $a->numify() if ref($a) && $a->can('numify'); 353 # also croak on non-numerical 354 if (!$a || $a <= 0) { 355 croak('Argument to accuracy must be greater than zero'); 356 } 357 if (int($a) != $a) { 358 croak('Argument to accuracy must be an integer'); 359 } 360 } 361 362 if (ref($x)) { 363 # Set instance variable. 364 $x->bround($a) if $a; # not for undef, 0 365 $x->{_a} = $a; # set/overwrite, even if not rounded 366 delete $x->{_p}; # clear P 367 # Why return class variable here? Fixme! 368 $a = ${"${class}::accuracy"} unless defined $a; # proper return value 369 } else { 370 # Set class variable. 371 ${"${class}::accuracy"} = $a; # set global A 372 ${"${class}::precision"} = undef; # clear global P 373 } 374 375 return $a; # shortcut 376 } 377 378 # Return instance variable. 379 return $x->{_a} if ref($x) && (defined $x->{_a} || defined $x->{_p}); 380 381 # Return class variable. 382 return ${"${class}::accuracy"}; 383} 384 385sub precision { 386 # $x->precision($p); ref($x) $p 387 # $x->precision(); ref($x) 388 # Class->precision(); class 389 # Class->precision($p); class $p 390 391 my $x = shift; 392 my $class = ref($x) || $x || __PACKAGE__; 393 394 no strict 'refs'; 395 if (@_ > 0) { 396 my $p = shift; 397 if (defined $p) { 398 $p = $p->numify() if ref($p) && $p->can('numify'); 399 if ($p != int $p) { 400 croak('Argument to precision must be an integer'); 401 } 402 } 403 404 if (ref($x)) { 405 # Set instance variable. 406 $x->bfround($p) if $p; # not for undef, 0 407 $x->{_p} = $p; # set/overwrite, even if not rounded 408 delete $x->{_a}; # clear A 409 # Why return class variable here? Fixme! 410 $p = ${"${class}::precision"} unless defined $p; # proper return value 411 } else { 412 # Set class variable. 413 ${"${class}::precision"} = $p; # set global P 414 ${"${class}::accuracy"} = undef; # clear global A 415 } 416 417 return $p; # shortcut 418 } 419 420 # Return instance variable. 421 return $x->{_p} if ref($x) && (defined $x->{_a} || defined $x->{_p}); 422 423 # Return class variable. 424 return ${"${class}::precision"}; 425} 426 427sub config { 428 # return (or set) configuration data. 429 my $class = shift || __PACKAGE__; 430 431 no strict 'refs'; 432 if (@_ > 1 || (@_ == 1 && (ref($_[0]) eq 'HASH'))) { 433 # try to set given options as arguments from hash 434 435 my $args = $_[0]; 436 if (ref($args) ne 'HASH') { 437 $args = { @_ }; 438 } 439 # these values can be "set" 440 my $set_args = {}; 441 foreach my $key (qw/ 442 accuracy precision 443 round_mode div_scale 444 upgrade downgrade 445 trap_inf trap_nan 446 /) 447 { 448 $set_args->{$key} = $args->{$key} if exists $args->{$key}; 449 delete $args->{$key}; 450 } 451 if (keys %$args > 0) { 452 croak("Illegal key(s) '", join("', '", keys %$args), 453 "' passed to $class\->config()"); 454 } 455 foreach my $key (keys %$set_args) { 456 if ($key =~ /^trap_(inf|nan)\z/) { 457 ${"${class}::_trap_$1"} = ($set_args->{"trap_$1"} ? 1 : 0); 458 next; 459 } 460 # use a call instead of just setting the $variable to check argument 461 $class->$key($set_args->{$key}); 462 } 463 } 464 465 # now return actual configuration 466 467 my $cfg = { 468 lib => $LIB, 469 lib_version => ${"${LIB}::VERSION"}, 470 class => $class, 471 trap_nan => ${"${class}::_trap_nan"}, 472 trap_inf => ${"${class}::_trap_inf"}, 473 version => ${"${class}::VERSION"}, 474 }; 475 foreach my $key (qw/ 476 accuracy precision 477 round_mode div_scale 478 upgrade downgrade 479 /) 480 { 481 $cfg->{$key} = ${"${class}::$key"}; 482 } 483 if (@_ == 1 && (ref($_[0]) ne 'HASH')) { 484 # calls of the style config('lib') return just this value 485 return $cfg->{$_[0]}; 486 } 487 $cfg; 488} 489 490sub _scale_a { 491 # select accuracy parameter based on precedence, 492 # used by bround() and bfround(), may return undef for scale (means no op) 493 my ($x, $scale, $mode) = @_; 494 495 $scale = $x->{_a} unless defined $scale; 496 497 no strict 'refs'; 498 my $class = ref($x); 499 500 $scale = ${ $class . '::accuracy' } unless defined $scale; 501 $mode = ${ $class . '::round_mode' } unless defined $mode; 502 503 if (defined $scale) { 504 $scale = $scale->can('numify') ? $scale->numify() 505 : "$scale" if ref($scale); 506 $scale = int($scale); 507 } 508 509 ($scale, $mode); 510} 511 512sub _scale_p { 513 # select precision parameter based on precedence, 514 # used by bround() and bfround(), may return undef for scale (means no op) 515 my ($x, $scale, $mode) = @_; 516 517 $scale = $x->{_p} unless defined $scale; 518 519 no strict 'refs'; 520 my $class = ref($x); 521 522 $scale = ${ $class . '::precision' } unless defined $scale; 523 $mode = ${ $class . '::round_mode' } unless defined $mode; 524 525 if (defined $scale) { 526 $scale = $scale->can('numify') ? $scale->numify() 527 : "$scale" if ref($scale); 528 $scale = int($scale); 529 } 530 531 ($scale, $mode); 532} 533 534############################################################################### 535# Constructor methods 536############################################################################### 537 538sub new { 539 # Create a new Math::BigInt object from a string or another Math::BigInt 540 # object. See hash keys documented at top. 541 542 # The argument could be an object, so avoid ||, && etc. on it. This would 543 # cause costly overloaded code to be called. The only allowed ops are ref() 544 # and defined. 545 546 my $self = shift; 547 my $selfref = ref $self; 548 my $class = $selfref || $self; 549 550 # Make "require" work. 551 552 $class -> import() if $IMPORT == 0; 553 554 # Although this use has been discouraged for more than 10 years, people 555 # apparently still use it, so we still support it. 556 557 return $class -> bzero() unless @_; 558 559 my ($wanted, @r) = @_; 560 561 if (!defined($wanted)) { 562 #if (warnings::enabled("uninitialized")) { 563 # warnings::warn("uninitialized", 564 # "Use of uninitialized value in new()"); 565 #} 566 return $class -> bzero(@r); 567 } 568 569 if (!ref($wanted) && $wanted eq "") { 570 #if (warnings::enabled("numeric")) { 571 # warnings::warn("numeric", 572 # q|Argument "" isn't numeric in new()|); 573 #} 574 #return $class -> bzero(@r); 575 return $class -> bnan(@r); 576 } 577 578 # Initialize a new object. 579 580 $self = bless {}, $class; 581 582 # Math::BigInt or subclass 583 584 if (defined(blessed($wanted)) && $wanted -> isa($class)) { 585 586 # We don't copy the accuracy and precision, because a new object should 587 # get them from the global configuration. 588 589 $self -> {sign} = $wanted -> {sign}; 590 $self -> {value} = $LIB -> _copy($wanted -> {value}); 591 $self->round(@r) unless @r >= 2 && !defined($r[0]) && !defined($r[1]); 592 return $self; 593 } 594 595 # Shortcut for non-zero scalar integers with no non-zero exponent. 596 597 if ($wanted =~ / ^ 598 ([+-]?) # optional sign 599 ([1-9][0-9]*) # non-zero significand 600 (\.0*)? # ... with optional zero fraction 601 ([Ee][+-]?0+)? # optional zero exponent 602 \z 603 /x) 604 { 605 my $sgn = $1; 606 my $abs = $2; 607 $self->{sign} = $sgn || '+'; 608 $self->{value} = $LIB->_new($abs); 609 $self->round(@r) unless @r >= 2 && !defined($r[0]) && !defined($r[1]); 610 return $self; 611 } 612 613 # Handle Infs. 614 615 if ($wanted =~ /^\s*([+-]?)inf(inity)?\s*\z/i) { 616 my $sgn = $1 || '+'; 617 $self = $class -> binf($sgn); 618 $self->round(@r) unless @r >= 2 && !defined($r[0]) && !defined($r[1]); 619 return $self; 620 } 621 622 # Handle explicit NaNs (not the ones returned due to invalid input). 623 624 if ($wanted =~ /^\s*([+-]?)nan\s*\z/i) { 625 $self = $class -> bnan(); 626 $self->round(@r) unless @r >= 2 && !defined($r[0]) && !defined($r[1]); 627 return $self; 628 } 629 630 my @parts; 631 632 if ( 633 # Handle hexadecimal numbers. We auto-detect hexadecimal numbers if they 634 # have a "0x", "0X", "x", or "X" prefix, cf. CORE::oct(). 635 636 $wanted =~ /^\s*[+-]?0?[Xx]/ and 637 @parts = $class -> _hex_str_to_lib_parts($wanted) 638 639 or 640 641 # Handle octal numbers. We auto-detect octal numbers if they have a 642 # "0o", "0O", "o", "O" prefix, cf. CORE::oct(). 643 644 $wanted =~ /^\s*[+-]?0?[Oo]/ and 645 @parts = $class -> _oct_str_to_lib_parts($wanted) 646 647 or 648 649 # Handle binary numbers. We auto-detect binary numbers if they have a 650 # "0b", "0B", "b", or "B" prefix, cf. CORE::oct(). 651 652 $wanted =~ /^\s*[+-]?0?[Bb]/ and 653 @parts = $class -> _bin_str_to_lib_parts($wanted) 654 655 or 656 657 # At this point, what is left are decimal numbers that aren't handled 658 # above and octal floating point numbers that don't have any of the 659 # "0o", "0O", "o", or "O" prefixes. First see if it is a decimal number. 660 661 @parts = $class -> _dec_str_to_lib_parts($wanted) 662 or 663 664 # See if it is an octal floating point number. The extra check is 665 # included because _oct_str_to_lib_parts() accepts octal numbers that 666 # don't have a prefix (this is needed to make it work with, e.g., 667 # from_oct() that don't require a prefix). However, Perl requires a 668 # prefix for octal floating point literals. For example, "1p+0" is not 669 # valid, but "01p+0" and "0__1p+0" are. 670 671 $wanted =~ /^\s*[+-]?0_*\d/ and 672 @parts = $class -> _oct_str_to_lib_parts($wanted)) 673 { 674 # The value is an integer iff the exponent is non-negative. 675 676 if ($parts[2] eq '+') { 677 $self -> {sign} = $parts[0]; 678 $self -> {value} = $LIB -> _lsft($parts[1], $parts[3], 10); 679 $self->round(@r) unless @r >= 2 && !defined($r[0]) && !defined($r[1]); 680 return $self; 681 } 682 683 # If we get here, the value is a valid number, but it is not an integer. 684 685 return $upgrade -> new($wanted, @r) if defined $upgrade; 686 return $class -> bnan(); 687 } 688 689 # If we get here, the value is neither a valid decimal, binary, octal, or 690 # hexadecimal number. It is not explicit an Inf or a NaN either. 691 692 return $class -> bnan(); 693} 694 695# Create a Math::BigInt from a decimal string. This is an equivalent to 696# from_hex(), from_oct(), and from_bin(). It is like new() except that it does 697# not accept anything but a string representing a finite decimal number. 698 699sub from_dec { 700 my $self = shift; 701 my $selfref = ref $self; 702 my $class = $selfref || $self; 703 704 # Don't modify constant (read-only) objects. 705 706 return if $selfref && $self->modify('from_dec'); 707 708 my $str = shift; 709 my @r = @_; 710 711 # If called as a class method, initialize a new object. 712 713 $self = $class -> bzero() unless $selfref; 714 715 if (my @parts = $class -> _dec_str_to_lib_parts($str)) { 716 717 # The value is an integer iff the exponent is non-negative. 718 719 if ($parts[2] eq '+') { 720 $self -> {sign} = $parts[0]; 721 $self -> {value} = $LIB -> _lsft($parts[1], $parts[3], 10); 722 return $self -> round(@r); 723 } 724 725 return $upgrade -> new($str, @r) if defined $upgrade; 726 } 727 728 return $self -> bnan(@r); 729} 730 731# Create a Math::BigInt from a hexadecimal string. 732 733sub from_hex { 734 my $self = shift; 735 my $selfref = ref $self; 736 my $class = $selfref || $self; 737 738 # Don't modify constant (read-only) objects. 739 740 return if $selfref && $self->modify('from_hex'); 741 742 my $str = shift; 743 my @r = @_; 744 745 # If called as a class method, initialize a new object. 746 747 $self = $class -> bzero() unless $selfref; 748 749 if (my @parts = $class -> _hex_str_to_lib_parts($str)) { 750 751 # The value is an integer iff the exponent is non-negative. 752 753 if ($parts[2] eq '+') { 754 $self -> {sign} = $parts[0]; 755 $self -> {value} = $LIB -> _lsft($parts[1], $parts[3], 10); 756 return $self -> round(@r); 757 } 758 759 return $upgrade -> new($str, @r) if defined $upgrade; 760 } 761 762 return $self -> bnan(@r); 763} 764 765# Create a Math::BigInt from an octal string. 766 767sub from_oct { 768 my $self = shift; 769 my $selfref = ref $self; 770 my $class = $selfref || $self; 771 772 # Don't modify constant (read-only) objects. 773 774 return if $selfref && $self->modify('from_oct'); 775 776 my $str = shift; 777 my @r = @_; 778 779 # If called as a class method, initialize a new object. 780 781 $self = $class -> bzero() unless $selfref; 782 783 if (my @parts = $class -> _oct_str_to_lib_parts($str)) { 784 785 # The value is an integer iff the exponent is non-negative. 786 787 if ($parts[2] eq '+') { 788 $self -> {sign} = $parts[0]; 789 $self -> {value} = $LIB -> _lsft($parts[1], $parts[3], 10); 790 return $self -> round(@r); 791 } 792 793 return $upgrade -> new($str, @r) if defined $upgrade; 794 } 795 796 return $self -> bnan(@r); 797} 798 799# Create a Math::BigInt from a binary string. 800 801sub from_bin { 802 my $self = shift; 803 my $selfref = ref $self; 804 my $class = $selfref || $self; 805 806 # Don't modify constant (read-only) objects. 807 808 return if $selfref && $self->modify('from_bin'); 809 810 my $str = shift; 811 my @r = @_; 812 813 # If called as a class method, initialize a new object. 814 815 $self = $class -> bzero() unless $selfref; 816 817 if (my @parts = $class -> _bin_str_to_lib_parts($str)) { 818 819 # The value is an integer iff the exponent is non-negative. 820 821 if ($parts[2] eq '+') { 822 $self -> {sign} = $parts[0]; 823 $self -> {value} = $LIB -> _lsft($parts[1], $parts[3], 10); 824 return $self -> round(@r); 825 } 826 827 return $upgrade -> new($str, @r) if defined $upgrade; 828 } 829 830 return $self -> bnan(@r); 831} 832 833# Create a Math::BigInt from a byte string. 834 835sub from_bytes { 836 my $self = shift; 837 my $selfref = ref $self; 838 my $class = $selfref || $self; 839 840 # Don't modify constant (read-only) objects. 841 842 return if $selfref && $self->modify('from_bytes'); 843 844 croak("from_bytes() requires a newer version of the $LIB library.") 845 unless $LIB->can('_from_bytes'); 846 847 my $str = shift; 848 my @r = @_; 849 850 # If called as a class method, initialize a new object. 851 852 $self = $class -> bzero() unless $selfref; 853 $self -> {sign} = '+'; 854 $self -> {value} = $LIB -> _from_bytes($str); 855 return $self -> round(@r); 856} 857 858sub from_base { 859 my $self = shift; 860 my $selfref = ref $self; 861 my $class = $selfref || $self; 862 863 # Don't modify constant (read-only) objects. 864 865 return if $selfref && $self->modify('from_base'); 866 867 my $str = shift; 868 869 my $base = shift; 870 $base = $class->new($base) unless ref($base); 871 872 croak("the base must be a finite integer >= 2") 873 if $base < 2 || ! $base -> is_int(); 874 875 # If called as a class method, initialize a new object. 876 877 $self = $class -> bzero() unless $selfref; 878 879 # If no collating sequence is given, pass some of the conversions to 880 # methods optimized for those cases. 881 882 if (! @_) { 883 return $self -> from_bin($str) if $base == 2; 884 return $self -> from_oct($str) if $base == 8; 885 return $self -> from_hex($str) if $base == 16; 886 if ($base == 10) { 887 my $tmp = $class -> new($str); 888 $self -> {value} = $tmp -> {value}; 889 $self -> {sign} = '+'; 890 } 891 } 892 893 croak("from_base() requires a newer version of the $LIB library.") 894 unless $LIB->can('_from_base'); 895 896 $self -> {sign} = '+'; 897 $self -> {value} 898 = $LIB->_from_base($str, $base -> {value}, @_ ? shift() : ()); 899 return $self; 900} 901 902sub from_base_num { 903 my $self = shift; 904 my $selfref = ref $self; 905 my $class = $selfref || $self; 906 907 # Don't modify constant (read-only) objects. 908 909 return if $selfref && $self->modify('from_base_num'); 910 911 # Make sure we have an array of non-negative, finite, numerical objects. 912 913 my $nums = shift; 914 $nums = [ @$nums ]; # create new reference 915 916 for my $i (0 .. $#$nums) { 917 # Make sure we have an object. 918 $nums -> [$i] = $class -> new($nums -> [$i]) 919 unless ref($nums -> [$i]) && $nums -> [$i] -> isa($class); 920 # Make sure we have a finite, non-negative integer. 921 croak "the elements must be finite non-negative integers" 922 if $nums -> [$i] -> is_neg() || ! $nums -> [$i] -> is_int(); 923 } 924 925 my $base = shift; 926 $base = $class -> new($base) unless ref($base) && $base -> isa($class); 927 928 my @r = @_; 929 930 # If called as a class method, initialize a new object. 931 932 $self = $class -> bzero() unless $selfref; 933 934 croak("from_base_num() requires a newer version of the $LIB library.") 935 unless $LIB->can('_from_base_num'); 936 937 $self -> {sign} = '+'; 938 $self -> {value} = $LIB -> _from_base_num([ map { $_ -> {value} } @$nums ], 939 $base -> {value}); 940 941 return $self -> round(@r); 942} 943 944sub bzero { 945 # create/assign '+0' 946 947 if (@_ == 0) { 948 #carp("Using bzero() as a function is deprecated;", 949 # " use bzero() as a method instead"); 950 unshift @_, __PACKAGE__; 951 } 952 953 my $self = shift; 954 my $selfref = ref $self; 955 my $class = $selfref || $self; 956 957 $self->import() if $IMPORT == 0; # make require work 958 959 # Don't modify constant (read-only) objects. 960 961 return if $selfref && $self->modify('bzero'); 962 963 $self = bless {}, $class unless $selfref; 964 965 $self->{sign} = '+'; 966 $self->{value} = $LIB->_zero(); 967 968 # If rounding parameters are given as arguments, use them. If no rounding 969 # parameters are given, and if called as a class method initialize the new 970 # instance with the class variables. 971 972 if (@_) { 973 croak "can't specify both accuracy and precision" 974 if @_ >= 2 && defined $_[0] && defined $_[1]; 975 $self->{_a} = $_[0]; 976 $self->{_p} = $_[1]; 977 } else { 978 unless($selfref) { 979 $self->{_a} = $class -> accuracy(); 980 $self->{_p} = $class -> precision(); 981 } 982 } 983 984 return $self; 985} 986 987sub bone { 988 # Create or assign '+1' (or -1 if given sign '-'). 989 990 if (@_ == 0 || (defined($_[0]) && ($_[0] eq '+' || $_[0] eq '-'))) { 991 #carp("Using bone() as a function is deprecated;", 992 # " use bone() as a method instead"); 993 unshift @_, __PACKAGE__; 994 } 995 996 my $self = shift; 997 my $selfref = ref $self; 998 my $class = $selfref || $self; 999 1000 $self->import() if $IMPORT == 0; # make require work 1001 1002 # Don't modify constant (read-only) objects. 1003 1004 return if $selfref && $self->modify('bone'); 1005 1006 my $sign = '+'; # default 1007 if (@_) { 1008 $sign = shift; 1009 $sign = $sign =~ /^\s*-/ ? "-" : "+"; 1010 } 1011 1012 $self = bless {}, $class unless $selfref; 1013 1014 $self->{sign} = $sign; 1015 $self->{value} = $LIB->_one(); 1016 1017 # If rounding parameters are given as arguments, use them. If no rounding 1018 # parameters are given, and if called as a class method initialize the new 1019 # instance with the class variables. 1020 1021 if (@_) { 1022 croak "can't specify both accuracy and precision" 1023 if @_ >= 2 && defined $_[0] && defined $_[1]; 1024 $self->{_a} = $_[0]; 1025 $self->{_p} = $_[1]; 1026 } else { 1027 unless($selfref) { 1028 $self->{_a} = $class -> accuracy(); 1029 $self->{_p} = $class -> precision(); 1030 } 1031 } 1032 1033 return $self; 1034} 1035 1036sub binf { 1037 # create/assign a '+inf' or '-inf' 1038 1039 if (@_ == 0 || (defined($_[0]) && !ref($_[0]) && 1040 $_[0] =~ /^\s*[+-](inf(inity)?)?\s*$/)) 1041 { 1042 #carp("Using binf() as a function is deprecated;", 1043 # " use binf() as a method instead"); 1044 unshift @_, __PACKAGE__; 1045 } 1046 1047 my $self = shift; 1048 my $selfref = ref $self; 1049 my $class = $selfref || $self; 1050 1051 { 1052 no strict 'refs'; 1053 if (${"${class}::_trap_inf"}) { 1054 croak("Tried to create +-inf in $class->binf()"); 1055 } 1056 } 1057 1058 $self->import() if $IMPORT == 0; # make require work 1059 1060 # Don't modify constant (read-only) objects. 1061 1062 return if $selfref && $self->modify('binf'); 1063 1064 my $sign = shift; 1065 $sign = defined $sign && $sign =~ /^\s*-/ ? "-" : "+"; 1066 1067 $self = bless {}, $class unless $selfref; 1068 1069 $self -> {sign} = $sign . 'inf'; 1070 $self -> {value} = $LIB -> _zero(); 1071 1072 # If rounding parameters are given as arguments, use them. If no rounding 1073 # parameters are given, and if called as a class method initialize the new 1074 # instance with the class variables. 1075 1076 if (@_) { 1077 croak "can't specify both accuracy and precision" 1078 if @_ >= 2 && defined $_[0] && defined $_[1]; 1079 $self->{_a} = $_[0]; 1080 $self->{_p} = $_[1]; 1081 } else { 1082 unless($selfref) { 1083 $self->{_a} = $class -> accuracy(); 1084 $self->{_p} = $class -> precision(); 1085 } 1086 } 1087 1088 return $self; 1089} 1090 1091sub bnan { 1092 # create/assign a 'NaN' 1093 1094 if (@_ == 0) { 1095 #carp("Using bnan() as a function is deprecated;", 1096 # " use bnan() as a method instead"); 1097 unshift @_, __PACKAGE__; 1098 } 1099 1100 my $self = shift; 1101 my $selfref = ref($self); 1102 my $class = $selfref || $self; 1103 1104 { 1105 no strict 'refs'; 1106 if (${"${class}::_trap_nan"}) { 1107 croak("Tried to create NaN in $class->bnan()"); 1108 } 1109 } 1110 1111 $self->import() if $IMPORT == 0; # make require work 1112 1113 # Don't modify constant (read-only) objects. 1114 1115 return if $selfref && $self->modify('bnan'); 1116 1117 $self = bless {}, $class unless $selfref; 1118 1119 $self -> {sign} = $nan; 1120 $self -> {value} = $LIB -> _zero(); 1121 1122 # If rounding parameters are given as arguments, use them. If no rounding 1123 # parameters are given, and if called as a class method initialize the new 1124 # instance with the class variables. 1125 1126 if (@_) { 1127 croak "can't specify both accuracy and precision" 1128 if @_ >= 2 && defined $_[0] && defined $_[1]; 1129 $self->{_a} = $_[0]; 1130 $self->{_p} = $_[1]; 1131 } else { 1132 unless($selfref) { 1133 $self->{_a} = $class -> accuracy(); 1134 $self->{_p} = $class -> precision(); 1135 } 1136 } 1137 1138 return $self; 1139} 1140 1141sub bpi { 1142 1143 # Called as Argument list 1144 # --------- ------------- 1145 # Math::BigInt->bpi() ("Math::BigInt") 1146 # Math::BigInt->bpi(10) ("Math::BigInt", 10) 1147 # $x->bpi() ($x) 1148 # $x->bpi(10) ($x, 10) 1149 # Math::BigInt::bpi() () 1150 # Math::BigInt::bpi(10) (10) 1151 # 1152 # In ambiguous cases, we favour the OO-style, so the following case 1153 # 1154 # $n = Math::BigInt->new("10"); 1155 # $x = Math::BigInt->bpi($n); 1156 # 1157 # which gives an argument list with the single element $n, is resolved as 1158 # 1159 # $n->bpi(); 1160 1161 my $self = shift; 1162 my $selfref = ref $self; 1163 my $class = $selfref || $self; 1164 1165 my @r; # rounding paramters 1166 1167 # If bpi() is called as a function ... 1168 # 1169 # This cludge is necessary because we still support bpi() as a function. If 1170 # bpi() is called with either no argument or one argument, and that one 1171 # argument is either undefined or a scalar that looks like a number, then 1172 # we assume bpi() is called as a function. 1173 1174 if (@_ == 0 && 1175 (defined($self) && !ref($self) && $self =~ /^\s*[+-]?\d/) 1176 || 1177 !defined($self)) 1178 { 1179 $r[0] = $self; 1180 $class = __PACKAGE__; 1181 $self = bless {}, $class; 1182 } 1183 1184 # ... or if bpi() is called as a method ... 1185 1186 else { 1187 @r = @_; 1188 if ($selfref) { # bpi() called as instance method 1189 return $self if $self -> modify('bpi'); 1190 } else { # bpi() called as class method 1191 $self = bless {}, $class; 1192 } 1193 } 1194 1195 return $upgrade -> bpi(@r) if defined $upgrade; 1196 1197 # hard-wired to "3" 1198 $self -> {sign} = '+'; 1199 $self -> {value} = $LIB -> _new("3"); 1200 $self -> round(@r) unless @r >= 2 && !defined($r[0]) && !defined($r[1]); 1201 return $self; 1202} 1203 1204sub copy { 1205 my $self = shift; 1206 my $selfref = ref $self; 1207 my $class = $selfref || $self; 1208 1209 # If called as a class method, the object to copy is the next argument. 1210 1211 $self = shift() unless $selfref; 1212 1213 my $copy = bless {}, $class; 1214 1215 $copy->{sign} = $self->{sign}; 1216 $copy->{value} = $LIB->_copy($self->{value}); 1217 $copy->{_a} = $self->{_a} if exists $self->{_a}; 1218 $copy->{_p} = $self->{_p} if exists $self->{_p}; 1219 1220 return $copy; 1221} 1222 1223sub as_number { 1224 # An object might be asked to return itself as bigint on certain overloaded 1225 # operations. This does exactly this, so that sub classes can simple inherit 1226 # it or override with their own integer conversion routine. 1227 $_[0]->copy(); 1228} 1229 1230############################################################################### 1231# Boolean methods 1232############################################################################### 1233 1234sub is_zero { 1235 # return true if arg (BINT or num_str) is zero (array '+', '0') 1236 my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); 1237 1238 return 0 if $x->{sign} !~ /^\+$/; # -, NaN & +-inf aren't 1239 $LIB->_is_zero($x->{value}); 1240} 1241 1242sub is_one { 1243 # return true if arg (BINT or num_str) is +1, or -1 if sign is given 1244 my ($class, $x, $sign) = ref($_[0]) ? (undef, @_) : objectify(1, @_); 1245 1246 $sign = '+' if !defined $sign || $sign ne '-'; 1247 1248 return 0 if $x->{sign} ne $sign; # -1 != +1, NaN, +-inf aren't either 1249 $LIB->_is_one($x->{value}); 1250} 1251 1252sub is_finite { 1253 my $x = shift; 1254 return $x->{sign} eq '+' || $x->{sign} eq '-'; 1255} 1256 1257sub is_inf { 1258 # return true if arg (BINT or num_str) is +-inf 1259 my ($class, $x, $sign) = ref($_[0]) ? (undef, @_) : objectify(1, @_); 1260 1261 if (defined $sign) { 1262 $sign = '[+-]inf' if $sign eq ''; # +- doesn't matter, only that's inf 1263 $sign = "[$1]inf" if $sign =~ /^([+-])(inf)?$/; # extract '+' or '-' 1264 return $x->{sign} =~ /^$sign$/ ? 1 : 0; 1265 } 1266 $x->{sign} =~ /^[+-]inf$/ ? 1 : 0; # only +-inf is infinity 1267} 1268 1269sub is_nan { 1270 # return true if arg (BINT or num_str) is NaN 1271 my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); 1272 1273 $x->{sign} eq $nan ? 1 : 0; 1274} 1275 1276sub is_positive { 1277 # return true when arg (BINT or num_str) is positive (> 0) 1278 my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); 1279 1280 return 1 if $x->{sign} eq '+inf'; # +inf is positive 1281 1282 # 0+ is neither positive nor negative 1283 ($x->{sign} eq '+' && !$x->is_zero()) ? 1 : 0; 1284} 1285 1286sub is_negative { 1287 # return true when arg (BINT or num_str) is negative (< 0) 1288 my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); 1289 1290 $x->{sign} =~ /^-/ ? 1 : 0; # -inf is negative, but NaN is not 1291} 1292 1293sub is_non_negative { 1294 # Return true if argument is non-negative (>= 0). 1295 my ($class, $x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_); 1296 1297 return 1 if $x->{sign} =~ /^\+/; 1298 return 1 if $x -> is_zero(); 1299 return 0; 1300} 1301 1302sub is_non_positive { 1303 # Return true if argument is non-positive (<= 0). 1304 my ($class, $x) = ref($_[0]) ? (undef,$_[0]) : objectify(1,@_); 1305 1306 return 1 if $x->{sign} =~ /^\-/; 1307 return 1 if $x -> is_zero(); 1308 return 0; 1309} 1310 1311sub is_odd { 1312 # return true when arg (BINT or num_str) is odd, false for even 1313 my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); 1314 1315 return 0 if $x->{sign} !~ /^[+-]$/; # NaN & +-inf aren't 1316 $LIB->_is_odd($x->{value}); 1317} 1318 1319sub is_even { 1320 # return true when arg (BINT or num_str) is even, false for odd 1321 my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); 1322 1323 return 0 if $x->{sign} !~ /^[+-]$/; # NaN & +-inf aren't 1324 $LIB->_is_even($x->{value}); 1325} 1326 1327sub is_int { 1328 # return true when arg (BINT or num_str) is an integer 1329 # always true for Math::BigInt, but different for Math::BigFloat objects 1330 my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); 1331 1332 $x->{sign} =~ /^[+-]$/ ? 1 : 0; # inf/-inf/NaN aren't 1333} 1334 1335############################################################################### 1336# Comparison methods 1337############################################################################### 1338 1339sub bcmp { 1340 # Compares 2 values. Returns one of undef, <0, =0, >0. (suitable for sort) 1341 # (BINT or num_str, BINT or num_str) return cond_code 1342 1343 # set up parameters 1344 my ($class, $x, $y) = ref($_[0]) && ref($_[0]) eq ref($_[1]) 1345 ? (ref($_[0]), @_) 1346 : objectify(2, @_); 1347 1348 return $upgrade->bcmp($x, $y) if defined $upgrade && 1349 ((!$x->isa($class)) || (!$y->isa($class))); 1350 1351 if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/)) { 1352 # handle +-inf and NaN 1353 return if (($x->{sign} eq $nan) || ($y->{sign} eq $nan)); 1354 return 0 if $x->{sign} eq $y->{sign} && $x->{sign} =~ /^[+-]inf$/; 1355 return +1 if $x->{sign} eq '+inf'; 1356 return -1 if $x->{sign} eq '-inf'; 1357 return -1 if $y->{sign} eq '+inf'; 1358 return +1; 1359 } 1360 # check sign for speed first 1361 return 1 if $x->{sign} eq '+' && $y->{sign} eq '-'; # does also 0 <=> -y 1362 return -1 if $x->{sign} eq '-' && $y->{sign} eq '+'; # does also -x <=> 0 1363 1364 # have same sign, so compare absolute values. Don't make tests for zero 1365 # here because it's actually slower than testing in Calc (especially w/ Pari 1366 # et al) 1367 1368 # post-normalized compare for internal use (honors signs) 1369 if ($x->{sign} eq '+') { 1370 # $x and $y both > 0 1371 return $LIB->_acmp($x->{value}, $y->{value}); 1372 } 1373 1374 # $x && $y both < 0 1375 $LIB->_acmp($y->{value}, $x->{value}); # swapped acmp (lib returns 0, 1, -1) 1376} 1377 1378sub bacmp { 1379 # Compares 2 values, ignoring their signs. 1380 # Returns one of undef, <0, =0, >0. (suitable for sort) 1381 # (BINT, BINT) return cond_code 1382 1383 # set up parameters 1384 my ($class, $x, $y) = ref($_[0]) && ref($_[0]) eq ref($_[1]) 1385 ? (ref($_[0]), @_) 1386 : objectify(2, @_); 1387 1388 return $upgrade->bacmp($x, $y) if defined $upgrade && 1389 ((!$x->isa($class)) || (!$y->isa($class))); 1390 1391 if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/)) { 1392 # handle +-inf and NaN 1393 return if (($x->{sign} eq $nan) || ($y->{sign} eq $nan)); 1394 return 0 if $x->{sign} =~ /^[+-]inf$/ && $y->{sign} =~ /^[+-]inf$/; 1395 return 1 if $x->{sign} =~ /^[+-]inf$/ && $y->{sign} !~ /^[+-]inf$/; 1396 return -1; 1397 } 1398 $LIB->_acmp($x->{value}, $y->{value}); # lib does only 0, 1, -1 1399} 1400 1401sub beq { 1402 my $self = shift; 1403 my $selfref = ref $self; 1404 1405 croak 'beq() is an instance method, not a class method' unless $selfref; 1406 croak 'Wrong number of arguments for beq()' unless @_ == 1; 1407 1408 my $cmp = $self -> bcmp(shift); 1409 return defined($cmp) && ! $cmp; 1410} 1411 1412sub bne { 1413 my $self = shift; 1414 my $selfref = ref $self; 1415 1416 croak 'bne() is an instance method, not a class method' unless $selfref; 1417 croak 'Wrong number of arguments for bne()' unless @_ == 1; 1418 1419 my $cmp = $self -> bcmp(shift); 1420 return defined($cmp) && ! $cmp ? '' : 1; 1421} 1422 1423sub blt { 1424 my $self = shift; 1425 my $selfref = ref $self; 1426 1427 croak 'blt() is an instance method, not a class method' unless $selfref; 1428 croak 'Wrong number of arguments for blt()' unless @_ == 1; 1429 1430 my $cmp = $self -> bcmp(shift); 1431 return defined($cmp) && $cmp < 0; 1432} 1433 1434sub ble { 1435 my $self = shift; 1436 my $selfref = ref $self; 1437 1438 croak 'ble() is an instance method, not a class method' unless $selfref; 1439 croak 'Wrong number of arguments for ble()' unless @_ == 1; 1440 1441 my $cmp = $self -> bcmp(shift); 1442 return defined($cmp) && $cmp <= 0; 1443} 1444 1445sub bgt { 1446 my $self = shift; 1447 my $selfref = ref $self; 1448 1449 croak 'bgt() is an instance method, not a class method' unless $selfref; 1450 croak 'Wrong number of arguments for bgt()' unless @_ == 1; 1451 1452 my $cmp = $self -> bcmp(shift); 1453 return defined($cmp) && $cmp > 0; 1454} 1455 1456sub bge { 1457 my $self = shift; 1458 my $selfref = ref $self; 1459 1460 croak 'bge() is an instance method, not a class method' 1461 unless $selfref; 1462 croak 'Wrong number of arguments for bge()' unless @_ == 1; 1463 1464 my $cmp = $self -> bcmp(shift); 1465 return defined($cmp) && $cmp >= 0; 1466} 1467 1468############################################################################### 1469# Arithmetic methods 1470############################################################################### 1471 1472sub bneg { 1473 # (BINT or num_str) return BINT 1474 # negate number or make a negated number from string 1475 my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); 1476 1477 return $x if $x->modify('bneg'); 1478 1479 # for +0 do not negate (to have always normalized +0). Does nothing for 'NaN' 1480 $x->{sign} =~ tr/+-/-+/ unless ($x->{sign} eq '+' && $LIB->_is_zero($x->{value})); 1481 $x; 1482} 1483 1484sub babs { 1485 # (BINT or num_str) return BINT 1486 # make number absolute, or return absolute BINT from string 1487 my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); 1488 1489 return $x if $x->modify('babs'); 1490 # post-normalized abs for internal use (does nothing for NaN) 1491 $x->{sign} =~ s/^-/+/; 1492 $x; 1493} 1494 1495sub bsgn { 1496 # Signum function. 1497 1498 my $self = shift; 1499 1500 return $self if $self->modify('bsgn'); 1501 1502 return $self -> bone("+") if $self -> is_pos(); 1503 return $self -> bone("-") if $self -> is_neg(); 1504 return $self; # zero or NaN 1505} 1506 1507sub bnorm { 1508 # (numstr or BINT) return BINT 1509 # Normalize number -- no-op here 1510 my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); 1511 $x; 1512} 1513 1514sub binc { 1515 # increment arg by one 1516 my ($class, $x, $a, $p, $r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_); 1517 return $x if $x->modify('binc'); 1518 1519 if ($x->{sign} eq '+') { 1520 $x->{value} = $LIB->_inc($x->{value}); 1521 return $x->round($a, $p, $r); 1522 } elsif ($x->{sign} eq '-') { 1523 $x->{value} = $LIB->_dec($x->{value}); 1524 $x->{sign} = '+' if $LIB->_is_zero($x->{value}); # -1 +1 => -0 => +0 1525 return $x->round($a, $p, $r); 1526 } 1527 # inf, nan handling etc 1528 $x->badd($class->bone(), $a, $p, $r); # badd does round 1529} 1530 1531sub bdec { 1532 # decrement arg by one 1533 my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_); 1534 return $x if $x->modify('bdec'); 1535 1536 if ($x->{sign} eq '-') { 1537 # x already < 0 1538 $x->{value} = $LIB->_inc($x->{value}); 1539 } else { 1540 return $x->badd($class->bone('-'), @r) 1541 unless $x->{sign} eq '+'; # inf or NaN 1542 # >= 0 1543 if ($LIB->_is_zero($x->{value})) { 1544 # == 0 1545 $x->{value} = $LIB->_one(); 1546 $x->{sign} = '-'; # 0 => -1 1547 } else { 1548 # > 0 1549 $x->{value} = $LIB->_dec($x->{value}); 1550 } 1551 } 1552 $x->round(@r); 1553} 1554 1555#sub bstrcmp { 1556# my $self = shift; 1557# my $selfref = ref $self; 1558# my $class = $selfref || $self; 1559# 1560# croak 'bstrcmp() is an instance method, not a class method' 1561# unless $selfref; 1562# croak 'Wrong number of arguments for bstrcmp()' unless @_ == 1; 1563# 1564# return $self -> bstr() CORE::cmp shift; 1565#} 1566# 1567#sub bstreq { 1568# my $self = shift; 1569# my $selfref = ref $self; 1570# my $class = $selfref || $self; 1571# 1572# croak 'bstreq() is an instance method, not a class method' 1573# unless $selfref; 1574# croak 'Wrong number of arguments for bstreq()' unless @_ == 1; 1575# 1576# my $cmp = $self -> bstrcmp(shift); 1577# return defined($cmp) && ! $cmp; 1578#} 1579# 1580#sub bstrne { 1581# my $self = shift; 1582# my $selfref = ref $self; 1583# my $class = $selfref || $self; 1584# 1585# croak 'bstrne() is an instance method, not a class method' 1586# unless $selfref; 1587# croak 'Wrong number of arguments for bstrne()' unless @_ == 1; 1588# 1589# my $cmp = $self -> bstrcmp(shift); 1590# return defined($cmp) && ! $cmp ? '' : 1; 1591#} 1592# 1593#sub bstrlt { 1594# my $self = shift; 1595# my $selfref = ref $self; 1596# my $class = $selfref || $self; 1597# 1598# croak 'bstrlt() is an instance method, not a class method' 1599# unless $selfref; 1600# croak 'Wrong number of arguments for bstrlt()' unless @_ == 1; 1601# 1602# my $cmp = $self -> bstrcmp(shift); 1603# return defined($cmp) && $cmp < 0; 1604#} 1605# 1606#sub bstrle { 1607# my $self = shift; 1608# my $selfref = ref $self; 1609# my $class = $selfref || $self; 1610# 1611# croak 'bstrle() is an instance method, not a class method' 1612# unless $selfref; 1613# croak 'Wrong number of arguments for bstrle()' unless @_ == 1; 1614# 1615# my $cmp = $self -> bstrcmp(shift); 1616# return defined($cmp) && $cmp <= 0; 1617#} 1618# 1619#sub bstrgt { 1620# my $self = shift; 1621# my $selfref = ref $self; 1622# my $class = $selfref || $self; 1623# 1624# croak 'bstrgt() is an instance method, not a class method' 1625# unless $selfref; 1626# croak 'Wrong number of arguments for bstrgt()' unless @_ == 1; 1627# 1628# my $cmp = $self -> bstrcmp(shift); 1629# return defined($cmp) && $cmp > 0; 1630#} 1631# 1632#sub bstrge { 1633# my $self = shift; 1634# my $selfref = ref $self; 1635# my $class = $selfref || $self; 1636# 1637# croak 'bstrge() is an instance method, not a class method' 1638# unless $selfref; 1639# croak 'Wrong number of arguments for bstrge()' unless @_ == 1; 1640# 1641# my $cmp = $self -> bstrcmp(shift); 1642# return defined($cmp) && $cmp >= 0; 1643#} 1644 1645sub badd { 1646 1647 # add second arg (BINT or string) to first (BINT) (modifies first) 1648 # return result as BINT 1649 1650 # set up parameters 1651 my ($class, $x, $y, @r) = (ref($_[0]), @_); 1652 # objectify is costly, so avoid it 1653 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { 1654 ($class, $x, $y, @r) = objectify(2, @_); 1655 } 1656 1657 return $x if $x->modify('badd'); 1658 return $upgrade->badd($upgrade->new($x), $upgrade->new($y), @r) if defined $upgrade && 1659 ((!$x->isa($class)) || (!$y->isa($class))); 1660 1661 $r[3] = $y; # no push! 1662 # inf and NaN handling 1663 if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/) { 1664 # NaN first 1665 return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan)); 1666 # inf handling 1667 if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/)) { 1668 # +inf++inf or -inf+-inf => same, rest is NaN 1669 return $x if $x->{sign} eq $y->{sign}; 1670 return $x->bnan(); 1671 } 1672 # +-inf + something => +inf 1673 # something +-inf => +-inf 1674 $x->{sign} = $y->{sign}, return $x if $y->{sign} =~ /^[+-]inf$/; 1675 return $x; 1676 } 1677 1678 my ($sx, $sy) = ($x->{sign}, $y->{sign}); # get signs 1679 1680 if ($sx eq $sy) { 1681 $x->{value} = $LIB->_add($x->{value}, $y->{value}); # same sign, abs add 1682 } else { 1683 my $a = $LIB->_acmp ($y->{value}, $x->{value}); # absolute compare 1684 if ($a > 0) { 1685 $x->{value} = $LIB->_sub($y->{value}, $x->{value}, 1); # abs sub w/ swap 1686 $x->{sign} = $sy; 1687 } elsif ($a == 0) { 1688 # speedup, if equal, set result to 0 1689 $x->{value} = $LIB->_zero(); 1690 $x->{sign} = '+'; 1691 } else # a < 0 1692 { 1693 $x->{value} = $LIB->_sub($x->{value}, $y->{value}); # abs sub 1694 } 1695 } 1696 $x->round(@r); 1697} 1698 1699sub bsub { 1700 # (BINT or num_str, BINT or num_str) return BINT 1701 # subtract second arg from first, modify first 1702 1703 # set up parameters 1704 my ($class, $x, $y, @r) = (ref($_[0]), @_); 1705 1706 # objectify is costly, so avoid it 1707 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { 1708 ($class, $x, $y, @r) = objectify(2, @_); 1709 } 1710 1711 return $x if $x -> modify('bsub'); 1712 1713 return $upgrade -> bsub($upgrade -> new($x), $upgrade -> new($y), @r) 1714 if defined $upgrade && (!$x -> isa($class) || !$y -> isa($class)); 1715 1716 return $x -> round(@r) if $y -> is_zero(); 1717 1718 # To correctly handle the lone special case $x -> bsub($x), we note the 1719 # sign of $x, then flip the sign from $y, and if the sign of $x did change, 1720 # too, then we caught the special case: 1721 1722 my $xsign = $x -> {sign}; 1723 $y -> {sign} =~ tr/+-/-+/; # does nothing for NaN 1724 if ($xsign ne $x -> {sign}) { 1725 # special case of $x -> bsub($x) results in 0 1726 return $x -> bzero(@r) if $xsign =~ /^[+-]$/; 1727 return $x -> bnan(); # NaN, -inf, +inf 1728 } 1729 $x -> badd($y, @r); # badd does not leave internal zeros 1730 $y -> {sign} =~ tr/+-/-+/; # refix $y (does nothing for NaN) 1731 $x; # already rounded by badd() or no rounding 1732} 1733 1734sub bmul { 1735 # multiply the first number by the second number 1736 # (BINT or num_str, BINT or num_str) return BINT 1737 1738 # set up parameters 1739 my ($class, $x, $y, @r) = (ref($_[0]), @_); 1740 # objectify is costly, so avoid it 1741 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { 1742 ($class, $x, $y, @r) = objectify(2, @_); 1743 } 1744 1745 return $x if $x->modify('bmul'); 1746 1747 return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan)); 1748 1749 # inf handling 1750 if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/)) { 1751 return $x->bnan() if $x->is_zero() || $y->is_zero(); 1752 # result will always be +-inf: 1753 # +inf * +/+inf => +inf, -inf * -/-inf => +inf 1754 # +inf * -/-inf => -inf, -inf * +/+inf => -inf 1755 return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/); 1756 return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/); 1757 return $x->binf('-'); 1758 } 1759 1760 return $upgrade->bmul($x, $upgrade->new($y), @r) 1761 if defined $upgrade && !$y->isa($class); 1762 1763 $r[3] = $y; # no push here 1764 1765 $x->{sign} = $x->{sign} eq $y->{sign} ? '+' : '-'; # +1 * +1 or -1 * -1 => + 1766 1767 $x->{value} = $LIB->_mul($x->{value}, $y->{value}); # do actual math 1768 $x->{sign} = '+' if $LIB->_is_zero($x->{value}); # no -0 1769 1770 $x->round(@r); 1771} 1772 1773sub bmuladd { 1774 # multiply two numbers and then add the third to the result 1775 # (BINT or num_str, BINT or num_str, BINT or num_str) return BINT 1776 1777 # set up parameters 1778 my ($class, $x, $y, $z, @r) = objectify(3, @_); 1779 1780 return $x if $x->modify('bmuladd'); 1781 1782 return $x->bnan() if (($x->{sign} eq $nan) || 1783 ($y->{sign} eq $nan) || 1784 ($z->{sign} eq $nan)); 1785 1786 # inf handling of x and y 1787 if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/)) { 1788 return $x->bnan() if $x->is_zero() || $y->is_zero(); 1789 # result will always be +-inf: 1790 # +inf * +/+inf => +inf, -inf * -/-inf => +inf 1791 # +inf * -/-inf => -inf, -inf * +/+inf => -inf 1792 return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/); 1793 return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/); 1794 return $x->binf('-'); 1795 } 1796 # inf handling x*y and z 1797 if (($z->{sign} =~ /^[+-]inf$/)) { 1798 # something +-inf => +-inf 1799 $x->{sign} = $z->{sign}, return $x if $z->{sign} =~ /^[+-]inf$/; 1800 } 1801 1802 return $upgrade->bmuladd($x, $upgrade->new($y), $upgrade->new($z), @r) 1803 if defined $upgrade && (!$y->isa($class) || !$z->isa($class) || !$x->isa($class)); 1804 1805 # TODO: what if $y and $z have A or P set? 1806 $r[3] = $z; # no push here 1807 1808 $x->{sign} = $x->{sign} eq $y->{sign} ? '+' : '-'; # +1 * +1 or -1 * -1 => + 1809 1810 $x->{value} = $LIB->_mul($x->{value}, $y->{value}); # do actual math 1811 $x->{sign} = '+' if $LIB->_is_zero($x->{value}); # no -0 1812 1813 my ($sx, $sz) = ( $x->{sign}, $z->{sign} ); # get signs 1814 1815 if ($sx eq $sz) { 1816 $x->{value} = $LIB->_add($x->{value}, $z->{value}); # same sign, abs add 1817 } else { 1818 my $a = $LIB->_acmp ($z->{value}, $x->{value}); # absolute compare 1819 if ($a > 0) { 1820 $x->{value} = $LIB->_sub($z->{value}, $x->{value}, 1); # abs sub w/ swap 1821 $x->{sign} = $sz; 1822 } elsif ($a == 0) { 1823 # speedup, if equal, set result to 0 1824 $x->{value} = $LIB->_zero(); 1825 $x->{sign} = '+'; 1826 } else # a < 0 1827 { 1828 $x->{value} = $LIB->_sub($x->{value}, $z->{value}); # abs sub 1829 } 1830 } 1831 $x->round(@r); 1832} 1833 1834sub bdiv { 1835 # This does floored division, where the quotient is floored, i.e., rounded 1836 # towards negative infinity. As a consequence, the remainder has the same 1837 # sign as the divisor. 1838 1839 # Set up parameters. 1840 my ($class, $x, $y, @r) = (ref($_[0]), @_); 1841 1842 # objectify() is costly, so avoid it if we can. 1843 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { 1844 ($class, $x, $y, @r) = objectify(2, @_); 1845 } 1846 1847 return $x if $x -> modify('bdiv'); 1848 1849 my $wantarray = wantarray; # call only once 1850 1851 # At least one argument is NaN. Return NaN for both quotient and the 1852 # modulo/remainder. 1853 1854 if ($x -> is_nan() || $y -> is_nan()) { 1855 return $wantarray ? ($x -> bnan(), $class -> bnan()) : $x -> bnan(); 1856 } 1857 1858 # Divide by zero and modulo zero. 1859 # 1860 # Division: Use the common convention that x / 0 is inf with the same sign 1861 # as x, except when x = 0, where we return NaN. This is also what earlier 1862 # versions did. 1863 # 1864 # Modulo: In modular arithmetic, the congruence relation z = x (mod y) 1865 # means that there is some integer k such that z - x = k y. If y = 0, we 1866 # get z - x = 0 or z = x. This is also what earlier versions did, except 1867 # that 0 % 0 returned NaN. 1868 # 1869 # inf / 0 = inf inf % 0 = inf 1870 # 5 / 0 = inf 5 % 0 = 5 1871 # 0 / 0 = NaN 0 % 0 = 0 1872 # -5 / 0 = -inf -5 % 0 = -5 1873 # -inf / 0 = -inf -inf % 0 = -inf 1874 1875 if ($y -> is_zero()) { 1876 my $rem; 1877 if ($wantarray) { 1878 $rem = $x -> copy(); 1879 } 1880 if ($x -> is_zero()) { 1881 $x -> bnan(); 1882 } else { 1883 $x -> binf($x -> {sign}); 1884 } 1885 return $wantarray ? ($x, $rem) : $x; 1886 } 1887 1888 # Numerator (dividend) is +/-inf, and denominator is finite and non-zero. 1889 # The divide by zero cases are covered above. In all of the cases listed 1890 # below we return the same as core Perl. 1891 # 1892 # inf / -inf = NaN inf % -inf = NaN 1893 # inf / -5 = -inf inf % -5 = NaN 1894 # inf / 5 = inf inf % 5 = NaN 1895 # inf / inf = NaN inf % inf = NaN 1896 # 1897 # -inf / -inf = NaN -inf % -inf = NaN 1898 # -inf / -5 = inf -inf % -5 = NaN 1899 # -inf / 5 = -inf -inf % 5 = NaN 1900 # -inf / inf = NaN -inf % inf = NaN 1901 1902 if ($x -> is_inf()) { 1903 my $rem; 1904 $rem = $class -> bnan() if $wantarray; 1905 if ($y -> is_inf()) { 1906 $x -> bnan(); 1907 } else { 1908 my $sign = $x -> bcmp(0) == $y -> bcmp(0) ? '+' : '-'; 1909 $x -> binf($sign); 1910 } 1911 return $wantarray ? ($x, $rem) : $x; 1912 } 1913 1914 # Denominator (divisor) is +/-inf. The cases when the numerator is +/-inf 1915 # are covered above. In the modulo cases (in the right column) we return 1916 # the same as core Perl, which does floored division, so for consistency we 1917 # also do floored division in the division cases (in the left column). 1918 # 1919 # -5 / inf = -1 -5 % inf = inf 1920 # 0 / inf = 0 0 % inf = 0 1921 # 5 / inf = 0 5 % inf = 5 1922 # 1923 # -5 / -inf = 0 -5 % -inf = -5 1924 # 0 / -inf = 0 0 % -inf = 0 1925 # 5 / -inf = -1 5 % -inf = -inf 1926 1927 if ($y -> is_inf()) { 1928 my $rem; 1929 if ($x -> is_zero() || $x -> bcmp(0) == $y -> bcmp(0)) { 1930 $rem = $x -> copy() if $wantarray; 1931 $x -> bzero(); 1932 } else { 1933 $rem = $class -> binf($y -> {sign}) if $wantarray; 1934 $x -> bone('-'); 1935 } 1936 return $wantarray ? ($x, $rem) : $x; 1937 } 1938 1939 # At this point, both the numerator and denominator are finite numbers, and 1940 # the denominator (divisor) is non-zero. 1941 1942 return $upgrade -> bdiv($upgrade -> new($x), $upgrade -> new($y), @r) 1943 if defined $upgrade; 1944 1945 $r[3] = $y; # no push! 1946 1947 # Inialize remainder. 1948 1949 my $rem = $class -> bzero(); 1950 1951 # Are both operands the same object, i.e., like $x -> bdiv($x)? If so, 1952 # flipping the sign of $y also flips the sign of $x. 1953 1954 my $xsign = $x -> {sign}; 1955 my $ysign = $y -> {sign}; 1956 1957 $y -> {sign} =~ tr/+-/-+/; # Flip the sign of $y, and see ... 1958 my $same = $xsign ne $x -> {sign}; # ... if that changed the sign of $x. 1959 $y -> {sign} = $ysign; # Re-insert the original sign. 1960 1961 if ($same) { 1962 $x -> bone(); 1963 } else { 1964 ($x -> {value}, $rem -> {value}) = 1965 $LIB -> _div($x -> {value}, $y -> {value}); 1966 1967 if ($LIB -> _is_zero($rem -> {value})) { 1968 if ($xsign eq $ysign || $LIB -> _is_zero($x -> {value})) { 1969 $x -> {sign} = '+'; 1970 } else { 1971 $x -> {sign} = '-'; 1972 } 1973 } else { 1974 if ($xsign eq $ysign) { 1975 $x -> {sign} = '+'; 1976 } else { 1977 if ($xsign eq '+') { 1978 $x -> badd(1); 1979 } else { 1980 $x -> bsub(1); 1981 } 1982 $x -> {sign} = '-'; 1983 } 1984 } 1985 } 1986 1987 $x -> round(@r); 1988 1989 if ($wantarray) { 1990 unless ($LIB -> _is_zero($rem -> {value})) { 1991 if ($xsign ne $ysign) { 1992 $rem = $y -> copy() -> babs() -> bsub($rem); 1993 } 1994 $rem -> {sign} = $ysign; 1995 } 1996 $rem -> {_a} = $x -> {_a}; 1997 $rem -> {_p} = $x -> {_p}; 1998 $rem -> round(@r); 1999 return ($x, $rem); 2000 } 2001 2002 return $x; 2003} 2004 2005sub btdiv { 2006 # This does truncated division, where the quotient is truncted, i.e., 2007 # rounded towards zero. 2008 # 2009 # ($q, $r) = $x -> btdiv($y) returns $q and $r so that $q is int($x / $y) 2010 # and $q * $y + $r = $x. 2011 2012 # Set up parameters 2013 my ($class, $x, $y, @r) = (ref($_[0]), @_); 2014 2015 # objectify is costly, so avoid it if we can. 2016 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { 2017 ($class, $x, $y, @r) = objectify(2, @_); 2018 } 2019 2020 return $x if $x -> modify('btdiv'); 2021 2022 my $wantarray = wantarray; # call only once 2023 2024 # At least one argument is NaN. Return NaN for both quotient and the 2025 # modulo/remainder. 2026 2027 if ($x -> is_nan() || $y -> is_nan()) { 2028 return $wantarray ? ($x -> bnan(), $class -> bnan()) : $x -> bnan(); 2029 } 2030 2031 # Divide by zero and modulo zero. 2032 # 2033 # Division: Use the common convention that x / 0 is inf with the same sign 2034 # as x, except when x = 0, where we return NaN. This is also what earlier 2035 # versions did. 2036 # 2037 # Modulo: In modular arithmetic, the congruence relation z = x (mod y) 2038 # means that there is some integer k such that z - x = k y. If y = 0, we 2039 # get z - x = 0 or z = x. This is also what earlier versions did, except 2040 # that 0 % 0 returned NaN. 2041 # 2042 # inf / 0 = inf inf % 0 = inf 2043 # 5 / 0 = inf 5 % 0 = 5 2044 # 0 / 0 = NaN 0 % 0 = 0 2045 # -5 / 0 = -inf -5 % 0 = -5 2046 # -inf / 0 = -inf -inf % 0 = -inf 2047 2048 if ($y -> is_zero()) { 2049 my $rem; 2050 if ($wantarray) { 2051 $rem = $x -> copy(); 2052 } 2053 if ($x -> is_zero()) { 2054 $x -> bnan(); 2055 } else { 2056 $x -> binf($x -> {sign}); 2057 } 2058 return $wantarray ? ($x, $rem) : $x; 2059 } 2060 2061 # Numerator (dividend) is +/-inf, and denominator is finite and non-zero. 2062 # The divide by zero cases are covered above. In all of the cases listed 2063 # below we return the same as core Perl. 2064 # 2065 # inf / -inf = NaN inf % -inf = NaN 2066 # inf / -5 = -inf inf % -5 = NaN 2067 # inf / 5 = inf inf % 5 = NaN 2068 # inf / inf = NaN inf % inf = NaN 2069 # 2070 # -inf / -inf = NaN -inf % -inf = NaN 2071 # -inf / -5 = inf -inf % -5 = NaN 2072 # -inf / 5 = -inf -inf % 5 = NaN 2073 # -inf / inf = NaN -inf % inf = NaN 2074 2075 if ($x -> is_inf()) { 2076 my $rem; 2077 $rem = $class -> bnan() if $wantarray; 2078 if ($y -> is_inf()) { 2079 $x -> bnan(); 2080 } else { 2081 my $sign = $x -> bcmp(0) == $y -> bcmp(0) ? '+' : '-'; 2082 $x -> binf($sign); 2083 } 2084 return $wantarray ? ($x, $rem) : $x; 2085 } 2086 2087 # Denominator (divisor) is +/-inf. The cases when the numerator is +/-inf 2088 # are covered above. In the modulo cases (in the right column) we return 2089 # the same as core Perl, which does floored division, so for consistency we 2090 # also do floored division in the division cases (in the left column). 2091 # 2092 # -5 / inf = 0 -5 % inf = -5 2093 # 0 / inf = 0 0 % inf = 0 2094 # 5 / inf = 0 5 % inf = 5 2095 # 2096 # -5 / -inf = 0 -5 % -inf = -5 2097 # 0 / -inf = 0 0 % -inf = 0 2098 # 5 / -inf = 0 5 % -inf = 5 2099 2100 if ($y -> is_inf()) { 2101 my $rem; 2102 $rem = $x -> copy() if $wantarray; 2103 $x -> bzero(); 2104 return $wantarray ? ($x, $rem) : $x; 2105 } 2106 2107 return $upgrade -> btdiv($upgrade -> new($x), $upgrade -> new($y), @r) 2108 if defined $upgrade; 2109 2110 $r[3] = $y; # no push! 2111 2112 # Inialize remainder. 2113 2114 my $rem = $class -> bzero(); 2115 2116 # Are both operands the same object, i.e., like $x -> bdiv($x)? If so, 2117 # flipping the sign of $y also flips the sign of $x. 2118 2119 my $xsign = $x -> {sign}; 2120 my $ysign = $y -> {sign}; 2121 2122 $y -> {sign} =~ tr/+-/-+/; # Flip the sign of $y, and see ... 2123 my $same = $xsign ne $x -> {sign}; # ... if that changed the sign of $x. 2124 $y -> {sign} = $ysign; # Re-insert the original sign. 2125 2126 if ($same) { 2127 $x -> bone(); 2128 } else { 2129 ($x -> {value}, $rem -> {value}) = 2130 $LIB -> _div($x -> {value}, $y -> {value}); 2131 2132 $x -> {sign} = $xsign eq $ysign ? '+' : '-'; 2133 $x -> {sign} = '+' if $LIB -> _is_zero($x -> {value}); 2134 $x -> round(@r); 2135 } 2136 2137 if (wantarray) { 2138 $rem -> {sign} = $xsign; 2139 $rem -> {sign} = '+' if $LIB -> _is_zero($rem -> {value}); 2140 $rem -> {_a} = $x -> {_a}; 2141 $rem -> {_p} = $x -> {_p}; 2142 $rem -> round(@r); 2143 return ($x, $rem); 2144 } 2145 2146 return $x; 2147} 2148 2149sub bmod { 2150 # This is the remainder after floored division. 2151 2152 # Set up parameters. 2153 my ($class, $x, $y, @r) = (ref($_[0]), @_); 2154 2155 # objectify is costly, so avoid it 2156 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { 2157 ($class, $x, $y, @r) = objectify(2, @_); 2158 } 2159 2160 return $x if $x -> modify('bmod'); 2161 $r[3] = $y; # no push! 2162 2163 # At least one argument is NaN. 2164 2165 if ($x -> is_nan() || $y -> is_nan()) { 2166 return $x -> bnan(); 2167 } 2168 2169 # Modulo zero. See documentation for bdiv(). 2170 2171 if ($y -> is_zero()) { 2172 return $x; 2173 } 2174 2175 # Numerator (dividend) is +/-inf. 2176 2177 if ($x -> is_inf()) { 2178 return $x -> bnan(); 2179 } 2180 2181 # Denominator (divisor) is +/-inf. 2182 2183 if ($y -> is_inf()) { 2184 if ($x -> is_zero() || $x -> bcmp(0) == $y -> bcmp(0)) { 2185 return $x; 2186 } else { 2187 return $x -> binf($y -> sign()); 2188 } 2189 } 2190 2191 # Calc new sign and in case $y == +/- 1, return $x. 2192 2193 $x -> {value} = $LIB -> _mod($x -> {value}, $y -> {value}); 2194 if ($LIB -> _is_zero($x -> {value})) { 2195 $x -> {sign} = '+'; # do not leave -0 2196 } else { 2197 $x -> {value} = $LIB -> _sub($y -> {value}, $x -> {value}, 1) # $y-$x 2198 if ($x -> {sign} ne $y -> {sign}); 2199 $x -> {sign} = $y -> {sign}; 2200 } 2201 2202 $x -> round(@r); 2203} 2204 2205sub btmod { 2206 # Remainder after truncated division. 2207 2208 # set up parameters 2209 my ($class, $x, $y, @r) = (ref($_[0]), @_); 2210 2211 # objectify is costly, so avoid it 2212 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { 2213 ($class, $x, $y, @r) = objectify(2, @_); 2214 } 2215 2216 return $x if $x -> modify('btmod'); 2217 2218 # At least one argument is NaN. 2219 2220 if ($x -> is_nan() || $y -> is_nan()) { 2221 return $x -> bnan(); 2222 } 2223 2224 # Modulo zero. See documentation for btdiv(). 2225 2226 if ($y -> is_zero()) { 2227 return $x; 2228 } 2229 2230 # Numerator (dividend) is +/-inf. 2231 2232 if ($x -> is_inf()) { 2233 return $x -> bnan(); 2234 } 2235 2236 # Denominator (divisor) is +/-inf. 2237 2238 if ($y -> is_inf()) { 2239 return $x; 2240 } 2241 2242 return $upgrade -> btmod($upgrade -> new($x), $upgrade -> new($y), @r) 2243 if defined $upgrade; 2244 2245 $r[3] = $y; # no push! 2246 2247 my $xsign = $x -> {sign}; 2248 2249 $x -> {value} = $LIB -> _mod($x -> {value}, $y -> {value}); 2250 2251 $x -> {sign} = $xsign; 2252 $x -> {sign} = '+' if $LIB -> _is_zero($x -> {value}); 2253 $x -> round(@r); 2254 return $x; 2255} 2256 2257sub bmodinv { 2258 # Return modular multiplicative inverse: 2259 # 2260 # z is the modular inverse of x (mod y) if and only if 2261 # 2262 # x*z ≡ 1 (mod y) 2263 # 2264 # If the modulus y is larger than one, x and z are relative primes (i.e., 2265 # their greatest common divisor is one). 2266 # 2267 # If no modular multiplicative inverse exists, NaN is returned. 2268 2269 # set up parameters 2270 my ($class, $x, $y, @r) = (undef, @_); 2271 # objectify is costly, so avoid it 2272 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { 2273 ($class, $x, $y, @r) = objectify(2, @_); 2274 } 2275 2276 return $x if $x->modify('bmodinv'); 2277 2278 # Return NaN if one or both arguments is +inf, -inf, or nan. 2279 2280 return $x->bnan() if ($y->{sign} !~ /^[+-]$/ || 2281 $x->{sign} !~ /^[+-]$/); 2282 2283 # Return NaN if $y is zero; 1 % 0 makes no sense. 2284 2285 return $x->bnan() if $y->is_zero(); 2286 2287 # Return 0 in the trivial case. $x % 1 or $x % -1 is zero for all finite 2288 # integers $x. 2289 2290 return $x->bzero() if ($y->is_one() || 2291 $y->is_one('-')); 2292 2293 # Return NaN if $x = 0, or $x modulo $y is zero. The only valid case when 2294 # $x = 0 is when $y = 1 or $y = -1, but that was covered above. 2295 # 2296 # Note that computing $x modulo $y here affects the value we'll feed to 2297 # $LIB->_modinv() below when $x and $y have opposite signs. E.g., if $x = 2298 # 5 and $y = 7, those two values are fed to _modinv(), but if $x = -5 and 2299 # $y = 7, the values fed to _modinv() are $x = 2 (= -5 % 7) and $y = 7. 2300 # The value if $x is affected only when $x and $y have opposite signs. 2301 2302 $x->bmod($y); 2303 return $x->bnan() if $x->is_zero(); 2304 2305 # Compute the modular multiplicative inverse of the absolute values. We'll 2306 # correct for the signs of $x and $y later. Return NaN if no GCD is found. 2307 2308 ($x->{value}, $x->{sign}) = $LIB->_modinv($x->{value}, $y->{value}); 2309 return $x->bnan() if !defined $x->{value}; 2310 2311 # Library inconsistency workaround: _modinv() in Math::BigInt::GMP versions 2312 # <= 1.32 return undef rather than a "+" for the sign. 2313 2314 $x->{sign} = '+' unless defined $x->{sign}; 2315 2316 # When one or both arguments are negative, we have the following 2317 # relations. If x and y are positive: 2318 # 2319 # modinv(-x, -y) = -modinv(x, y) 2320 # modinv(-x, y) = y - modinv(x, y) = -modinv(x, y) (mod y) 2321 # modinv( x, -y) = modinv(x, y) - y = modinv(x, y) (mod -y) 2322 2323 # We must swap the sign of the result if the original $x is negative. 2324 # However, we must compensate for ignoring the signs when computing the 2325 # inverse modulo. The net effect is that we must swap the sign of the 2326 # result if $y is negative. 2327 2328 $x -> bneg() if $y->{sign} eq '-'; 2329 2330 # Compute $x modulo $y again after correcting the sign. 2331 2332 $x -> bmod($y) if $x->{sign} ne $y->{sign}; 2333 2334 return $x; 2335} 2336 2337sub bmodpow { 2338 # Modular exponentiation. Raises a very large number to a very large exponent 2339 # in a given very large modulus quickly, thanks to binary exponentiation. 2340 # Supports negative exponents. 2341 my ($class, $num, $exp, $mod, @r) = objectify(3, @_); 2342 2343 return $num if $num->modify('bmodpow'); 2344 2345 # When the exponent 'e' is negative, use the following relation, which is 2346 # based on finding the multiplicative inverse 'd' of 'b' modulo 'm': 2347 # 2348 # b^(-e) (mod m) = d^e (mod m) where b*d = 1 (mod m) 2349 2350 $num->bmodinv($mod) if ($exp->{sign} eq '-'); 2351 2352 # Check for valid input. All operands must be finite, and the modulus must be 2353 # non-zero. 2354 2355 return $num->bnan() if ($num->{sign} =~ /NaN|inf/ || # NaN, -inf, +inf 2356 $exp->{sign} =~ /NaN|inf/ || # NaN, -inf, +inf 2357 $mod->{sign} =~ /NaN|inf/); # NaN, -inf, +inf 2358 2359 # Modulo zero. See documentation for Math::BigInt's bmod() method. 2360 2361 if ($mod -> is_zero()) { 2362 if ($num -> is_zero()) { 2363 return $class -> bnan(); 2364 } else { 2365 return $num -> copy(); 2366 } 2367 } 2368 2369 # Compute 'a (mod m)', ignoring the signs on 'a' and 'm'. If the resulting 2370 # value is zero, the output is also zero, regardless of the signs on 'a' and 2371 # 'm'. 2372 2373 my $value = $LIB->_modpow($num->{value}, $exp->{value}, $mod->{value}); 2374 my $sign = '+'; 2375 2376 # If the resulting value is non-zero, we have four special cases, depending 2377 # on the signs on 'a' and 'm'. 2378 2379 unless ($LIB->_is_zero($value)) { 2380 2381 # There is a negative sign on 'a' (= $num**$exp) only if the number we 2382 # are exponentiating ($num) is negative and the exponent ($exp) is odd. 2383 2384 if ($num->{sign} eq '-' && $exp->is_odd()) { 2385 2386 # When both the number 'a' and the modulus 'm' have a negative sign, 2387 # use this relation: 2388 # 2389 # -a (mod -m) = -(a (mod m)) 2390 2391 if ($mod->{sign} eq '-') { 2392 $sign = '-'; 2393 } 2394 2395 # When only the number 'a' has a negative sign, use this relation: 2396 # 2397 # -a (mod m) = m - (a (mod m)) 2398 2399 else { 2400 # Use copy of $mod since _sub() modifies the first argument. 2401 my $mod = $LIB->_copy($mod->{value}); 2402 $value = $LIB->_sub($mod, $value); 2403 $sign = '+'; 2404 } 2405 2406 } else { 2407 2408 # When only the modulus 'm' has a negative sign, use this relation: 2409 # 2410 # a (mod -m) = (a (mod m)) - m 2411 # = -(m - (a (mod m))) 2412 2413 if ($mod->{sign} eq '-') { 2414 # Use copy of $mod since _sub() modifies the first argument. 2415 my $mod = $LIB->_copy($mod->{value}); 2416 $value = $LIB->_sub($mod, $value); 2417 $sign = '-'; 2418 } 2419 2420 # When neither the number 'a' nor the modulus 'm' have a negative 2421 # sign, directly return the already computed value. 2422 # 2423 # (a (mod m)) 2424 2425 } 2426 2427 } 2428 2429 $num->{value} = $value; 2430 $num->{sign} = $sign; 2431 2432 return $num -> round(@r); 2433} 2434 2435sub bpow { 2436 # (BINT or num_str, BINT or num_str) return BINT 2437 # compute power of two numbers -- stolen from Knuth Vol 2 pg 233 2438 # modifies first argument 2439 2440 # set up parameters 2441 my ($class, $x, $y, @r) = (ref($_[0]), @_); 2442 # objectify is costly, so avoid it 2443 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { 2444 ($class, $x, $y, @r) = objectify(2, @_); 2445 } 2446 2447 return $x if $x -> modify('bpow'); 2448 2449 # $x and/or $y is a NaN 2450 return $x -> bnan() if $x -> is_nan() || $y -> is_nan(); 2451 2452 # $x and/or $y is a +/-Inf 2453 if ($x -> is_inf("-")) { 2454 return $x -> bzero() if $y -> is_negative(); 2455 return $x -> bnan() if $y -> is_zero(); 2456 return $x if $y -> is_odd(); 2457 return $x -> bneg(); 2458 } elsif ($x -> is_inf("+")) { 2459 return $x -> bzero() if $y -> is_negative(); 2460 return $x -> bnan() if $y -> is_zero(); 2461 return $x; 2462 } elsif ($y -> is_inf("-")) { 2463 return $x -> bnan() if $x -> is_one("-"); 2464 return $x -> binf("+") if $x -> is_zero(); 2465 return $x -> bone() if $x -> is_one("+"); 2466 return $x -> bzero(); 2467 } elsif ($y -> is_inf("+")) { 2468 return $x -> bnan() if $x -> is_one("-"); 2469 return $x -> bzero() if $x -> is_zero(); 2470 return $x -> bone() if $x -> is_one("+"); 2471 return $x -> binf("+"); 2472 } 2473 2474 if ($x -> is_zero()) { 2475 return $x -> bone() if $y -> is_zero(); 2476 return $x -> binf() if $y -> is_negative(); 2477 return $x; 2478 } 2479 2480 if ($x -> is_one("+")) { 2481 return $x; 2482 } 2483 2484 if ($x -> is_one("-")) { 2485 return $x if $y -> is_odd(); 2486 return $x -> bneg(); 2487 } 2488 2489 # We don't support finite non-integers, so upgrade or return zero. The 2490 # reason for returning zero, not NaN, is that all output is in the open 2491 # interval (0,1), and truncating that to integer gives zero. 2492 2493 if ($y->{sign} eq '-' || !$y -> isa($class)) { 2494 return $upgrade -> bpow($upgrade -> new($x), $y, @r) 2495 if defined $upgrade; 2496 return $x -> bzero(); 2497 } 2498 2499 $r[3] = $y; # no push! 2500 2501 $x->{value} = $LIB -> _pow($x->{value}, $y->{value}); 2502 $x->{sign} = $x -> is_negative() && $y -> is_odd() ? '-' : '+'; 2503 $x -> round(@r); 2504} 2505 2506sub blog { 2507 # Return the logarithm of the operand. If a second operand is defined, that 2508 # value is used as the base, otherwise the base is assumed to be Euler's 2509 # constant. 2510 2511 my ($class, $x, $base, @r); 2512 2513 # Don't objectify the base, since an undefined base, as in $x->blog() or 2514 # $x->blog(undef) signals that the base is Euler's number. 2515 2516 if (!ref($_[0]) && $_[0] =~ /^[A-Za-z]|::/) { 2517 # E.g., Math::BigInt->blog(256, 2) 2518 ($class, $x, $base, @r) = 2519 defined $_[2] ? objectify(2, @_) : objectify(1, @_); 2520 } else { 2521 # E.g., Math::BigInt::blog(256, 2) or $x->blog(2) 2522 ($class, $x, $base, @r) = 2523 defined $_[1] ? objectify(2, @_) : objectify(1, @_); 2524 } 2525 2526 return $x if $x->modify('blog'); 2527 2528 # Handle all exception cases and all trivial cases. I have used Wolfram 2529 # Alpha (http://www.wolframalpha.com) as the reference for these cases. 2530 2531 return $x -> bnan() if $x -> is_nan(); 2532 2533 if (defined $base) { 2534 $base = $class -> new($base) unless ref $base; 2535 if ($base -> is_nan() || $base -> is_one()) { 2536 return $x -> bnan(); 2537 } elsif ($base -> is_inf() || $base -> is_zero()) { 2538 return $x -> bnan() if $x -> is_inf() || $x -> is_zero(); 2539 return $x -> bzero(); 2540 } elsif ($base -> is_negative()) { # -inf < base < 0 2541 return $x -> bzero() if $x -> is_one(); # x = 1 2542 return $x -> bone() if $x == $base; # x = base 2543 return $x -> bnan(); # otherwise 2544 } 2545 return $x -> bone() if $x == $base; # 0 < base && 0 < x < inf 2546 } 2547 2548 # We now know that the base is either undefined or >= 2 and finite. 2549 2550 return $x -> binf('+') if $x -> is_inf(); # x = +/-inf 2551 return $x -> bnan() if $x -> is_neg(); # -inf < x < 0 2552 return $x -> bzero() if $x -> is_one(); # x = 1 2553 return $x -> binf('-') if $x -> is_zero(); # x = 0 2554 2555 # At this point we are done handling all exception cases and trivial cases. 2556 2557 return $upgrade -> blog($upgrade -> new($x), $base, @r) if defined $upgrade; 2558 2559 # fix for bug #24969: 2560 # the default base is e (Euler's number) which is not an integer 2561 if (!defined $base) { 2562 require Math::BigFloat; 2563 my $u = Math::BigFloat->blog(Math::BigFloat->new($x))->as_int(); 2564 # modify $x in place 2565 $x->{value} = $u->{value}; 2566 $x->{sign} = $u->{sign}; 2567 return $x; 2568 } 2569 2570 my ($rc) = $LIB->_log_int($x->{value}, $base->{value}); 2571 return $x->bnan() unless defined $rc; # not possible to take log? 2572 $x->{value} = $rc; 2573 $x->round(@r); 2574} 2575 2576sub bexp { 2577 # Calculate e ** $x (Euler's number to the power of X), truncated to 2578 # an integer value. 2579 my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_); 2580 return $x if $x->modify('bexp'); 2581 2582 # inf, -inf, NaN, <0 => NaN 2583 return $x->bnan() if $x->{sign} eq 'NaN'; 2584 return $x->bone() if $x->is_zero(); 2585 return $x if $x->{sign} eq '+inf'; 2586 return $x->bzero() if $x->{sign} eq '-inf'; 2587 2588 my $u; 2589 { 2590 # run through Math::BigFloat unless told otherwise 2591 require Math::BigFloat unless defined $upgrade; 2592 local $upgrade = 'Math::BigFloat' unless defined $upgrade; 2593 # calculate result, truncate it to integer 2594 $u = $upgrade->bexp($upgrade->new($x), @r); 2595 } 2596 2597 if (defined $upgrade) { 2598 $x = $u; 2599 } else { 2600 $u = $u->as_int(); 2601 # modify $x in place 2602 $x->{value} = $u->{value}; 2603 $x->round(@r); 2604 } 2605} 2606 2607sub bnok { 2608 # Calculate n over k (binomial coefficient or "choose" function) as 2609 # integer. 2610 2611 # Set up parameters. 2612 my ($self, $n, $k, @r) = (ref($_[0]), @_); 2613 2614 # Objectify is costly, so avoid it. 2615 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { 2616 ($self, $n, $k, @r) = objectify(2, @_); 2617 } 2618 2619 return $n if $n->modify('bnok'); 2620 2621 # All cases where at least one argument is NaN. 2622 2623 return $n->bnan() if $n->{sign} eq 'NaN' || $k->{sign} eq 'NaN'; 2624 2625 # All cases where at least one argument is +/-inf. 2626 2627 if ($n -> is_inf()) { 2628 if ($k -> is_inf()) { # bnok(+/-inf,+/-inf) 2629 return $n -> bnan(); 2630 } elsif ($k -> is_neg()) { # bnok(+/-inf,k), k < 0 2631 return $n -> bzero(); 2632 } elsif ($k -> is_zero()) { # bnok(+/-inf,k), k = 0 2633 return $n -> bone(); 2634 } else { 2635 if ($n -> is_inf("+")) { # bnok(+inf,k), 0 < k < +inf 2636 return $n -> binf("+"); 2637 } else { # bnok(-inf,k), k > 0 2638 my $sign = $k -> is_even() ? "+" : "-"; 2639 return $n -> binf($sign); 2640 } 2641 } 2642 } 2643 2644 elsif ($k -> is_inf()) { # bnok(n,+/-inf), -inf <= n <= inf 2645 return $n -> bnan(); 2646 } 2647 2648 # At this point, both n and k are real numbers. 2649 2650 my $sign = 1; 2651 2652 if ($n >= 0) { 2653 if ($k < 0 || $k > $n) { 2654 return $n -> bzero(); 2655 } 2656 } else { 2657 2658 if ($k >= 0) { 2659 2660 # n < 0 and k >= 0: bnok(n,k) = (-1)^k * bnok(-n+k-1,k) 2661 2662 $sign = (-1) ** $k; 2663 $n -> bneg() -> badd($k) -> bdec(); 2664 2665 } elsif ($k <= $n) { 2666 2667 # n < 0 and k <= n: bnok(n,k) = (-1)^(n-k) * bnok(-k-1,n-k) 2668 2669 $sign = (-1) ** ($n - $k); 2670 my $x0 = $n -> copy(); 2671 $n -> bone() -> badd($k) -> bneg(); 2672 $k = $k -> copy(); 2673 $k -> bneg() -> badd($x0); 2674 2675 } else { 2676 2677 # n < 0 and n < k < 0: 2678 2679 return $n -> bzero(); 2680 } 2681 } 2682 2683 $n->{value} = $LIB->_nok($n->{value}, $k->{value}); 2684 $n -> bneg() if $sign == -1; 2685 2686 $n->round(@r); 2687} 2688 2689sub buparrow { 2690 my $a = shift; 2691 my $y = $a -> uparrow(@_); 2692 $a -> {value} = $y -> {value}; 2693 return $a; 2694} 2695 2696sub uparrow { 2697 # Knuth's up-arrow notation buparrow(a, n, b) 2698 # 2699 # The following is a simple, recursive implementation of the up-arrow 2700 # notation, just to show the idea. Such implementations cause "Deep 2701 # recursion on subroutine ..." warnings, so we use a faster, non-recursive 2702 # algorithm below with @_ as a stack. 2703 # 2704 # sub buparrow { 2705 # my ($a, $n, $b) = @_; 2706 # return $a ** $b if $n == 1; 2707 # return $a * $b if $n == 0; 2708 # return 1 if $b == 0; 2709 # return buparrow($a, $n - 1, buparrow($a, $n, $b - 1)); 2710 # } 2711 2712 my ($a, $b, $n) = @_; 2713 my $class = ref $a; 2714 croak("a must be non-negative") if $a < 0; 2715 croak("n must be non-negative") if $n < 0; 2716 croak("b must be non-negative") if $b < 0; 2717 2718 while (@_ >= 3) { 2719 2720 # return $a ** $b if $n == 1; 2721 2722 if ($_[-2] == 1) { 2723 my ($a, $n, $b) = splice @_, -3; 2724 push @_, $a ** $b; 2725 next; 2726 } 2727 2728 # return $a * $b if $n == 0; 2729 2730 if ($_[-2] == 0) { 2731 my ($a, $n, $b) = splice @_, -3; 2732 push @_, $a * $b; 2733 next; 2734 } 2735 2736 # return 1 if $b == 0; 2737 2738 if ($_[-1] == 0) { 2739 splice @_, -3; 2740 push @_, $class -> bone(); 2741 next; 2742 } 2743 2744 # return buparrow($a, $n - 1, buparrow($a, $n, $b - 1)); 2745 2746 my ($a, $n, $b) = splice @_, -3; 2747 push @_, ($a, $n - 1, 2748 $a, $n, $b - 1); 2749 2750 } 2751 2752 pop @_; 2753} 2754 2755sub backermann { 2756 my $m = shift; 2757 my $y = $m -> ackermann(@_); 2758 $m -> {value} = $y -> {value}; 2759 return $m; 2760} 2761 2762sub ackermann { 2763 # Ackermann's function ackermann(m, n) 2764 # 2765 # The following is a simple, recursive implementation of the ackermann 2766 # function, just to show the idea. Such implementations cause "Deep 2767 # recursion on subroutine ..." warnings, so we use a faster, non-recursive 2768 # algorithm below with @_ as a stack. 2769 # 2770 # sub ackermann { 2771 # my ($m, $n) = @_; 2772 # return $n + 1 if $m == 0; 2773 # return ackermann($m - 1, 1) if $m > 0 && $n == 0; 2774 # return ackermann($m - 1, ackermann($m, $n - 1) if $m > 0 && $n > 0; 2775 # } 2776 2777 my ($m, $n) = @_; 2778 my $class = ref $m; 2779 croak("m must be non-negative") if $m < 0; 2780 croak("n must be non-negative") if $n < 0; 2781 2782 my $two = $class -> new("2"); 2783 my $three = $class -> new("3"); 2784 my $thirteen = $class -> new("13"); 2785 2786 $n = pop; 2787 $n = $class -> new($n) unless ref($n); 2788 while (@_) { 2789 my $m = pop; 2790 if ($m > $three) { 2791 push @_, (--$m) x $n; 2792 while (--$m >= $three) { 2793 push @_, $m; 2794 } 2795 $n = $thirteen; 2796 } elsif ($m == $three) { 2797 $n = $class -> bone() -> blsft($n + $three) -> bsub($three); 2798 } elsif ($m == $two) { 2799 $n -> bmul($two) -> badd($three); 2800 } elsif ($m >= 0) { 2801 $n -> badd($m) -> binc(); 2802 } else { 2803 die "negative m!"; 2804 } 2805 } 2806 $n; 2807} 2808 2809sub bsin { 2810 # Calculate sinus(x) to N digits. Unless upgrading is in effect, returns the 2811 # result truncated to an integer. 2812 my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_); 2813 2814 return $x if $x->modify('bsin'); 2815 2816 return $x->bnan() if $x->{sign} !~ /^[+-]\z/; # -inf +inf or NaN => NaN 2817 2818 return $upgrade -> bsin($upgrade -> new($x, @r)) if defined $upgrade; 2819 2820 require Math::BigFloat; 2821 # calculate the result and truncate it to integer 2822 my $t = Math::BigFloat->new($x)->bsin(@r)->as_int(); 2823 2824 $x->bone() if $t->is_one(); 2825 $x->bzero() if $t->is_zero(); 2826 $x->round(@r); 2827} 2828 2829sub bcos { 2830 # Calculate cosinus(x) to N digits. Unless upgrading is in effect, returns the 2831 # result truncated to an integer. 2832 my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_); 2833 2834 return $x if $x->modify('bcos'); 2835 2836 return $x->bnan() if $x->{sign} !~ /^[+-]\z/; # -inf +inf or NaN => NaN 2837 2838 return $upgrade -> bcos($upgrade -> new($x), @r) if defined $upgrade; 2839 2840 require Math::BigFloat; 2841 # calculate the result and truncate it to integer 2842 my $t = Math::BigFloat -> bcos(Math::BigFloat -> new($x), @r) -> as_int(); 2843 2844 $x->bone() if $t->is_one(); 2845 $x->bzero() if $t->is_zero(); 2846 $x->round(@r); 2847} 2848 2849sub batan { 2850 # Calculate arcus tangens of x to N digits. Unless upgrading is in effect, returns the 2851 # result truncated to an integer. 2852 my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_); 2853 2854 return $x if $x->modify('batan'); 2855 2856 return $x->bnan() if $x->{sign} !~ /^[+-]\z/; # -inf +inf or NaN => NaN 2857 2858 return $upgrade->new($x)->batan(@r) if defined $upgrade; 2859 2860 # calculate the result and truncate it to integer 2861 my $tmp = Math::BigFloat->new($x)->batan(@r); 2862 2863 $x->{value} = $LIB->_new($tmp->as_int()->bstr()); 2864 $x->round(@r); 2865} 2866 2867sub batan2 { 2868 # calculate arcus tangens of ($y/$x) 2869 2870 # set up parameters 2871 my ($class, $y, $x, @r) = (ref($_[0]), @_); 2872 # objectify is costly, so avoid it 2873 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { 2874 ($class, $y, $x, @r) = objectify(2, @_); 2875 } 2876 2877 return $y if $y->modify('batan2'); 2878 2879 return $y->bnan() if ($y->{sign} eq $nan) || ($x->{sign} eq $nan); 2880 2881 # Y X 2882 # != 0 -inf result is +- pi 2883 if ($x->is_inf() || $y->is_inf()) { 2884 # upgrade to Math::BigFloat etc. 2885 return $upgrade->new($y)->batan2($upgrade->new($x), @r) if defined $upgrade; 2886 if ($y->is_inf()) { 2887 if ($x->{sign} eq '-inf') { 2888 # calculate 3 pi/4 => 2.3.. => 2 2889 $y->bone(substr($y->{sign}, 0, 1)); 2890 $y->bmul($class->new(2)); 2891 } elsif ($x->{sign} eq '+inf') { 2892 # calculate pi/4 => 0.7 => 0 2893 $y->bzero(); 2894 } else { 2895 # calculate pi/2 => 1.5 => 1 2896 $y->bone(substr($y->{sign}, 0, 1)); 2897 } 2898 } else { 2899 if ($x->{sign} eq '+inf') { 2900 # calculate pi/4 => 0.7 => 0 2901 $y->bzero(); 2902 } else { 2903 # PI => 3.1415.. => 3 2904 $y->bone(substr($y->{sign}, 0, 1)); 2905 $y->bmul($class->new(3)); 2906 } 2907 } 2908 return $y; 2909 } 2910 2911 return $upgrade->new($y)->batan2($upgrade->new($x), @r) if defined $upgrade; 2912 2913 require Math::BigFloat; 2914 my $r = Math::BigFloat->new($y) 2915 ->batan2(Math::BigFloat->new($x), @r) 2916 ->as_int(); 2917 2918 $x->{value} = $r->{value}; 2919 $x->{sign} = $r->{sign}; 2920 2921 $x; 2922} 2923 2924sub bsqrt { 2925 # calculate square root of $x 2926 my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_); 2927 2928 return $x if $x->modify('bsqrt'); 2929 2930 return $x->bnan() if $x->{sign} !~ /^\+/; # -x or -inf or NaN => NaN 2931 return $x if $x->{sign} eq '+inf'; # sqrt(+inf) == inf 2932 2933 return $upgrade->bsqrt($x, @r) if defined $upgrade; 2934 2935 $x->{value} = $LIB->_sqrt($x->{value}); 2936 $x->round(@r); 2937} 2938 2939sub broot { 2940 # calculate $y'th root of $x 2941 2942 # set up parameters 2943 my ($class, $x, $y, @r) = (ref($_[0]), @_); 2944 2945 $y = $class->new(2) unless defined $y; 2946 2947 # objectify is costly, so avoid it 2948 if ((!ref($x)) || (ref($x) ne ref($y))) { 2949 ($class, $x, $y, @r) = objectify(2, $class || $class, @_); 2950 } 2951 2952 return $x if $x->modify('broot'); 2953 2954 # NaN handling: $x ** 1/0, x or y NaN, or y inf/-inf or y == 0 2955 return $x->bnan() if $x->{sign} !~ /^\+/ || $y->is_zero() || 2956 $y->{sign} !~ /^\+$/; 2957 2958 return $x->round(@r) 2959 if $x->is_zero() || $x->is_one() || $x->is_inf() || $y->is_one(); 2960 2961 return $upgrade->new($x)->broot($upgrade->new($y), @r) if defined $upgrade; 2962 2963 $x->{value} = $LIB->_root($x->{value}, $y->{value}); 2964 $x->round(@r); 2965} 2966 2967sub bfac { 2968 # (BINT or num_str, BINT or num_str) return BINT 2969 # compute factorial number from $x, modify $x in place 2970 my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_); 2971 2972 return $x if $x->modify('bfac') || $x->{sign} eq '+inf'; # inf => inf 2973 return $x->bnan() if $x->{sign} ne '+'; # NaN, <0 => NaN 2974 2975 $x->{value} = $LIB->_fac($x->{value}); 2976 $x->round(@r); 2977} 2978 2979sub bdfac { 2980 # compute double factorial, modify $x in place 2981 my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_); 2982 2983 return $x if $x->modify('bdfac') || $x->{sign} eq '+inf'; # inf => inf 2984 return $x->bnan() if $x->is_nan() || $x <= -2; 2985 return $x->bone() if $x <= 1; 2986 2987 croak("bdfac() requires a newer version of the $LIB library.") 2988 unless $LIB->can('_dfac'); 2989 2990 $x->{value} = $LIB->_dfac($x->{value}); 2991 $x->round(@r); 2992} 2993 2994sub btfac { 2995 # compute triple factorial, modify $x in place 2996 my ($class, $x, @r) = objectify(1, @_); 2997 2998 return $x if $x->modify('btfac') || $x->{sign} eq '+inf'; # inf => inf 2999 3000 return $x->bnan() if $x->is_nan(); 3001 3002 my $k = $class -> new("3"); 3003 return $x->bnan() if $x <= -$k; 3004 3005 my $one = $class -> bone(); 3006 return $x->bone() if $x <= $one; 3007 3008 my $f = $x -> copy(); 3009 while ($f -> bsub($k) > $one) { 3010 $x -> bmul($f); 3011 } 3012 $x->round(@r); 3013} 3014 3015sub bmfac { 3016 # compute multi-factorial 3017 my ($class, $x, $k, @r) = objectify(2, @_); 3018 3019 return $x if $x->modify('bmfac') || $x->{sign} eq '+inf'; 3020 return $x->bnan() if $x->is_nan() || $k->is_nan() || $k < 1 || $x <= -$k; 3021 3022 my $one = $class -> bone(); 3023 return $x->bone() if $x <= $one; 3024 3025 my $f = $x -> copy(); 3026 while ($f -> bsub($k) > $one) { 3027 $x -> bmul($f); 3028 } 3029 $x->round(@r); 3030} 3031 3032sub bfib { 3033 # compute Fibonacci number(s) 3034 my ($class, $x, @r) = objectify(1, @_); 3035 3036 croak("bfib() requires a newer version of the $LIB library.") 3037 unless $LIB->can('_fib'); 3038 3039 return $x if $x->modify('bfib'); 3040 3041 # List context. 3042 3043 if (wantarray) { 3044 return () if $x -> is_nan(); 3045 croak("bfib() can't return an infinitely long list of numbers") 3046 if $x -> is_inf(); 3047 3048 # Use the backend library to compute the first $x Fibonacci numbers. 3049 3050 my @values = $LIB->_fib($x->{value}); 3051 3052 # Make objects out of them. The last element in the array is the 3053 # invocand. 3054 3055 for (my $i = 0 ; $i < $#values ; ++ $i) { 3056 my $fib = $class -> bzero(); 3057 $fib -> {value} = $values[$i]; 3058 $values[$i] = $fib; 3059 } 3060 3061 $x -> {value} = $values[-1]; 3062 $values[-1] = $x; 3063 3064 # If negative, insert sign as appropriate. 3065 3066 if ($x -> is_neg()) { 3067 for (my $i = 2 ; $i <= $#values ; $i += 2) { 3068 $values[$i]{sign} = '-'; 3069 } 3070 } 3071 3072 @values = map { $_ -> round(@r) } @values; 3073 return @values; 3074 } 3075 3076 # Scalar context. 3077 3078 else { 3079 return $x if $x->modify('bdfac') || $x -> is_inf('+'); 3080 return $x->bnan() if $x -> is_nan() || $x -> is_inf('-'); 3081 3082 $x->{sign} = $x -> is_neg() && $x -> is_even() ? '-' : '+'; 3083 $x->{value} = $LIB->_fib($x->{value}); 3084 return $x->round(@r); 3085 } 3086} 3087 3088sub blucas { 3089 # compute Lucas number(s) 3090 my ($class, $x, @r) = objectify(1, @_); 3091 3092 croak("blucas() requires a newer version of the $LIB library.") 3093 unless $LIB->can('_lucas'); 3094 3095 return $x if $x->modify('blucas'); 3096 3097 # List context. 3098 3099 if (wantarray) { 3100 return () if $x -> is_nan(); 3101 croak("blucas() can't return an infinitely long list of numbers") 3102 if $x -> is_inf(); 3103 3104 # Use the backend library to compute the first $x Lucas numbers. 3105 3106 my @values = $LIB->_lucas($x->{value}); 3107 3108 # Make objects out of them. The last element in the array is the 3109 # invocand. 3110 3111 for (my $i = 0 ; $i < $#values ; ++ $i) { 3112 my $lucas = $class -> bzero(); 3113 $lucas -> {value} = $values[$i]; 3114 $values[$i] = $lucas; 3115 } 3116 3117 $x -> {value} = $values[-1]; 3118 $values[-1] = $x; 3119 3120 # If negative, insert sign as appropriate. 3121 3122 if ($x -> is_neg()) { 3123 for (my $i = 2 ; $i <= $#values ; $i += 2) { 3124 $values[$i]{sign} = '-'; 3125 } 3126 } 3127 3128 @values = map { $_ -> round(@r) } @values; 3129 return @values; 3130 } 3131 3132 # Scalar context. 3133 3134 else { 3135 return $x if $x -> is_inf('+'); 3136 return $x->bnan() if $x -> is_nan() || $x -> is_inf('-'); 3137 3138 $x->{sign} = $x -> is_neg() && $x -> is_even() ? '-' : '+'; 3139 $x->{value} = $LIB->_lucas($x->{value}); 3140 return $x->round(@r); 3141 } 3142} 3143 3144sub blsft { 3145 # (BINT or num_str, BINT or num_str) return BINT 3146 # compute x << y, base n, y >= 0 3147 3148 my ($class, $x, $y, $b, @r); 3149 3150 # Objectify the base only when it is defined, since an undefined base, as 3151 # in $x->blsft(3) or $x->blog(3, undef) means use the default base 2. 3152 3153 if (!ref($_[0]) && $_[0] =~ /^[A-Za-z]|::/) { 3154 # E.g., Math::BigInt->blog(256, 5, 2) 3155 ($class, $x, $y, $b, @r) = 3156 defined $_[3] ? objectify(3, @_) : objectify(2, @_); 3157 } else { 3158 # E.g., Math::BigInt::blog(256, 5, 2) or $x->blog(5, 2) 3159 ($class, $x, $y, $b, @r) = 3160 defined $_[2] ? objectify(3, @_) : objectify(2, @_); 3161 } 3162 3163 return $x if $x -> modify('blsft'); 3164 return $x -> bnan() if ($x -> {sign} !~ /^[+-]$/ || 3165 $y -> {sign} !~ /^[+-]$/); 3166 return $x -> round(@r) if $y -> is_zero(); 3167 3168 $b = defined($b) ? $b -> numify() : 2; 3169 3170 # While some of the libraries support an arbitrarily large base, not all of 3171 # them do, so rather than returning an incorrect result in those cases, 3172 # disallow bases that don't work with all libraries. 3173 3174 my $uintmax = ~0; 3175 croak("Base is too large.") if $b > $uintmax; 3176 3177 return $x -> bnan() if $b <= 0 || $y -> {sign} eq '-'; 3178 3179 $x -> {value} = $LIB -> _lsft($x -> {value}, $y -> {value}, $b); 3180 $x -> round(@r); 3181} 3182 3183sub brsft { 3184 # (BINT or num_str, BINT or num_str) return BINT 3185 # compute x >> y, base n, y >= 0 3186 3187 # set up parameters 3188 my ($class, $x, $y, $b, @r) = (ref($_[0]), @_); 3189 3190 # objectify is costly, so avoid it 3191 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { 3192 ($class, $x, $y, $b, @r) = objectify(2, @_); 3193 } 3194 3195 return $x if $x -> modify('brsft'); 3196 return $x -> bnan() if ($x -> {sign} !~ /^[+-]$/ || $y -> {sign} !~ /^[+-]$/); 3197 return $x -> round(@r) if $y -> is_zero(); 3198 return $x -> bzero(@r) if $x -> is_zero(); # 0 => 0 3199 3200 $b = 2 if !defined $b; 3201 return $x -> bnan() if $b <= 0 || $y -> {sign} eq '-'; 3202 3203 # this only works for negative numbers when shifting in base 2 3204 if (($x -> {sign} eq '-') && ($b == 2)) { 3205 return $x -> round(@r) if $x -> is_one('-'); # -1 => -1 3206 if (!$y -> is_one()) { 3207 # although this is O(N*N) in calc (as_bin!) it is O(N) in Pari et 3208 # al but perhaps there is a better emulation for two's complement 3209 # shift... 3210 # if $y != 1, we must simulate it by doing: 3211 # convert to bin, flip all bits, shift, and be done 3212 $x -> binc(); # -3 => -2 3213 my $bin = $x -> as_bin(); 3214 $bin =~ s/^-0b//; # strip '-0b' prefix 3215 $bin =~ tr/10/01/; # flip bits 3216 # now shift 3217 if ($y >= CORE::length($bin)) { 3218 $bin = '0'; # shifting to far right creates -1 3219 # 0, because later increment makes 3220 # that 1, attached '-' makes it '-1' 3221 # because -1 >> x == -1 ! 3222 } else { 3223 $bin =~ s/.{$y}$//; # cut off at the right side 3224 $bin = '1' . $bin; # extend left side by one dummy '1' 3225 $bin =~ tr/10/01/; # flip bits back 3226 } 3227 my $res = $class -> new('0b' . $bin); # add prefix and convert back 3228 $res -> binc(); # remember to increment 3229 $x -> {value} = $res -> {value}; # take over value 3230 return $x -> round(@r); # we are done now, magic, isn't? 3231 } 3232 3233 # x < 0, n == 2, y == 1 3234 $x -> bdec(); # n == 2, but $y == 1: this fixes it 3235 } 3236 3237 $x -> {value} = $LIB -> _rsft($x -> {value}, $y -> {value}, $b); 3238 $x -> round(@r); 3239} 3240 3241############################################################################### 3242# Bitwise methods 3243############################################################################### 3244 3245sub band { 3246 #(BINT or num_str, BINT or num_str) return BINT 3247 # compute x & y 3248 3249 # set up parameters 3250 my ($class, $x, $y, @r) = (ref($_[0]), @_); 3251 # objectify is costly, so avoid it 3252 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { 3253 ($class, $x, $y, @r) = objectify(2, @_); 3254 } 3255 3256 return $x if $x->modify('band'); 3257 3258 $r[3] = $y; # no push! 3259 3260 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/); 3261 3262 if ($x->{sign} eq '+' && $y->{sign} eq '+') { 3263 $x->{value} = $LIB->_and($x->{value}, $y->{value}); 3264 } else { 3265 ($x->{value}, $x->{sign}) = $LIB->_sand($x->{value}, $x->{sign}, 3266 $y->{value}, $y->{sign}); 3267 } 3268 return $x->round(@r); 3269} 3270 3271sub bior { 3272 #(BINT or num_str, BINT or num_str) return BINT 3273 # compute x | y 3274 3275 # set up parameters 3276 my ($class, $x, $y, @r) = (ref($_[0]), @_); 3277 # objectify is costly, so avoid it 3278 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { 3279 ($class, $x, $y, @r) = objectify(2, @_); 3280 } 3281 3282 return $x if $x->modify('bior'); 3283 3284 $r[3] = $y; # no push! 3285 3286 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/); 3287 3288 if ($x->{sign} eq '+' && $y->{sign} eq '+') { 3289 $x->{value} = $LIB->_or($x->{value}, $y->{value}); 3290 } else { 3291 ($x->{value}, $x->{sign}) = $LIB->_sor($x->{value}, $x->{sign}, 3292 $y->{value}, $y->{sign}); 3293 } 3294 return $x->round(@r); 3295} 3296 3297sub bxor { 3298 #(BINT or num_str, BINT or num_str) return BINT 3299 # compute x ^ y 3300 3301 # set up parameters 3302 my ($class, $x, $y, @r) = (ref($_[0]), @_); 3303 # objectify is costly, so avoid it 3304 if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { 3305 ($class, $x, $y, @r) = objectify(2, @_); 3306 } 3307 3308 return $x if $x->modify('bxor'); 3309 3310 $r[3] = $y; # no push! 3311 3312 return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/); 3313 3314 if ($x->{sign} eq '+' && $y->{sign} eq '+') { 3315 $x->{value} = $LIB->_xor($x->{value}, $y->{value}); 3316 } else { 3317 ($x->{value}, $x->{sign}) = $LIB->_sxor($x->{value}, $x->{sign}, 3318 $y->{value}, $y->{sign}); 3319 } 3320 return $x->round(@r); 3321} 3322 3323sub bnot { 3324 # (num_str or BINT) return BINT 3325 # represent ~x as twos-complement number 3326 # we don't need $class, so undef instead of ref($_[0]) make it slightly faster 3327 my ($class, $x) = ref($_[0]) ? (undef, @_) : objectify(1, @_); 3328 3329 return $x if $x->modify('bnot'); 3330 $x->binc()->bneg(); # binc already does round 3331} 3332 3333############################################################################### 3334# Rounding methods 3335############################################################################### 3336 3337sub round { 3338 # Round $self according to given parameters, or given second argument's 3339 # parameters or global defaults 3340 3341 # for speed reasons, _find_round_parameters is embedded here: 3342 3343 my ($self, $a, $p, $r, @args) = @_; 3344 # $a accuracy, if given by caller 3345 # $p precision, if given by caller 3346 # $r round_mode, if given by caller 3347 # @args all 'other' arguments (0 for unary, 1 for binary ops) 3348 3349 my $class = ref($self); # find out class of argument(s) 3350 no strict 'refs'; 3351 3352 # now pick $a or $p, but only if we have got "arguments" 3353 if (!defined $a) { 3354 foreach ($self, @args) { 3355 # take the defined one, or if both defined, the one that is smaller 3356 $a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a); 3357 } 3358 } 3359 if (!defined $p) { 3360 # even if $a is defined, take $p, to signal error for both defined 3361 foreach ($self, @args) { 3362 # take the defined one, or if both defined, the one that is bigger 3363 # -2 > -3, and 3 > 2 3364 $p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p); 3365 } 3366 } 3367 3368 # if still none defined, use globals 3369 unless (defined $a || defined $p) { 3370 $a = ${"$class\::accuracy"}; 3371 $p = ${"$class\::precision"}; 3372 } 3373 3374 # A == 0 is useless, so undef it to signal no rounding 3375 $a = undef if defined $a && $a == 0; 3376 3377 # no rounding today? 3378 return $self unless defined $a || defined $p; # early out 3379 3380 # set A and set P is an fatal error 3381 return $self->bnan() if defined $a && defined $p; 3382 3383 $r = ${"$class\::round_mode"} unless defined $r; 3384 if ($r !~ /^(even|odd|[+-]inf|zero|trunc|common)$/) { 3385 croak("Unknown round mode '$r'"); 3386 } 3387 3388 # now round, by calling either bround or bfround: 3389 if (defined $a) { 3390 $self->bround(int($a), $r) if !defined $self->{_a} || $self->{_a} >= $a; 3391 } else { # both can't be undefined due to early out 3392 $self->bfround(int($p), $r) if !defined $self->{_p} || $self->{_p} <= $p; 3393 } 3394 3395 # bround() or bfround() already called bnorm() if nec. 3396 $self; 3397} 3398 3399sub bround { 3400 # accuracy: +$n preserve $n digits from left, 3401 # -$n preserve $n digits from right (f.i. for 0.1234 style in MBF) 3402 # no-op for $n == 0 3403 # and overwrite the rest with 0's, return normalized number 3404 # do not return $x->bnorm(), but $x 3405 3406 my $x = shift; 3407 $x = __PACKAGE__->new($x) unless ref $x; 3408 my ($scale, $mode) = $x->_scale_a(@_); 3409 return $x if !defined $scale || $x->modify('bround'); # no-op 3410 3411 if ($x->is_zero() || $scale == 0) { 3412 $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2 3413 return $x; 3414 } 3415 return $x if $x->{sign} !~ /^[+-]$/; # inf, NaN 3416 3417 # we have fewer digits than we want to scale to 3418 my $len = $x->length(); 3419 # convert $scale to a scalar in case it is an object (put's a limit on the 3420 # number length, but this would already limited by memory constraints), makes 3421 # it faster 3422 $scale = $scale->numify() if ref ($scale); 3423 3424 # scale < 0, but > -len (not >=!) 3425 if (($scale < 0 && $scale < -$len-1) || ($scale >= $len)) { 3426 $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2 3427 return $x; 3428 } 3429 3430 # count of 0's to pad, from left (+) or right (-): 9 - +6 => 3, or |-6| => 6 3431 my ($pad, $digit_round, $digit_after); 3432 $pad = $len - $scale; 3433 $pad = abs($scale-1) if $scale < 0; 3434 3435 # do not use digit(), it is very costly for binary => decimal 3436 # getting the entire string is also costly, but we need to do it only once 3437 my $xs = $LIB->_str($x->{value}); 3438 my $pl = -$pad-1; 3439 3440 # pad: 123: 0 => -1, at 1 => -2, at 2 => -3, at 3 => -4 3441 # pad+1: 123: 0 => 0, at 1 => -1, at 2 => -2, at 3 => -3 3442 $digit_round = '0'; 3443 $digit_round = substr($xs, $pl, 1) if $pad <= $len; 3444 $pl++; 3445 $pl ++ if $pad >= $len; 3446 $digit_after = '0'; 3447 $digit_after = substr($xs, $pl, 1) if $pad > 0; 3448 3449 # in case of 01234 we round down, for 6789 up, and only in case 5 we look 3450 # closer at the remaining digits of the original $x, remember decision 3451 my $round_up = 1; # default round up 3452 $round_up -- if 3453 ($mode eq 'trunc') || # trunc by round down 3454 ($digit_after =~ /[01234]/) || # round down anyway, 3455 # 6789 => round up 3456 ($digit_after eq '5') && # not 5000...0000 3457 ($x->_scan_for_nonzero($pad, $xs, $len) == 0) && 3458 ( 3459 ($mode eq 'even') && ($digit_round =~ /[24680]/) || 3460 ($mode eq 'odd') && ($digit_round =~ /[13579]/) || 3461 ($mode eq '+inf') && ($x->{sign} eq '-') || 3462 ($mode eq '-inf') && ($x->{sign} eq '+') || 3463 ($mode eq 'zero') # round down if zero, sign adjusted below 3464 ); 3465 my $put_back = 0; # not yet modified 3466 3467 if (($pad > 0) && ($pad <= $len)) { 3468 substr($xs, -$pad, $pad) = '0' x $pad; # replace with '00...' 3469 $xs =~ s/^0+(\d)/$1/; # "00000" -> "0" 3470 $put_back = 1; # need to put back 3471 } elsif ($pad > $len) { 3472 $x->bzero(); # round to '0' 3473 } 3474 3475 if ($round_up) { # what gave test above? 3476 $put_back = 1; # need to put back 3477 $pad = $len, $xs = '0' x $pad if $scale < 0; # tlr: whack 0.51=>1.0 3478 3479 # we modify directly the string variant instead of creating a number and 3480 # adding it, since that is faster (we already have the string) 3481 my $c = 0; 3482 $pad ++; # for $pad == $len case 3483 while ($pad <= $len) { 3484 $c = substr($xs, -$pad, 1) + 1; 3485 $c = '0' if $c eq '10'; 3486 substr($xs, -$pad, 1) = $c; 3487 $pad++; 3488 last if $c != 0; # no overflow => early out 3489 } 3490 $xs = '1'.$xs if $c == 0; 3491 } 3492 $x->{value} = $LIB->_new($xs) if $put_back == 1; # put back, if needed 3493 3494 $x->{_a} = $scale if $scale >= 0; 3495 if ($scale < 0) { 3496 $x->{_a} = $len+$scale; 3497 $x->{_a} = 0 if $scale < -$len; 3498 } 3499 $x; 3500} 3501 3502sub bfround { 3503 # precision: round to the $Nth digit left (+$n) or right (-$n) from the '.' 3504 # $n == 0 || $n == 1 => round to integer 3505 my $x = shift; 3506 my $class = ref($x) || $x; 3507 $x = $class->new($x) unless ref $x; 3508 3509 my ($scale, $mode) = $x->_scale_p(@_); 3510 3511 return $x if !defined $scale || $x->modify('bfround'); # no-op 3512 3513 # no-op for Math::BigInt objects if $n <= 0 3514 $x->bround($x->length()-$scale, $mode) if $scale > 0; 3515 3516 delete $x->{_a}; # delete to save memory 3517 $x->{_p} = $scale; # store new _p 3518 $x; 3519} 3520 3521sub fround { 3522 # Exists to make life easier for switch between MBF and MBI (should we 3523 # autoload fxxx() like MBF does for bxxx()?) 3524 my $x = shift; 3525 $x = __PACKAGE__->new($x) unless ref $x; 3526 $x->bround(@_); 3527} 3528 3529sub bfloor { 3530 # round towards minus infinity; no-op since it's already integer 3531 my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_); 3532 3533 $x->round(@r); 3534} 3535 3536sub bceil { 3537 # round towards plus infinity; no-op since it's already int 3538 my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_); 3539 3540 $x->round(@r); 3541} 3542 3543sub bint { 3544 # round towards zero; no-op since it's already integer 3545 my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_); 3546 3547 $x->round(@r); 3548} 3549 3550############################################################################### 3551# Other mathematical methods 3552############################################################################### 3553 3554sub bgcd { 3555 # (BINT or num_str, BINT or num_str) return BINT 3556 # does not modify arguments, but returns new object 3557 # GCD -- Euclid's algorithm, variant C (Knuth Vol 3, pg 341 ff) 3558 3559 my ($class, @args) = objectify(0, @_); 3560 3561 my $x = shift @args; 3562 $x = ref($x) && $x -> isa($class) ? $x -> copy() : $class -> new($x); 3563 3564 return $class->bnan() if $x->{sign} !~ /^[+-]$/; # x NaN? 3565 3566 while (@args) { 3567 my $y = shift @args; 3568 $y = $class->new($y) unless ref($y) && $y -> isa($class); 3569 return $class->bnan() if $y->{sign} !~ /^[+-]$/; # y NaN? 3570 $x->{value} = $LIB->_gcd($x->{value}, $y->{value}); 3571 last if $LIB->_is_one($x->{value}); 3572 } 3573 3574 return $x -> babs(); 3575} 3576 3577sub blcm { 3578 # (BINT or num_str, BINT or num_str) return BINT 3579 # does not modify arguments, but returns new object 3580 # Least Common Multiple 3581 3582 my ($class, @args) = objectify(0, @_); 3583 3584 my $x = shift @args; 3585 $x = ref($x) && $x -> isa($class) ? $x -> copy() : $class -> new($x); 3586 return $class->bnan() if $x->{sign} !~ /^[+-]$/; # x NaN? 3587 3588 while (@args) { 3589 my $y = shift @args; 3590 $y = $class -> new($y) unless ref($y) && $y -> isa($class); 3591 return $x->bnan() if $y->{sign} !~ /^[+-]$/; # y not integer 3592 $x -> {value} = $LIB->_lcm($x -> {value}, $y -> {value}); 3593 } 3594 3595 return $x -> babs(); 3596} 3597 3598############################################################################### 3599# Object property methods 3600############################################################################### 3601 3602sub sign { 3603 # return the sign of the number: +/-/-inf/+inf/NaN 3604 my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); 3605 3606 $x->{sign}; 3607} 3608 3609sub digit { 3610 # return the nth decimal digit, negative values count backward, 0 is right 3611 my ($class, $x, $n) = ref($_[0]) ? (undef, @_) : objectify(1, @_); 3612 3613 $n = $n->numify() if ref($n); 3614 $LIB->_digit($x->{value}, $n || 0); 3615} 3616 3617sub bdigitsum { 3618 # like digitsum(), but assigns the result to the invocand 3619 my $x = shift; 3620 3621 return $x if $x -> is_nan(); 3622 return $x -> bnan() if $x -> is_inf(); 3623 3624 $x -> {value} = $LIB -> _digitsum($x -> {value}); 3625 $x -> {sign} = '+'; 3626 return $x; 3627} 3628 3629sub digitsum { 3630 # compute sum of decimal digits and return it 3631 my $x = shift; 3632 my $class = ref $x; 3633 3634 return $class -> bnan() if $x -> is_nan(); 3635 return $class -> bnan() if $x -> is_inf(); 3636 3637 my $y = $class -> bzero(); 3638 $y -> {value} = $LIB -> _digitsum($x -> {value}); 3639 return $y; 3640} 3641 3642sub length { 3643 my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); 3644 3645 my $e = $LIB->_len($x->{value}); 3646 wantarray ? ($e, 0) : $e; 3647} 3648 3649sub exponent { 3650 # return a copy of the exponent (here always 0, NaN or 1 for $m == 0) 3651 my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_); 3652 3653 if ($x->{sign} !~ /^[+-]$/) { 3654 my $s = $x->{sign}; 3655 $s =~ s/^[+-]//; # NaN, -inf, +inf => NaN or inf 3656 return $class->new($s); 3657 } 3658 return $class->bzero() if $x->is_zero(); 3659 3660 # 12300 => 2 trailing zeros => exponent is 2 3661 $class->new($LIB->_zeros($x->{value})); 3662} 3663 3664sub mantissa { 3665 # return the mantissa (compatible to Math::BigFloat, e.g. reduced) 3666 my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_); 3667 3668 if ($x->{sign} !~ /^[+-]$/) { 3669 # for NaN, +inf, -inf: keep the sign 3670 return $class->new($x->{sign}); 3671 } 3672 my $m = $x->copy(); 3673 delete $m->{_p}; 3674 delete $m->{_a}; 3675 3676 # that's a bit inefficient: 3677 my $zeros = $LIB->_zeros($m->{value}); 3678 $m->brsft($zeros, 10) if $zeros != 0; 3679 $m; 3680} 3681 3682sub parts { 3683 # return a copy of both the exponent and the mantissa 3684 my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); 3685 3686 ($x->mantissa(), $x->exponent()); 3687} 3688 3689sub sparts { 3690 my $self = shift; 3691 my $class = ref $self; 3692 3693 croak("sparts() is an instance method, not a class method") 3694 unless $class; 3695 3696 # Not-a-number. 3697 3698 if ($self -> is_nan()) { 3699 my $mant = $self -> copy(); # mantissa 3700 return $mant unless wantarray; # scalar context 3701 my $expo = $class -> bnan(); # exponent 3702 return ($mant, $expo); # list context 3703 } 3704 3705 # Infinity. 3706 3707 if ($self -> is_inf()) { 3708 my $mant = $self -> copy(); # mantissa 3709 return $mant unless wantarray; # scalar context 3710 my $expo = $class -> binf('+'); # exponent 3711 return ($mant, $expo); # list context 3712 } 3713 3714 # Finite number. 3715 3716 my $mant = $self -> copy(); 3717 my $nzeros = $LIB -> _zeros($mant -> {value}); 3718 3719 $mant -> brsft($nzeros, 10) if $nzeros != 0; 3720 return $mant unless wantarray; 3721 3722 my $expo = $class -> new($nzeros); 3723 return ($mant, $expo); 3724} 3725 3726sub nparts { 3727 my $self = shift; 3728 my $class = ref $self; 3729 3730 croak("nparts() is an instance method, not a class method") 3731 unless $class; 3732 3733 # Not-a-number. 3734 3735 if ($self -> is_nan()) { 3736 my $mant = $self -> copy(); # mantissa 3737 return $mant unless wantarray; # scalar context 3738 my $expo = $class -> bnan(); # exponent 3739 return ($mant, $expo); # list context 3740 } 3741 3742 # Infinity. 3743 3744 if ($self -> is_inf()) { 3745 my $mant = $self -> copy(); # mantissa 3746 return $mant unless wantarray; # scalar context 3747 my $expo = $class -> binf('+'); # exponent 3748 return ($mant, $expo); # list context 3749 } 3750 3751 # Finite number. 3752 3753 my ($mant, $expo) = $self -> sparts(); 3754 3755 if ($mant -> bcmp(0)) { 3756 my ($ndigtot, $ndigfrac) = $mant -> length(); 3757 my $expo10adj = $ndigtot - $ndigfrac - 1; 3758 3759 if ($expo10adj != 0) { 3760 return $upgrade -> new($self) -> nparts() if $upgrade; 3761 $mant -> bnan(); 3762 return $mant unless wantarray; 3763 $expo -> badd($expo10adj); 3764 return ($mant, $expo); 3765 } 3766 } 3767 3768 return $mant unless wantarray; 3769 return ($mant, $expo); 3770} 3771 3772sub eparts { 3773 my $self = shift; 3774 my $class = ref $self; 3775 3776 croak("eparts() is an instance method, not a class method") 3777 unless $class; 3778 3779 # Not-a-number and Infinity. 3780 3781 return $self -> sparts() if $self -> is_nan() || $self -> is_inf(); 3782 3783 # Finite number. 3784 3785 my ($mant, $expo) = $self -> sparts(); 3786 3787 if ($mant -> bcmp(0)) { 3788 my $ndigmant = $mant -> length(); 3789 $expo -> badd($ndigmant); 3790 3791 # $c is the number of digits that will be in the integer part of the 3792 # final mantissa. 3793 3794 my $c = $expo -> copy() -> bdec() -> bmod(3) -> binc(); 3795 $expo -> bsub($c); 3796 3797 if ($ndigmant > $c) { 3798 return $upgrade -> new($self) -> eparts() if $upgrade; 3799 $mant -> bnan(); 3800 return $mant unless wantarray; 3801 return ($mant, $expo); 3802 } 3803 3804 $mant -> blsft($c - $ndigmant, 10); 3805 } 3806 3807 return $mant unless wantarray; 3808 return ($mant, $expo); 3809} 3810 3811sub dparts { 3812 my $self = shift; 3813 my $class = ref $self; 3814 3815 croak("dparts() is an instance method, not a class method") 3816 unless $class; 3817 3818 my $int = $self -> copy(); 3819 return $int unless wantarray; 3820 3821 my $frc = $class -> bzero(); 3822 return ($int, $frc); 3823} 3824 3825sub fparts { 3826 my $x = shift; 3827 my $class = ref $x; 3828 3829 croak("fparts() is an instance method") unless $class; 3830 3831 return ($x -> copy(), 3832 $x -> is_nan() ? $class -> bnan() : $class -> bone()); 3833} 3834 3835sub numerator { 3836 my $x = shift; 3837 my $class = ref $x; 3838 3839 croak("numerator() is an instance method") unless $class; 3840 3841 return $x -> copy(); 3842} 3843 3844sub denominator { 3845 my $x = shift; 3846 my $class = ref $x; 3847 3848 croak("denominator() is an instance method") unless $class; 3849 3850 return $x -> is_nan() ? $class -> bnan() : $class -> bone(); 3851} 3852 3853############################################################################### 3854# String conversion methods 3855############################################################################### 3856 3857sub bstr { 3858 my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); 3859 3860 if ($x->{sign} ne '+' && $x->{sign} ne '-') { 3861 return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN 3862 return 'inf'; # +inf 3863 } 3864 my $str = $LIB->_str($x->{value}); 3865 return $x->{sign} eq '-' ? "-$str" : $str; 3866} 3867 3868# Scientific notation with significand/mantissa as an integer, e.g., "12345" is 3869# written as "1.2345e+4". 3870 3871sub bsstr { 3872 my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); 3873 3874 if ($x->{sign} ne '+' && $x->{sign} ne '-') { 3875 return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN 3876 return 'inf'; # +inf 3877 } 3878 my ($m, $e) = $x -> parts(); 3879 my $str = $LIB->_str($m->{value}) . 'e+' . $LIB->_str($e->{value}); 3880 return $x->{sign} eq '-' ? "-$str" : $str; 3881} 3882 3883# Normalized notation, e.g., "12345" is written as "12345e+0". 3884 3885sub bnstr { 3886 my $x = shift; 3887 3888 if ($x->{sign} ne '+' && $x->{sign} ne '-') { 3889 return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN 3890 return 'inf'; # +inf 3891 } 3892 3893 return $x -> bstr() if $x -> is_nan() || $x -> is_inf(); 3894 3895 my ($mant, $expo) = $x -> parts(); 3896 3897 # The "fraction posision" is the position (offset) for the decimal point 3898 # relative to the end of the digit string. 3899 3900 my $fracpos = $mant -> length() - 1; 3901 if ($fracpos == 0) { 3902 my $str = $LIB->_str($mant->{value}) . "e+" . $LIB->_str($expo->{value}); 3903 return $x->{sign} eq '-' ? "-$str" : $str; 3904 } 3905 3906 $expo += $fracpos; 3907 my $mantstr = $LIB->_str($mant -> {value}); 3908 substr($mantstr, -$fracpos, 0) = '.'; 3909 3910 my $str = $mantstr . 'e+' . $LIB->_str($expo -> {value}); 3911 return $x->{sign} eq '-' ? "-$str" : $str; 3912} 3913 3914# Engineering notation, e.g., "12345" is written as "12.345e+3". 3915 3916sub bestr { 3917 my $x = shift; 3918 3919 if ($x->{sign} ne '+' && $x->{sign} ne '-') { 3920 return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN 3921 return 'inf'; # +inf 3922 } 3923 3924 my ($mant, $expo) = $x -> parts(); 3925 3926 my $sign = $mant -> sign(); 3927 $mant -> babs(); 3928 3929 my $mantstr = $LIB->_str($mant -> {value}); 3930 my $mantlen = CORE::length($mantstr); 3931 3932 my $dotidx = 1; 3933 $expo += $mantlen - 1; 3934 3935 my $c = $expo -> copy() -> bmod(3); 3936 $expo -= $c; 3937 $dotidx += $c; 3938 3939 if ($mantlen < $dotidx) { 3940 $mantstr .= "0" x ($dotidx - $mantlen); 3941 } elsif ($mantlen > $dotidx) { 3942 substr($mantstr, $dotidx, 0) = "."; 3943 } 3944 3945 my $str = $mantstr . 'e+' . $LIB->_str($expo -> {value}); 3946 return $sign eq "-" ? "-$str" : $str; 3947} 3948 3949# Decimal notation, e.g., "12345". 3950 3951sub bdstr { 3952 my $x = shift; 3953 3954 if ($x->{sign} ne '+' && $x->{sign} ne '-') { 3955 return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN 3956 return 'inf'; # +inf 3957 } 3958 3959 my $str = $LIB->_str($x->{value}); 3960 return $x->{sign} eq '-' ? "-$str" : $str; 3961} 3962 3963sub to_hex { 3964 # return as hex string, with prefixed 0x 3965 my $x = shift; 3966 $x = __PACKAGE__->new($x) if !ref($x); 3967 3968 return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc 3969 3970 my $hex = $LIB->_to_hex($x->{value}); 3971 return $x->{sign} eq '-' ? "-$hex" : $hex; 3972} 3973 3974sub to_oct { 3975 # return as octal string, with prefixed 0 3976 my $x = shift; 3977 $x = __PACKAGE__->new($x) if !ref($x); 3978 3979 return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc 3980 3981 my $oct = $LIB->_to_oct($x->{value}); 3982 return $x->{sign} eq '-' ? "-$oct" : $oct; 3983} 3984 3985sub to_bin { 3986 # return as binary string, with prefixed 0b 3987 my $x = shift; 3988 $x = __PACKAGE__->new($x) if !ref($x); 3989 3990 return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc 3991 3992 my $bin = $LIB->_to_bin($x->{value}); 3993 return $x->{sign} eq '-' ? "-$bin" : $bin; 3994} 3995 3996sub to_bytes { 3997 # return a byte string 3998 my $x = shift; 3999 $x = __PACKAGE__->new($x) if !ref($x); 4000 4001 croak("to_bytes() requires a finite, non-negative integer") 4002 if $x -> is_neg() || ! $x -> is_int(); 4003 4004 croak("to_bytes() requires a newer version of the $LIB library.") 4005 unless $LIB->can('_to_bytes'); 4006 4007 return $LIB->_to_bytes($x->{value}); 4008} 4009 4010sub to_base { 4011 # return a base anything string 4012 my $x = shift; 4013 $x = __PACKAGE__->new($x) if !ref($x); 4014 4015 croak("the value to convert must be a finite, non-negative integer") 4016 if $x -> is_neg() || !$x -> is_int(); 4017 4018 my $base = shift; 4019 $base = __PACKAGE__->new($base) unless ref($base); 4020 4021 croak("the base must be a finite integer >= 2") 4022 if $base < 2 || ! $base -> is_int(); 4023 4024 # If no collating sequence is given, pass some of the conversions to 4025 # methods optimized for those cases. 4026 4027 if (! @_) { 4028 return $x -> to_bin() if $base == 2; 4029 return $x -> to_oct() if $base == 8; 4030 return uc $x -> to_hex() if $base == 16; 4031 return $x -> bstr() if $base == 10; 4032 } 4033 4034 croak("to_base() requires a newer version of the $LIB library.") 4035 unless $LIB->can('_to_base'); 4036 4037 return $LIB->_to_base($x->{value}, $base -> {value}, @_ ? shift() : ()); 4038} 4039 4040sub to_base_num { 4041 my $x = shift; 4042 my $class = ref $x; 4043 4044 # return a base anything string 4045 croak("the value to convert must be a finite non-negative integer") 4046 if $x -> is_neg() || !$x -> is_int(); 4047 4048 my $base = shift; 4049 $base = $class -> new($base) unless ref $base; 4050 4051 croak("the base must be a finite integer >= 2") 4052 if $base < 2 || ! $base -> is_int(); 4053 4054 croak("to_base() requires a newer version of the $LIB library.") 4055 unless $LIB->can('_to_base'); 4056 4057 # Get a reference to an array of library thingies, and replace each element 4058 # with a Math::BigInt object using that thingy. 4059 4060 my $vals = $LIB -> _to_base_num($x->{value}, $base -> {value}); 4061 4062 for my $i (0 .. $#$vals) { 4063 my $x = $class -> bzero(); 4064 $x -> {value} = $vals -> [$i]; 4065 $vals -> [$i] = $x; 4066 } 4067 4068 return $vals; 4069} 4070 4071sub as_hex { 4072 # return as hex string, with prefixed 0x 4073 my $x = shift; 4074 $x = __PACKAGE__->new($x) if !ref($x); 4075 4076 return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc 4077 4078 my $hex = $LIB->_as_hex($x->{value}); 4079 return $x->{sign} eq '-' ? "-$hex" : $hex; 4080} 4081 4082sub as_oct { 4083 # return as octal string, with prefixed 0 4084 my $x = shift; 4085 $x = __PACKAGE__->new($x) if !ref($x); 4086 4087 return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc 4088 4089 my $oct = $LIB->_as_oct($x->{value}); 4090 return $x->{sign} eq '-' ? "-$oct" : $oct; 4091} 4092 4093sub as_bin { 4094 # return as binary string, with prefixed 0b 4095 my $x = shift; 4096 $x = __PACKAGE__->new($x) if !ref($x); 4097 4098 return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc 4099 4100 my $bin = $LIB->_as_bin($x->{value}); 4101 return $x->{sign} eq '-' ? "-$bin" : $bin; 4102} 4103 4104*as_bytes = \&to_bytes; 4105 4106############################################################################### 4107# Other conversion methods 4108############################################################################### 4109 4110sub numify { 4111 # Make a Perl scalar number from a Math::BigInt object. 4112 my $x = shift; 4113 $x = __PACKAGE__->new($x) unless ref $x; 4114 4115 if ($x -> is_nan()) { 4116 require Math::Complex; 4117 my $inf = $Math::Complex::Inf; 4118 return $inf - $inf; 4119 } 4120 4121 if ($x -> is_inf()) { 4122 require Math::Complex; 4123 my $inf = $Math::Complex::Inf; 4124 return $x -> is_negative() ? -$inf : $inf; 4125 } 4126 4127 my $num = 0 + $LIB->_num($x->{value}); 4128 return $x->{sign} eq '-' ? -$num : $num; 4129} 4130 4131############################################################################### 4132# Private methods and functions. 4133############################################################################### 4134 4135sub objectify { 4136 # Convert strings and "foreign objects" to the objects we want. 4137 4138 # The first argument, $count, is the number of following arguments that 4139 # objectify() looks at and converts to objects. The first is a classname. 4140 # If the given count is 0, all arguments will be used. 4141 4142 # After the count is read, objectify obtains the name of the class to which 4143 # the following arguments are converted. If the second argument is a 4144 # reference, use the reference type as the class name. Otherwise, if it is 4145 # a string that looks like a class name, use that. Otherwise, use $class. 4146 4147 # Caller: Gives us: 4148 # 4149 # $x->badd(1); => ref x, scalar y 4150 # Class->badd(1, 2); => classname x (scalar), scalar x, scalar y 4151 # Class->badd(Class->(1), 2); => classname x (scalar), ref x, scalar y 4152 # Math::BigInt::badd(1, 2); => scalar x, scalar y 4153 4154 # A shortcut for the common case $x->unary_op(), in which case the argument 4155 # list is (0, $x) or (1, $x). 4156 4157 return (ref($_[1]), $_[1]) if @_ == 2 && ($_[0] || 0) == 1 && ref($_[1]); 4158 4159 # Check the context. 4160 4161 unless (wantarray) { 4162 croak(__PACKAGE__ . "::objectify() needs list context"); 4163 } 4164 4165 # Get the number of arguments to objectify. 4166 4167 my $count = shift; 4168 4169 # Initialize the output array. 4170 4171 my @a = @_; 4172 4173 # If the first argument is a reference, use that reference type as our 4174 # class name. Otherwise, if the first argument looks like a class name, 4175 # then use that as our class name. Otherwise, use the default class name. 4176 4177 my $class; 4178 if (ref($a[0])) { # reference? 4179 $class = ref($a[0]); 4180 } elsif ($a[0] =~ /^[A-Z].*::/) { # string with class name? 4181 $class = shift @a; 4182 } else { 4183 $class = __PACKAGE__; # default class name 4184 } 4185 4186 $count ||= @a; 4187 unshift @a, $class; 4188 4189 no strict 'refs'; 4190 4191 # What we upgrade to, if anything. Note that we need the whole upgrade 4192 # chain, since there might be multiple levels of upgrading. E.g., class A 4193 # upgrades to class B, which upgrades to class C. Delay getting the chain 4194 # until we actually need it. 4195 4196 my @upg = (); 4197 my $have_upgrade_chain = 0; 4198 4199 # Disable downgrading, because Math::BigFloat -> foo('1.0', '2.0') needs 4200 # floats. 4201 4202 my $down; 4203 if (defined ${"$a[0]::downgrade"}) { 4204 $down = ${"$a[0]::downgrade"}; 4205 ${"$a[0]::downgrade"} = undef; 4206 } 4207 4208 ARG: for my $i (1 .. $count) { 4209 4210 my $ref = ref $a[$i]; 4211 4212 # Perl scalars are fed to the appropriate constructor. 4213 4214 unless ($ref) { 4215 $a[$i] = $a[0] -> new($a[$i]); 4216 next; 4217 } 4218 4219 # If it is an object of the right class, all is fine. 4220 4221 next if $ref -> isa($a[0]); 4222 4223 # Upgrading is OK, so skip further tests if the argument is upgraded, 4224 # but first get the whole upgrade chain if we haven't got it yet. 4225 4226 unless ($have_upgrade_chain) { 4227 my $cls = $class; 4228 my $upg = $cls -> upgrade(); 4229 while (defined $upg) { 4230 last if $upg eq $cls; 4231 push @upg, $upg; 4232 $cls = $upg; 4233 $upg = $cls -> upgrade(); 4234 } 4235 $have_upgrade_chain = 1; 4236 } 4237 4238 for my $upg (@upg) { 4239 next ARG if $ref -> isa($upg); 4240 } 4241 4242 # See if we can call one of the as_xxx() methods. We don't know whether 4243 # the as_xxx() method returns an object or a scalar, so re-check 4244 # afterwards. 4245 4246 my $recheck = 0; 4247 4248 if ($a[0] -> isa('Math::BigInt')) { 4249 if ($a[$i] -> can('as_int')) { 4250 $a[$i] = $a[$i] -> as_int(); 4251 $recheck = 1; 4252 } elsif ($a[$i] -> can('as_number')) { 4253 $a[$i] = $a[$i] -> as_number(); 4254 $recheck = 1; 4255 } 4256 } 4257 4258 elsif ($a[0] -> isa('Math::BigFloat')) { 4259 if ($a[$i] -> can('as_float')) { 4260 $a[$i] = $a[$i] -> as_float(); 4261 $recheck = $1; 4262 } 4263 } 4264 4265 # If we called one of the as_xxx() methods, recheck. 4266 4267 if ($recheck) { 4268 $ref = ref($a[$i]); 4269 4270 # Perl scalars are fed to the appropriate constructor. 4271 4272 unless ($ref) { 4273 $a[$i] = $a[0] -> new($a[$i]); 4274 next; 4275 } 4276 4277 # If it is an object of the right class, all is fine. 4278 4279 next if $ref -> isa($a[0]); 4280 } 4281 4282 # Last resort. 4283 4284 $a[$i] = $a[0] -> new($a[$i]); 4285 } 4286 4287 # Reset the downgrading. 4288 4289 ${"$a[0]::downgrade"} = $down; 4290 4291 return @a; 4292} 4293 4294sub import { 4295 my $class = shift; 4296 $IMPORT++; # remember we did import() 4297 my @a; # unrecognized arguments 4298 4299 while (@_) { 4300 my $param = shift; 4301 4302 # Enable overloading of constants. 4303 4304 if ($param eq ':constant') { 4305 overload::constant 4306 4307 integer => sub { 4308 $class -> new(shift); 4309 }, 4310 4311 float => sub { 4312 $class -> new(shift); 4313 }, 4314 4315 binary => sub { 4316 # E.g., a literal 0377 shall result in an object whose value 4317 # is decimal 255, but new("0377") returns decimal 377. 4318 return $class -> from_oct($_[0]) if $_[0] =~ /^0_*[0-7]/; 4319 $class -> new(shift); 4320 }; 4321 next; 4322 } 4323 4324 # Upgrading. 4325 4326 if ($param eq 'upgrade') { 4327 $class -> upgrade(shift); 4328 next; 4329 } 4330 4331 # Downgrading. 4332 4333 if ($param eq 'downgrade') { 4334 $class -> downgrade(shift); 4335 next; 4336 } 4337 4338 # Accuracy. 4339 4340 if ($param eq 'accuracy') { 4341 $class -> accuracy(shift); 4342 next; 4343 } 4344 4345 # Precision. 4346 4347 if ($param eq 'precision') { 4348 $class -> precision(shift); 4349 next; 4350 } 4351 4352 # Rounding mode. 4353 4354 if ($param eq 'round_mode') { 4355 $class -> round_mode(shift); 4356 next; 4357 } 4358 4359 # Backend library. 4360 4361 if ($param =~ /^(lib|try|only)\z/) { 4362 # try => 0 (no warn if unavailable module) 4363 # lib => 1 (warn on fallback) 4364 # only => 2 (die on fallback) 4365 4366 # Get the list of user-specified libraries. 4367 4368 croak "Library argument for import parameter '$param' is missing" 4369 unless @_; 4370 my $libs = shift; 4371 croak "Library argument for import parameter '$param' is undefined" 4372 unless defined($libs); 4373 4374 # Check and clean up the list of user-specified libraries. 4375 4376 my @libs; 4377 for my $lib (split /,/, $libs) { 4378 $lib =~ s/^\s+//; 4379 $lib =~ s/\s+$//; 4380 4381 if ($lib =~ /[^a-zA-Z0-9_:]/) { 4382 carp "Library name '$lib' contains invalid characters"; 4383 next; 4384 } 4385 4386 if (! CORE::length $lib) { 4387 carp "Library name is empty"; 4388 next; 4389 } 4390 4391 $lib = "Math::BigInt::$lib" if $lib !~ /^Math::BigInt::/i; 4392 4393 # If a library has already been loaded, that is OK only if the 4394 # requested library is identical to the loaded one. 4395 4396 if (defined($LIB)) { 4397 if ($lib ne $LIB) { 4398 #carp "Library '$LIB' has already been loaded, so", 4399 # " ignoring requested library '$lib'"; 4400 } 4401 next; 4402 } 4403 4404 push @libs, $lib; 4405 } 4406 4407 next if defined $LIB; 4408 4409 croak "Library list contains no valid libraries" unless @libs; 4410 4411 # Try to load the specified libraries, if any. 4412 4413 for (my $i = 0 ; $i <= $#libs ; $i++) { 4414 my $lib = $libs[$i]; 4415 eval "require $lib"; 4416 unless ($@) { 4417 $LIB = $lib; 4418 last; 4419 } 4420 } 4421 4422 next if defined $LIB; 4423 4424 # No library has been loaded, and none of the requested libraries 4425 # could be loaded, and fallback and the user doesn't allow fallback. 4426 4427 if ($param eq 'only') { 4428 croak "Couldn't load the specified math lib(s) ", 4429 join(", ", map "'$_'", @libs), 4430 ", and fallback to '$DEFAULT_LIB' is not allowed"; 4431 } 4432 4433 # No library has been loaded, and none of the requested libraries 4434 # could be loaded, but the user accepts the use of a fallback 4435 # library, so try to load it. 4436 4437 eval "require $DEFAULT_LIB"; 4438 if ($@) { 4439 croak "Couldn't load the specified math lib(s) ", 4440 join(", ", map "'$_'", @libs), 4441 ", not even the fallback lib '$DEFAULT_LIB'"; 4442 } 4443 4444 # The fallback library was successfully loaded, but the user 4445 # might want to know that we are using the fallback. 4446 4447 if ($param eq 'lib') { 4448 carp "Couldn't load the specified math lib(s) ", 4449 join(", ", map "'$_'", @libs), 4450 ", so using fallback lib '$DEFAULT_LIB'"; 4451 } 4452 4453 next; 4454 } 4455 4456 # Unrecognized parameter. 4457 4458 push @a, $param; 4459 } 4460 4461 # Any non-':constant' stuff is handled by our parent, Exporter 4462 4463 if (@a) { 4464 $class->SUPER::import(@a); # need it for subclasses 4465 $class->export_to_level(1, $class, @a); # need it for Math::BigFloat 4466 } 4467 4468 # We might not have loaded any backend library yet, either because the user 4469 # didn't specify any, or because the specified libraries failed to load and 4470 # the user allows the use of a fallback library. 4471 4472 unless (defined $LIB) { 4473 eval "require $DEFAULT_LIB"; 4474 if ($@) { 4475 croak "No lib specified, and couldn't load the default", 4476 " lib '$DEFAULT_LIB'"; 4477 } 4478 $LIB = $DEFAULT_LIB; 4479 } 4480 4481 # import done 4482} 4483 4484sub _split { 4485 # input: num_str; output: undef for invalid or 4486 # (\$mantissa_sign, \$mantissa_value, \$mantissa_fraction, 4487 # \$exp_sign, \$exp_value) 4488 # Internal, take apart a string and return the pieces. 4489 # Strip leading/trailing whitespace, leading zeros, underscore and reject 4490 # invalid input. 4491 my $x = shift; 4492 4493 # strip white space at front, also extraneous leading zeros 4494 $x =~ s/^\s*([-]?)0*([0-9])/$1$2/g; # will not strip ' .2' 4495 $x =~ s/^\s+//; # but this will 4496 $x =~ s/\s+$//g; # strip white space at end 4497 4498 # shortcut, if nothing to split, return early 4499 if ($x =~ /^[+-]?[0-9]+\z/) { 4500 $x =~ s/^([+-])0*([0-9])/$2/; 4501 my $sign = $1 || '+'; 4502 return (\$sign, \$x, \'', \'', \0); 4503 } 4504 4505 # invalid starting char? 4506 return if $x !~ /^[+-]?(\.?[0-9]|0b[0-1]|0x[0-9a-fA-F])/; 4507 4508 return Math::BigInt->from_hex($x) if $x =~ /^[+-]?0x/; # hex string 4509 return Math::BigInt->from_bin($x) if $x =~ /^[+-]?0b/; # binary string 4510 4511 # strip underscores between digits 4512 $x =~ s/([0-9])_([0-9])/$1$2/g; 4513 $x =~ s/([0-9])_([0-9])/$1$2/g; # do twice for 1_2_3 4514 4515 # some possible inputs: 4516 # 2.1234 # 0.12 # 1 # 1E1 # 2.134E1 # 434E-10 # 1.02009E-2 4517 # .2 # 1_2_3.4_5_6 # 1.4E1_2_3 # 1e3 # +.2 # 0e999 4518 4519 my ($m, $e, $last) = split /[Ee]/, $x; 4520 return if defined $last; # last defined => 1e2E3 or others 4521 $e = '0' if !defined $e || $e eq ""; 4522 4523 # sign, value for exponent, mantint, mantfrac 4524 my ($es, $ev, $mis, $miv, $mfv); 4525 # valid exponent? 4526 if ($e =~ /^([+-]?)0*([0-9]+)$/) # strip leading zeros 4527 { 4528 $es = $1; 4529 $ev = $2; 4530 # valid mantissa? 4531 return if $m eq '.' || $m eq ''; 4532 my ($mi, $mf, $lastf) = split /\./, $m; 4533 return if defined $lastf; # lastf defined => 1.2.3 or others 4534 $mi = '0' if !defined $mi; 4535 $mi .= '0' if $mi =~ /^[\-\+]?$/; 4536 $mf = '0' if !defined $mf || $mf eq ''; 4537 if ($mi =~ /^([+-]?)0*([0-9]+)$/) # strip leading zeros 4538 { 4539 $mis = $1 || '+'; 4540 $miv = $2; 4541 return unless ($mf =~ /^([0-9]*?)0*$/); # strip trailing zeros 4542 $mfv = $1; 4543 # handle the 0e999 case here 4544 $ev = 0 if $miv eq '0' && $mfv eq ''; 4545 return (\$mis, \$miv, \$mfv, \$es, \$ev); 4546 } 4547 } 4548 return; # NaN, not a number 4549} 4550 4551sub _e_add { 4552 # Internal helper sub to take two positive integers and their signs and 4553 # then add them. Input ($LIB, $LIB, ('+'|'-'), ('+'|'-')), output 4554 # ($LIB, ('+'|'-')). 4555 4556 my ($x, $y, $xs, $ys) = @_; 4557 4558 # if the signs are equal we can add them (-5 + -3 => -(5 + 3) => -8) 4559 if ($xs eq $ys) { 4560 $x = $LIB->_add($x, $y); # +a + +b or -a + -b 4561 } else { 4562 my $a = $LIB->_acmp($x, $y); 4563 if ($a == 0) { 4564 # This does NOT modify $x in-place. TODO: Fix this? 4565 $x = $LIB->_zero(); # result is 0 4566 $xs = '+'; 4567 return ($x, $xs); 4568 } 4569 if ($a > 0) { 4570 $x = $LIB->_sub($x, $y); # abs sub 4571 } else { # a < 0 4572 $x = $LIB->_sub ($y, $x, 1); # abs sub 4573 $xs = $ys; 4574 } 4575 } 4576 4577 $xs = '+' if $xs eq '-' && $LIB->_is_zero($x); # no "-0" 4578 4579 return ($x, $xs); 4580} 4581 4582sub _e_sub { 4583 # Internal helper sub to take two positive integers and their signs and 4584 # then subtract them. Input ($LIB, $LIB, ('+'|'-'), ('+'|'-')), 4585 # output ($LIB, ('+'|'-')) 4586 my ($x, $y, $xs, $ys) = @_; 4587 4588 # flip sign 4589 $ys = $ys eq '+' ? '-' : '+'; # swap sign of second operand ... 4590 _e_add($x, $y, $xs, $ys); # ... and let _e_add() do the job 4591 #$LIB -> _sadd($x, $xs, $y, $ys); # ... and let $LIB -> _sadd() do the job 4592} 4593 4594sub _trailing_zeros { 4595 # return the amount of trailing zeros in $x (as scalar) 4596 my $x = shift; 4597 $x = __PACKAGE__->new($x) unless ref $x; 4598 4599 return 0 if $x->{sign} !~ /^[+-]$/; # NaN, inf, -inf etc 4600 4601 $LIB->_zeros($x->{value}); # must handle odd values, 0 etc 4602} 4603 4604sub _scan_for_nonzero { 4605 # internal, used by bround() to scan for non-zeros after a '5' 4606 my ($x, $pad, $xs, $len) = @_; 4607 4608 return 0 if $len == 1; # "5" is trailed by invisible zeros 4609 my $follow = $pad - 1; 4610 return 0 if $follow > $len || $follow < 1; 4611 4612 # use the string form to check whether only '0's follow or not 4613 substr ($xs, -$follow) =~ /[^0]/ ? 1 : 0; 4614} 4615 4616sub _find_round_parameters { 4617 # After any operation or when calling round(), the result is rounded by 4618 # regarding the A & P from arguments, local parameters, or globals. 4619 4620 # !!!!!!! If you change this, remember to change round(), too! !!!!!!!!!! 4621 4622 # This procedure finds the round parameters, but it is for speed reasons 4623 # duplicated in round. Otherwise, it is tested by the testsuite and used 4624 # by bdiv(). 4625 4626 # returns ($self) or ($self, $a, $p, $r) - sets $self to NaN of both A and P 4627 # were requested/defined (locally or globally or both) 4628 4629 my ($self, $a, $p, $r, @args) = @_; 4630 # $a accuracy, if given by caller 4631 # $p precision, if given by caller 4632 # $r round_mode, if given by caller 4633 # @args all 'other' arguments (0 for unary, 1 for binary ops) 4634 4635 my $class = ref($self); # find out class of argument(s) 4636 no strict 'refs'; 4637 4638 # convert to normal scalar for speed and correctness in inner parts 4639 $a = $a->can('numify') ? $a->numify() : "$a" if defined $a && ref($a); 4640 $p = $p->can('numify') ? $p->numify() : "$p" if defined $p && ref($p); 4641 4642 # now pick $a or $p, but only if we have got "arguments" 4643 if (!defined $a) { 4644 foreach ($self, @args) { 4645 # take the defined one, or if both defined, the one that is smaller 4646 $a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a); 4647 } 4648 } 4649 if (!defined $p) { 4650 # even if $a is defined, take $p, to signal error for both defined 4651 foreach ($self, @args) { 4652 # take the defined one, or if both defined, the one that is bigger 4653 # -2 > -3, and 3 > 2 4654 $p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p); 4655 } 4656 } 4657 4658 # if still none defined, use globals (#2) 4659 $a = ${"$class\::accuracy"} unless defined $a; 4660 $p = ${"$class\::precision"} unless defined $p; 4661 4662 # A == 0 is useless, so undef it to signal no rounding 4663 $a = undef if defined $a && $a == 0; 4664 4665 # no rounding today? 4666 return ($self) unless defined $a || defined $p; # early out 4667 4668 # set A and set P is an fatal error 4669 return ($self->bnan()) if defined $a && defined $p; # error 4670 4671 $r = ${"$class\::round_mode"} unless defined $r; 4672 if ($r !~ /^(even|odd|[+-]inf|zero|trunc|common)$/) { 4673 croak("Unknown round mode '$r'"); 4674 } 4675 4676 $a = int($a) if defined $a; 4677 $p = int($p) if defined $p; 4678 4679 ($self, $a, $p, $r); 4680} 4681 4682# Trims the sign of the significand, the (absolute value of the) significand, 4683# the sign of the exponent, and the (absolute value of the) exponent. The 4684# returned values have no underscores ("_") or unnecessary leading or trailing 4685# zeros. 4686 4687sub _trim_split_parts { 4688 shift; 4689 4690 my $sig_sgn = shift() || '+'; 4691 my $sig_str = shift() || '0'; 4692 my $exp_sgn = shift() || '+'; 4693 my $exp_str = shift() || '0'; 4694 4695 $sig_str =~ tr/_//d; # "1.0_0_0" -> "1.000" 4696 $sig_str =~ s/^0+//; # "01.000" -> "1.000" 4697 $sig_str =~ s/\.0*$// # "1.000" -> "1" 4698 || $sig_str =~ s/(\..*[^0])0+$/$1/; # "1.010" -> "1.01" 4699 $sig_str = '0' unless CORE::length($sig_str); 4700 4701 return '+', '0', '+', '0' if $sig_str eq '0'; 4702 4703 $exp_str =~ tr/_//d; # "01_234" -> "01234" 4704 $exp_str =~ s/^0+//; # "01234" -> "1234" 4705 $exp_str = '0' unless CORE::length($exp_str); 4706 4707 return $sig_sgn, $sig_str, $exp_sgn, $exp_str; 4708} 4709 4710# Takes any string representing a valid decimal number and splits it into four 4711# strings: the sign of the significand, the absolute value of the significand, 4712# the sign of the exponent, and the absolute value of the exponent. Both the 4713# significand and the exponent are in base 10. 4714# 4715# Perl accepts literals like the following. The value is 100.1. 4716# 4717# 1__0__.__0__1__e+0__1__ (prints "Misplaced _ in number") 4718# 1_0.0_1e+0_1 4719# 4720# Strings representing decimal numbers do not allow underscores, so only the 4721# following is valid 4722# 4723# "10.01e+01" 4724 4725sub _dec_str_to_str_parts { 4726 my $class = shift; 4727 my $str = shift; 4728 4729 if ($str =~ / 4730 ^ 4731 4732 # optional leading whitespace 4733 \s* 4734 4735 # optional sign 4736 ( [+-]? ) 4737 4738 # significand 4739 ( 4740 # integer part and optional fraction part ... 4741 \d+ (?: _+ \d+ )* _* 4742 (?: 4743 \. 4744 (?: _* \d+ (?: _+ \d+ )* _* )? 4745 )? 4746 | 4747 # ... or mandatory fraction part 4748 \. 4749 \d+ (?: _+ \d+ )* _* 4750 ) 4751 4752 # optional exponent 4753 (?: 4754 [Ee] 4755 ( [+-]? ) 4756 ( \d+ (?: _+ \d+ )* _* ) 4757 )? 4758 4759 # optional trailing whitespace 4760 \s* 4761 4762 $ 4763 /x) 4764 { 4765 return $class -> _trim_split_parts($1, $2, $3, $4); 4766 } 4767 4768 return; 4769} 4770 4771# Takes any string representing a valid hexadecimal number and splits it into 4772# four strings: the sign of the significand, the absolute value of the 4773# significand, the sign of the exponent, and the absolute value of the exponent. 4774# The significand is in base 16, and the exponent is in base 2. 4775# 4776# Perl accepts literals like the following. The "x" might be a capital "X". The 4777# value is 32.0078125. 4778# 4779# 0x__1__0__.0__1__p+0__1__ (prints "Misplaced _ in number") 4780# 0x1_0.0_1p+0_1 4781# 4782# The CORE::hex() function does not accept floating point accepts 4783# 4784# "0x_1_0" 4785# "x_1_0" 4786# "_1_0" 4787 4788sub _hex_str_to_str_parts { 4789 my $class = shift; 4790 my $str = shift; 4791 4792 if ($str =~ / 4793 ^ 4794 4795 # optional leading whitespace 4796 \s* 4797 4798 # optional sign 4799 ( [+-]? ) 4800 4801 # optional hex prefix 4802 (?: 0? [Xx] _* )? 4803 4804 # significand using the hex digits 0..9 and a..f 4805 ( 4806 # integer part and optional fraction part ... 4807 [0-9a-fA-F]+ (?: _+ [0-9a-fA-F]+ )* _* 4808 (?: 4809 \. 4810 (?: _* [0-9a-fA-F]+ (?: _+ [0-9a-fA-F]+ )* _* )? 4811 )? 4812 | 4813 # ... or mandatory fraction part 4814 \. 4815 [0-9a-fA-F]+ (?: _+ [0-9a-fA-F]+ )* _* 4816 ) 4817 4818 # optional exponent (power of 2) using decimal digits 4819 (?: 4820 [Pp] 4821 ( [+-]? ) 4822 ( \d+ (?: _+ \d+ )* _* ) 4823 )? 4824 4825 # optional trailing whitespace 4826 \s* 4827 4828 $ 4829 /x) 4830 { 4831 return $class -> _trim_split_parts($1, $2, $3, $4); 4832 } 4833 4834 return; 4835} 4836 4837# Takes any string representing a valid octal number and splits it into four 4838# strings: the sign of the significand, the absolute value of the significand, 4839# the sign of the exponent, and the absolute value of the exponent. The 4840# significand is in base 8, and the exponent is in base 2. 4841 4842sub _oct_str_to_str_parts { 4843 my $class = shift; 4844 my $str = shift; 4845 4846 if ($str =~ / 4847 ^ 4848 4849 # optional leading whitespace 4850 \s* 4851 4852 # optional sign 4853 ( [+-]? ) 4854 4855 # optional octal prefix 4856 (?: 0? [Oo] _* )? 4857 4858 # significand using the octal digits 0..7 4859 ( 4860 # integer part and optional fraction part ... 4861 [0-7]+ (?: _+ [0-7]+ )* _* 4862 (?: 4863 \. 4864 (?: _* [0-7]+ (?: _+ [0-7]+ )* _* )? 4865 )? 4866 | 4867 # ... or mandatory fraction part 4868 \. 4869 [0-7]+ (?: _+ [0-7]+ )* _* 4870 ) 4871 4872 # optional exponent (power of 2) using decimal digits 4873 (?: 4874 [Pp] 4875 ( [+-]? ) 4876 ( \d+ (?: _+ \d+ )* _* ) 4877 )? 4878 4879 # optional trailing whitespace 4880 \s* 4881 4882 $ 4883 /x) 4884 { 4885 return $class -> _trim_split_parts($1, $2, $3, $4); 4886 } 4887 4888 return; 4889} 4890 4891# Takes any string representing a valid binary number and splits it into four 4892# strings: the sign of the significand, the absolute value of the significand, 4893# the sign of the exponent, and the absolute value of the exponent. The 4894# significand is in base 2, and the exponent is in base 2. 4895 4896sub _bin_str_to_str_parts { 4897 my $class = shift; 4898 my $str = shift; 4899 4900 if ($str =~ / 4901 ^ 4902 4903 # optional leading whitespace 4904 \s* 4905 4906 # optional sign 4907 ( [+-]? ) 4908 4909 # optional binary prefix 4910 (?: 0? [Bb] _* )? 4911 4912 # significand using the binary digits 0 and 1 4913 ( 4914 # integer part and optional fraction part ... 4915 [01]+ (?: _+ [01]+ )* _* 4916 (?: 4917 \. 4918 (?: _* [01]+ (?: _+ [01]+ )* _* )? 4919 )? 4920 | 4921 # ... or mandatory fraction part 4922 \. 4923 [01]+ (?: _+ [01]+ )* _* 4924 ) 4925 4926 # optional exponent (power of 2) using decimal digits 4927 (?: 4928 [Pp] 4929 ( [+-]? ) 4930 ( \d+ (?: _+ \d+ )* _* ) 4931 )? 4932 4933 # optional trailing whitespace 4934 \s* 4935 4936 $ 4937 /x) 4938 { 4939 return $class -> _trim_split_parts($1, $2, $3, $4); 4940 } 4941 4942 return; 4943} 4944 4945# Takes any string representing a valid decimal number and splits it into four 4946# parts: the sign of the significand, the absolute value of the significand as a 4947# libray thingy, the sign of the exponent, and the absolute value of the 4948# exponent as a library thingy. 4949 4950sub _dec_parts_to_lib_parts { 4951 shift; 4952 4953 my ($sig_sgn, $sig_str, $exp_sgn, $exp_str) = @_; 4954 4955 # Handle zero. 4956 4957 if ($sig_str eq '0') { 4958 return '+', $LIB -> _zero(), '+', $LIB -> _zero(); 4959 } 4960 4961 # Absolute value of exponent as library "object". 4962 4963 my $exp_lib = $LIB -> _new($exp_str); 4964 4965 # If there is a dot in the significand, remove it so the significand 4966 # becomes an integer and adjust the exponent accordingly. Also remove 4967 # leading zeros which might now appear in the significand. E.g., 4968 # 4969 # 12.345e-2 -> 12345e-5 4970 # 12.345e+2 -> 12345e-1 4971 # 0.0123e+5 -> 00123e+1 -> 123e+1 4972 4973 my $idx = index $sig_str, '.'; 4974 if ($idx >= 0) { 4975 substr($sig_str, $idx, 1) = ''; 4976 4977 # delta = length - index 4978 my $delta = $LIB -> _new(CORE::length($sig_str)); 4979 $delta = $LIB -> _sub($delta, $LIB -> _new($idx)); 4980 4981 # exponent - delta 4982 ($exp_lib, $exp_sgn) = _e_sub($exp_lib, $delta, $exp_sgn, '+'); 4983 #($exp_lib, $exp_sgn) = $LIB -> _ssub($exp_lib, $exp_sgn, $delta, '+'); 4984 4985 $sig_str =~ s/^0+//; 4986 } 4987 4988 # If there are trailing zeros in the significand, remove them and 4989 # adjust the exponent. E.g., 4990 # 4991 # 12340e-5 -> 1234e-4 4992 # 12340e-1 -> 1234e0 4993 # 12340e+3 -> 1234e4 4994 4995 if ($sig_str =~ s/(0+)\z//) { 4996 my $len = CORE::length($1); 4997 ($exp_lib, $exp_sgn) = 4998 $LIB -> _sadd($exp_lib, $exp_sgn, $LIB -> _new($len), '+'); 4999 } 5000 5001 # At this point, the significand is empty or an integer with no trailing 5002 # zeros. The exponent is in base 10. 5003 5004 unless (CORE::length $sig_str) { 5005 return '+', $LIB -> _zero(), '+', $LIB -> _zero(); 5006 } 5007 5008 # Absolute value of significand as library "object". 5009 5010 my $sig_lib = $LIB -> _new($sig_str); 5011 5012 return $sig_sgn, $sig_lib, $exp_sgn, $exp_lib; 5013} 5014 5015# Takes any string representing a valid binary number and splits it into four 5016# parts: the sign of the significand, the absolute value of the significand as a 5017# libray thingy, the sign of the exponent, and the absolute value of the 5018# exponent as a library thingy. 5019 5020sub _bin_parts_to_lib_parts { 5021 shift; 5022 5023 my ($sig_sgn, $sig_str, $exp_sgn, $exp_str, $bpc) = @_; 5024 my $bpc_lib = $LIB -> _new($bpc); 5025 5026 # Handle zero. 5027 5028 if ($sig_str eq '0') { 5029 return '+', $LIB -> _zero(), '+', $LIB -> _zero(); 5030 } 5031 5032 # Absolute value of exponent as library "object". 5033 5034 my $exp_lib = $LIB -> _new($exp_str); 5035 5036 # If there is a dot in the significand, remove it so the significand 5037 # becomes an integer and adjust the exponent accordingly. Also remove 5038 # leading zeros which might now appear in the significand. E.g., with 5039 # hexadecimal numbers 5040 # 5041 # 12.345p-2 -> 12345p-14 5042 # 12.345p+2 -> 12345p-10 5043 # 0.0123p+5 -> 00123p-11 -> 123p-11 5044 5045 my $idx = index $sig_str, '.'; 5046 if ($idx >= 0) { 5047 substr($sig_str, $idx, 1) = ''; 5048 5049 # delta = (length - index) * bpc 5050 my $delta = $LIB -> _new(CORE::length($sig_str)); 5051 $delta = $LIB -> _sub($delta, $LIB -> _new($idx)); 5052 $delta = $LIB -> _mul($delta, $bpc_lib) if $bpc != 1; 5053 5054 # exponent - delta 5055 ($exp_lib, $exp_sgn) = _e_sub($exp_lib, $delta, $exp_sgn, '+'); 5056 #($exp_lib, $exp_sgn) = $LIB -> _ssub($exp_lib, $exp_sgn, $delta, '+'); 5057 5058 $sig_str =~ s/^0+//; 5059 } 5060 5061 # If there are trailing zeros in the significand, remove them and 5062 # adjust the exponent accordingly. E.g., with hexadecimal numbers 5063 # 5064 # 12340p-5 -> 1234p-1 5065 # 12340p-1 -> 1234p+3 5066 # 12340p+3 -> 1234p+7 5067 5068 if ($sig_str =~ s/(0+)\z//) { 5069 5070 # delta = length * bpc 5071 my $delta = $LIB -> _new(CORE::length($1)); 5072 $delta = $LIB -> _mul($delta, $bpc_lib) if $bpc != 1; 5073 5074 # exponent + delta 5075 ($exp_lib, $exp_sgn) = $LIB -> _sadd($exp_lib, $exp_sgn, $delta, '+'); 5076 } 5077 5078 # At this point, the significand is empty or an integer with no leading 5079 # or trailing zeros. The exponent is in base 2. 5080 5081 unless (CORE::length $sig_str) { 5082 return '+', $LIB -> _zero(), '+', $LIB -> _zero(); 5083 } 5084 5085 # Absolute value of significand as library "object". 5086 5087 my $sig_lib = $bpc == 1 ? $LIB -> _from_bin('0b' . $sig_str) 5088 : $bpc == 3 ? $LIB -> _from_oct('0' . $sig_str) 5089 : $bpc == 4 ? $LIB -> _from_hex('0x' . $sig_str) 5090 : die "internal error: invalid exponent multiplier"; 5091 5092 # If the exponent (in base 2) is positive or zero ... 5093 5094 if ($exp_sgn eq '+') { 5095 5096 if (!$LIB -> _is_zero($exp_lib)) { 5097 5098 # Multiply significand by 2 raised to the exponent. 5099 5100 my $p = $LIB -> _pow($LIB -> _two(), $exp_lib); 5101 $sig_lib = $LIB -> _mul($sig_lib, $p); 5102 $exp_lib = $LIB -> _zero(); 5103 } 5104 } 5105 5106 # ... else if the exponent is negative ... 5107 5108 else { 5109 5110 # Rather than dividing the significand by 2 raised to the absolute 5111 # value of the exponent, multiply the significand by 5 raised to the 5112 # absolute value of the exponent and let the exponent be in base 10: 5113 # 5114 # a * 2^(-b) = a * 5^b * 10^(-b) = c * 10^(-b), where c = a * 5^b 5115 5116 my $p = $LIB -> _pow($LIB -> _new("5"), $exp_lib); 5117 $sig_lib = $LIB -> _mul($sig_lib, $p); 5118 } 5119 5120 # Adjust for the case when the conversion to decimal introduced trailing 5121 # zeros in the significand. 5122 5123 my $n = $LIB -> _zeros($sig_lib); 5124 if ($n) { 5125 $n = $LIB -> _new($n); 5126 $sig_lib = $LIB -> _rsft($sig_lib, $n, 10); 5127 ($exp_lib, $exp_sgn) = $LIB -> _sadd($exp_lib, $exp_sgn, $n, '+'); 5128 } 5129 5130 return $sig_sgn, $sig_lib, $exp_sgn, $exp_lib; 5131} 5132 5133# Takes any string representing a valid hexadecimal number and splits it into 5134# four parts: the sign of the significand, the absolute value of the significand 5135# as a libray thingy, the sign of the exponent, and the absolute value of the 5136# exponent as a library thingy. 5137 5138sub _hex_str_to_lib_parts { 5139 my $class = shift; 5140 my $str = shift; 5141 if (my @parts = $class -> _hex_str_to_str_parts($str)) { 5142 return $class -> _bin_parts_to_lib_parts(@parts, 4); # 4 bits pr. chr 5143 } 5144 return; 5145} 5146 5147# Takes any string representing a valid octal number and splits it into four 5148# parts: the sign of the significand, the absolute value of the significand as a 5149# libray thingy, the sign of the exponent, and the absolute value of the 5150# exponent as a library thingy. 5151 5152sub _oct_str_to_lib_parts { 5153 my $class = shift; 5154 my $str = shift; 5155 if (my @parts = $class -> _oct_str_to_str_parts($str)) { 5156 return $class -> _bin_parts_to_lib_parts(@parts, 3); # 3 bits pr. chr 5157 } 5158 return; 5159} 5160 5161# Takes any string representing a valid binary number and splits it into four 5162# parts: the sign of the significand, the absolute value of the significand as a 5163# libray thingy, the sign of the exponent, and the absolute value of the 5164# exponent as a library thingy. 5165 5166sub _bin_str_to_lib_parts { 5167 my $class = shift; 5168 my $str = shift; 5169 if (my @parts = $class -> _bin_str_to_str_parts($str)) { 5170 return $class -> _bin_parts_to_lib_parts(@parts, 1); # 1 bit pr. chr 5171 } 5172 return; 5173} 5174 5175# Decimal string is split into the sign of the signficant, the absolute value of 5176# the significand as library thingy, the sign of the exponent, and the absolute 5177# value of the exponent as a a library thingy. 5178 5179sub _dec_str_to_lib_parts { 5180 my $class = shift; 5181 my $str = shift; 5182 if (my @parts = $class -> _dec_str_to_str_parts($str)) { 5183 return $class -> _dec_parts_to_lib_parts(@parts); 5184 } 5185 return; 5186} 5187 5188# Hexdecimal string to a string using decimal floating point notation. 5189 5190sub hex_str_to_dec_flt_str { 5191 my $class = shift; 5192 my $str = shift; 5193 if (my @parts = $class -> _hex_str_to_lib_parts($str)) { 5194 return $class -> _lib_parts_to_flt_str(@parts); 5195 } 5196 return; 5197} 5198 5199# Octal string to a string using decimal floating point notation. 5200 5201sub oct_str_to_dec_flt_str { 5202 my $class = shift; 5203 my $str = shift; 5204 if (my @parts = $class -> _oct_str_to_lib_parts($str)) { 5205 return $class -> _lib_parts_to_flt_str(@parts); 5206 } 5207 return; 5208} 5209 5210# Binary string to a string decimal floating point notation. 5211 5212sub bin_str_to_dec_flt_str { 5213 my $class = shift; 5214 my $str = shift; 5215 if (my @parts = $class -> _bin_str_to_lib_parts($str)) { 5216 return $class -> _lib_parts_to_flt_str(@parts); 5217 } 5218 return; 5219} 5220 5221# Decimal string to a string using decimal floating point notation. 5222 5223sub dec_str_to_dec_flt_str { 5224 my $class = shift; 5225 my $str = shift; 5226 if (my @parts = $class -> _dec_str_to_lib_parts($str)) { 5227 return $class -> _lib_parts_to_flt_str(@parts); 5228 } 5229 return; 5230} 5231 5232# Hexdecimal string to decimal notation (no exponent). 5233 5234sub hex_str_to_dec_str { 5235 my $class = shift; 5236 my $str = shift; 5237 if (my @parts = $class -> _dec_str_to_lib_parts($str)) { 5238 return $class -> _lib_parts_to_dec_str(@parts); 5239 } 5240 return; 5241} 5242 5243# Octal string to decimal notation (no exponent). 5244 5245sub oct_str_to_dec_str { 5246 my $class = shift; 5247 my $str = shift; 5248 if (my @parts = $class -> _oct_str_to_lib_parts($str)) { 5249 return $class -> _lib_parts_to_dec_str(@parts); 5250 } 5251 return; 5252} 5253 5254# Binary string to decimal notation (no exponent). 5255 5256sub bin_str_to_dec_str { 5257 my $class = shift; 5258 my $str = shift; 5259 if (my @parts = $class -> _bin_str_to_lib_parts($str)) { 5260 return $class -> _lib_parts_to_dec_str(@parts); 5261 } 5262 return; 5263} 5264 5265# Decimal string to decimal notation (no exponent). 5266 5267sub dec_str_to_dec_str { 5268 my $class = shift; 5269 my $str = shift; 5270 if (my @parts = $class -> _dec_str_to_lib_parts($str)) { 5271 return $class -> _lib_parts_to_dec_str(@parts); 5272 } 5273 return; 5274} 5275 5276sub _lib_parts_to_flt_str { 5277 my $class = shift; 5278 my @parts = @_; 5279 return $parts[0] . $LIB -> _str($parts[1]) 5280 . 'e' . $parts[2] . $LIB -> _str($parts[3]); 5281} 5282 5283sub _lib_parts_to_dec_str { 5284 my $class = shift; 5285 my @parts = @_; 5286 5287 # The number is an integer iff the exponent is non-negative. 5288 5289 if ($parts[2] eq '+') { 5290 my $str = $parts[0] 5291 . $LIB -> _str($LIB -> _lsft($parts[1], $parts[3], 10)); 5292 return $str; 5293 } 5294 5295 # If it is not an integer, add a decimal point. 5296 5297 else { 5298 my $mant = $LIB -> _str($parts[1]); 5299 my $mant_len = CORE::length($mant); 5300 my $expo = $LIB -> _num($parts[3]); 5301 my $len_cmp = $mant_len <=> $expo; 5302 if ($len_cmp <= 0) { 5303 return $parts[0] . '0.' . '0' x ($expo - $mant_len) . $mant; 5304 } else { 5305 substr $mant, $mant_len - $expo, 0, '.'; 5306 return $parts[0] . $mant; 5307 } 5308 } 5309} 5310 5311############################################################################### 5312# this method returns 0 if the object can be modified, or 1 if not. 5313# We use a fast constant sub() here, to avoid costly calls. Subclasses 5314# may override it with special code (f.i. Math::BigInt::Constant does so) 5315 5316sub modify () { 0; } 5317 53181; 5319 5320__END__ 5321 5322=pod 5323 5324=head1 NAME 5325 5326Math::BigInt - arbitrary size integer math package 5327 5328=head1 SYNOPSIS 5329 5330 use Math::BigInt; 5331 5332 # or make it faster with huge numbers: install (optional) 5333 # Math::BigInt::GMP and always use (it falls back to 5334 # pure Perl if the GMP library is not installed): 5335 # (See also the L<MATH LIBRARY> section!) 5336 5337 # to warn if Math::BigInt::GMP cannot be found, use 5338 use Math::BigInt lib => 'GMP'; 5339 5340 # to suppress the warning if Math::BigInt::GMP cannot be found, use 5341 # use Math::BigInt try => 'GMP'; 5342 5343 # to die if Math::BigInt::GMP cannot be found, use 5344 # use Math::BigInt only => 'GMP'; 5345 5346 my $str = '1234567890'; 5347 my @values = (64, 74, 18); 5348 my $n = 1; my $sign = '-'; 5349 5350 # Configuration methods (may be used as class methods and instance methods) 5351 5352 Math::BigInt->accuracy(); # get class accuracy 5353 Math::BigInt->accuracy($n); # set class accuracy 5354 Math::BigInt->precision(); # get class precision 5355 Math::BigInt->precision($n); # set class precision 5356 Math::BigInt->round_mode(); # get class rounding mode 5357 Math::BigInt->round_mode($m); # set global round mode, must be one of 5358 # 'even', 'odd', '+inf', '-inf', 'zero', 5359 # 'trunc', or 'common' 5360 Math::BigInt->config(); # return hash with configuration 5361 5362 # Constructor methods (when the class methods below are used as instance 5363 # methods, the value is assigned the invocand) 5364 5365 $x = Math::BigInt->new($str); # defaults to 0 5366 $x = Math::BigInt->new('0x123'); # from hexadecimal 5367 $x = Math::BigInt->new('0b101'); # from binary 5368 $x = Math::BigInt->from_hex('cafe'); # from hexadecimal 5369 $x = Math::BigInt->from_oct('377'); # from octal 5370 $x = Math::BigInt->from_bin('1101'); # from binary 5371 $x = Math::BigInt->from_base('why', 36); # from any base 5372 $x = Math::BigInt->from_base_num([1, 0], 2); # from any base 5373 $x = Math::BigInt->bzero(); # create a +0 5374 $x = Math::BigInt->bone(); # create a +1 5375 $x = Math::BigInt->bone('-'); # create a -1 5376 $x = Math::BigInt->binf(); # create a +inf 5377 $x = Math::BigInt->binf('-'); # create a -inf 5378 $x = Math::BigInt->bnan(); # create a Not-A-Number 5379 $x = Math::BigInt->bpi(); # returns pi 5380 5381 $y = $x->copy(); # make a copy (unlike $y = $x) 5382 $y = $x->as_int(); # return as a Math::BigInt 5383 5384 # Boolean methods (these don't modify the invocand) 5385 5386 $x->is_zero(); # if $x is 0 5387 $x->is_one(); # if $x is +1 5388 $x->is_one("+"); # ditto 5389 $x->is_one("-"); # if $x is -1 5390 $x->is_inf(); # if $x is +inf or -inf 5391 $x->is_inf("+"); # if $x is +inf 5392 $x->is_inf("-"); # if $x is -inf 5393 $x->is_nan(); # if $x is NaN 5394 5395 $x->is_positive(); # if $x > 0 5396 $x->is_pos(); # ditto 5397 $x->is_negative(); # if $x < 0 5398 $x->is_neg(); # ditto 5399 5400 $x->is_odd(); # if $x is odd 5401 $x->is_even(); # if $x is even 5402 $x->is_int(); # if $x is an integer 5403 5404 # Comparison methods 5405 5406 $x->bcmp($y); # compare numbers (undef, < 0, == 0, > 0) 5407 $x->bacmp($y); # compare absolutely (undef, < 0, == 0, > 0) 5408 $x->beq($y); # true if and only if $x == $y 5409 $x->bne($y); # true if and only if $x != $y 5410 $x->blt($y); # true if and only if $x < $y 5411 $x->ble($y); # true if and only if $x <= $y 5412 $x->bgt($y); # true if and only if $x > $y 5413 $x->bge($y); # true if and only if $x >= $y 5414 5415 # Arithmetic methods 5416 5417 $x->bneg(); # negation 5418 $x->babs(); # absolute value 5419 $x->bsgn(); # sign function (-1, 0, 1, or NaN) 5420 $x->bnorm(); # normalize (no-op) 5421 $x->binc(); # increment $x by 1 5422 $x->bdec(); # decrement $x by 1 5423 $x->badd($y); # addition (add $y to $x) 5424 $x->bsub($y); # subtraction (subtract $y from $x) 5425 $x->bmul($y); # multiplication (multiply $x by $y) 5426 $x->bmuladd($y,$z); # $x = $x * $y + $z 5427 $x->bdiv($y); # division (floored), set $x to quotient 5428 # return (quo,rem) or quo if scalar 5429 $x->btdiv($y); # division (truncated), set $x to quotient 5430 # return (quo,rem) or quo if scalar 5431 $x->bmod($y); # modulus (x % y) 5432 $x->btmod($y); # modulus (truncated) 5433 $x->bmodinv($mod); # modular multiplicative inverse 5434 $x->bmodpow($y,$mod); # modular exponentiation (($x ** $y) % $mod) 5435 $x->bpow($y); # power of arguments (x ** y) 5436 $x->blog(); # logarithm of $x to base e (Euler's number) 5437 $x->blog($base); # logarithm of $x to base $base (e.g., base 2) 5438 $x->bexp(); # calculate e ** $x where e is Euler's number 5439 $x->bnok($y); # x over y (binomial coefficient n over k) 5440 $x->buparrow($n, $y); # Knuth's up-arrow notation 5441 $x->backermann($y); # the Ackermann function 5442 $x->bsin(); # sine 5443 $x->bcos(); # cosine 5444 $x->batan(); # inverse tangent 5445 $x->batan2($y); # two-argument inverse tangent 5446 $x->bsqrt(); # calculate square root 5447 $x->broot($y); # $y'th root of $x (e.g. $y == 3 => cubic root) 5448 $x->bfac(); # factorial of $x (1*2*3*4*..$x) 5449 $x->bdfac(); # double factorial of $x ($x*($x-2)*($x-4)*...) 5450 $x->btfac(); # triple factorial of $x ($x*($x-3)*($x-6)*...) 5451 $x->bmfac($k); # $k'th multi-factorial of $x ($x*($x-$k)*...) 5452 5453 $x->blsft($n); # left shift $n places in base 2 5454 $x->blsft($n,$b); # left shift $n places in base $b 5455 # returns (quo,rem) or quo (scalar context) 5456 $x->brsft($n); # right shift $n places in base 2 5457 $x->brsft($n,$b); # right shift $n places in base $b 5458 # returns (quo,rem) or quo (scalar context) 5459 5460 # Bitwise methods 5461 5462 $x->band($y); # bitwise and 5463 $x->bior($y); # bitwise inclusive or 5464 $x->bxor($y); # bitwise exclusive or 5465 $x->bnot(); # bitwise not (two's complement) 5466 5467 # Rounding methods 5468 $x->round($A,$P,$mode); # round to accuracy or precision using 5469 # rounding mode $mode 5470 $x->bround($n); # accuracy: preserve $n digits 5471 $x->bfround($n); # $n > 0: round to $nth digit left of dec. point 5472 # $n < 0: round to $nth digit right of dec. point 5473 $x->bfloor(); # round towards minus infinity 5474 $x->bceil(); # round towards plus infinity 5475 $x->bint(); # round towards zero 5476 5477 # Other mathematical methods 5478 5479 $x->bgcd($y); # greatest common divisor 5480 $x->blcm($y); # least common multiple 5481 5482 # Object property methods (do not modify the invocand) 5483 5484 $x->sign(); # the sign, either +, - or NaN 5485 $x->digit($n); # the nth digit, counting from the right 5486 $x->digit(-$n); # the nth digit, counting from the left 5487 $x->length(); # return number of digits in number 5488 ($xl,$f) = $x->length(); # length of number and length of fraction 5489 # part, latter is always 0 digits long 5490 # for Math::BigInt objects 5491 $x->mantissa(); # return (signed) mantissa as a Math::BigInt 5492 $x->exponent(); # return exponent as a Math::BigInt 5493 $x->parts(); # return (mantissa,exponent) as a Math::BigInt 5494 $x->sparts(); # mantissa and exponent (as integers) 5495 $x->nparts(); # mantissa and exponent (normalised) 5496 $x->eparts(); # mantissa and exponent (engineering notation) 5497 $x->dparts(); # integer and fraction part 5498 $x->fparts(); # numerator and denominator 5499 $x->numerator(); # numerator 5500 $x->denominator(); # denominator 5501 5502 # Conversion methods (do not modify the invocand) 5503 5504 $x->bstr(); # decimal notation, possibly zero padded 5505 $x->bsstr(); # string in scientific notation with integers 5506 $x->bnstr(); # string in normalized notation 5507 $x->bestr(); # string in engineering notation 5508 $x->bdstr(); # string in decimal notation 5509 5510 $x->to_hex(); # as signed hexadecimal string 5511 $x->to_bin(); # as signed binary string 5512 $x->to_oct(); # as signed octal string 5513 $x->to_bytes(); # as byte string 5514 $x->to_base($b); # as string in any base 5515 $x->to_base_num($b); # as array of integers in any base 5516 5517 $x->as_hex(); # as signed hexadecimal string with prefixed 0x 5518 $x->as_bin(); # as signed binary string with prefixed 0b 5519 $x->as_oct(); # as signed octal string with prefixed 0 5520 5521 # Other conversion methods 5522 5523 $x->numify(); # return as scalar (might overflow or underflow) 5524 5525=head1 DESCRIPTION 5526 5527Math::BigInt provides support for arbitrary precision integers. Overloading is 5528also provided for Perl operators. 5529 5530=head2 Input 5531 5532Input values to these routines may be any scalar number or string that looks 5533like a number and represents an integer. Anything that is accepted by Perl as a 5534literal numeric constant should be accepted by this module, except that finite 5535non-integers return NaN. 5536 5537=over 5538 5539=item * 5540 5541Leading and trailing whitespace is ignored. 5542 5543=item * 5544 5545Leading zeros are ignored, except for floating point numbers with a binary 5546exponent, in which case the number is interpreted as an octal floating point 5547number. For example, "01.4p+0" gives 1.5, "00.4p+0" gives 0.5, but "0.4p+0" 5548gives a NaN. And while "0377" gives 255, "0377p0" gives 255. 5549 5550=item * 5551 5552If the string has a "0x" or "0X" prefix, it is interpreted as a hexadecimal 5553number. 5554 5555=item * 5556 5557If the string has a "0o" or "0O" prefix, it is interpreted as an octal number. A 5558floating point literal with a "0" prefix is also interpreted as an octal number. 5559 5560=item * 5561 5562If the string has a "0b" or "0B" prefix, it is interpreted as a binary number. 5563 5564=item * 5565 5566Underline characters are allowed in the same way as they are allowed in literal 5567numerical constants. 5568 5569=item * 5570 5571If the string can not be interpreted, or does not represent a finite integer, 5572NaN is returned. 5573 5574=item * 5575 5576For hexadecimal, octal, and binary floating point numbers, the exponent must be 5577separated from the significand (mantissa) by the letter "p" or "P", not "e" or 5578"E" as with decimal numbers. 5579 5580=back 5581 5582Some examples of valid string input 5583 5584 Input string Resulting value 5585 5586 123 123 5587 1.23e2 123 5588 12300e-2 123 5589 5590 67_538_754 67538754 5591 -4_5_6.7_8_9e+0_1_0 -4567890000000 5592 5593 0x13a 314 5594 0x13ap0 314 5595 0x1.3ap+8 314 5596 0x0.00013ap+24 314 5597 0x13a000p-12 314 5598 5599 0o472 314 5600 0o1.164p+8 314 5601 0o0.0001164p+20 314 5602 0o1164000p-10 314 5603 5604 0472 472 Note! 5605 01.164p+8 314 5606 00.0001164p+20 314 5607 01164000p-10 314 5608 5609 0b100111010 314 5610 0b1.0011101p+8 314 5611 0b0.00010011101p+12 314 5612 0b100111010000p-3 314 5613 5614Input given as scalar numbers might lose precision. Quote your input to ensure 5615that no digits are lost: 5616 5617 $x = Math::BigInt->new( 56789012345678901234 ); # bad 5618 $x = Math::BigInt->new('56789012345678901234'); # good 5619 5620Currently, C<Math::BigInt->new()> (no input argument) and 5621C<Math::BigInt->new("")> return 0. This might change in the future, so always 5622use the following explicit forms to get a zero: 5623 5624 $zero = Math::BigInt->bzero(); 5625 5626=head2 Output 5627 5628Output values are usually Math::BigInt objects. 5629 5630Boolean operators C<is_zero()>, C<is_one()>, C<is_inf()>, etc. return true or 5631false. 5632 5633Comparison operators C<bcmp()> and C<bacmp()>) return -1, 0, 1, or 5634undef. 5635 5636=head1 METHODS 5637 5638=head2 Configuration methods 5639 5640Each of the methods below (except config(), accuracy() and precision()) accepts 5641three additional parameters. These arguments C<$A>, C<$P> and C<$R> are 5642C<accuracy>, C<precision> and C<round_mode>. Please see the section about 5643L</ACCURACY and PRECISION> for more information. 5644 5645Setting a class variable effects all object instance that are created 5646afterwards. 5647 5648=over 5649 5650=item accuracy() 5651 5652 Math::BigInt->accuracy(5); # set class accuracy 5653 $x->accuracy(5); # set instance accuracy 5654 5655 $A = Math::BigInt->accuracy(); # get class accuracy 5656 $A = $x->accuracy(); # get instance accuracy 5657 5658Set or get the accuracy, i.e., the number of significant digits. The accuracy 5659must be an integer. If the accuracy is set to C<undef>, no rounding is done. 5660 5661Alternatively, one can round the results explicitly using one of L</round()>, 5662L</bround()> or L</bfround()> or by passing the desired accuracy to the method 5663as an additional parameter: 5664 5665 my $x = Math::BigInt->new(30000); 5666 my $y = Math::BigInt->new(7); 5667 print scalar $x->copy()->bdiv($y, 2); # prints 4300 5668 print scalar $x->copy()->bdiv($y)->bround(2); # prints 4300 5669 5670Please see the section about L</ACCURACY and PRECISION> for further details. 5671 5672 $y = Math::BigInt->new(1234567); # $y is not rounded 5673 Math::BigInt->accuracy(4); # set class accuracy to 4 5674 $x = Math::BigInt->new(1234567); # $x is rounded automatically 5675 print "$x $y"; # prints "1235000 1234567" 5676 5677 print $x->accuracy(); # prints "4" 5678 print $y->accuracy(); # also prints "4", since 5679 # class accuracy is 4 5680 5681 Math::BigInt->accuracy(5); # set class accuracy to 5 5682 print $x->accuracy(); # prints "4", since instance 5683 # accuracy is 4 5684 print $y->accuracy(); # prints "5", since no instance 5685 # accuracy, and class accuracy is 5 5686 5687Note: Each class has it's own globals separated from Math::BigInt, but it is 5688possible to subclass Math::BigInt and make the globals of the subclass aliases 5689to the ones from Math::BigInt. 5690 5691=item precision() 5692 5693 Math::BigInt->precision(-2); # set class precision 5694 $x->precision(-2); # set instance precision 5695 5696 $P = Math::BigInt->precision(); # get class precision 5697 $P = $x->precision(); # get instance precision 5698 5699Set or get the precision, i.e., the place to round relative to the decimal 5700point. The precision must be a integer. Setting the precision to $P means that 5701each number is rounded up or down, depending on the rounding mode, to the 5702nearest multiple of 10**$P. If the precision is set to C<undef>, no rounding is 5703done. 5704 5705You might want to use L</accuracy()> instead. With L</accuracy()> you set the 5706number of digits each result should have, with L</precision()> you set the 5707place where to round. 5708 5709Please see the section about L</ACCURACY and PRECISION> for further details. 5710 5711 $y = Math::BigInt->new(1234567); # $y is not rounded 5712 Math::BigInt->precision(4); # set class precision to 4 5713 $x = Math::BigInt->new(1234567); # $x is rounded automatically 5714 print $x; # prints "1230000" 5715 5716Note: Each class has its own globals separated from Math::BigInt, but it is 5717possible to subclass Math::BigInt and make the globals of the subclass aliases 5718to the ones from Math::BigInt. 5719 5720=item div_scale() 5721 5722Set/get the fallback accuracy. This is the accuracy used when neither accuracy 5723nor precision is set explicitly. It is used when a computation might otherwise 5724attempt to return an infinite number of digits. 5725 5726=item round_mode() 5727 5728Set/get the rounding mode. 5729 5730=item upgrade() 5731 5732Set/get the class for upgrading. When a computation might result in a 5733non-integer, the operands are upgraded to this class. This is used for instance 5734by L<bignum>. The default is C<undef>, i.e., no upgrading. 5735 5736 # with no upgrading 5737 $x = Math::BigInt->new(12); 5738 $y = Math::BigInt->new(5); 5739 print $x / $y, "\n"; # 2 as a Math::BigInt 5740 5741 # with upgrading to Math::BigFloat 5742 Math::BigInt -> upgrade("Math::BigFloat"); 5743 print $x / $y, "\n"; # 2.4 as a Math::BigFloat 5744 5745 # with upgrading to Math::BigRat (after loading Math::BigRat) 5746 Math::BigInt -> upgrade("Math::BigRat"); 5747 print $x / $y, "\n"; # 12/5 as a Math::BigRat 5748 5749=item downgrade() 5750 5751Set/get the class for downgrading. The default is C<undef>, i.e., no 5752downgrading. Downgrading is not done by Math::BigInt. 5753 5754=item modify() 5755 5756 $x->modify('bpowd'); 5757 5758This method returns 0 if the object can be modified with the given operation, 5759or 1 if not. 5760 5761This is used for instance by L<Math::BigInt::Constant>. 5762 5763=item config() 5764 5765 Math::BigInt->config("trap_nan" => 1); # set 5766 $accu = Math::BigInt->config("accuracy"); # get 5767 5768Set or get class variables. Read-only parameters are marked as RO. Read-write 5769parameters are marked as RW. The following parameters are supported. 5770 5771 Parameter RO/RW Description 5772 Example 5773 ============================================================ 5774 lib RO Name of the math backend library 5775 Math::BigInt::Calc 5776 lib_version RO Version of the math backend library 5777 0.30 5778 class RO The class of config you just called 5779 Math::BigRat 5780 version RO version number of the class you used 5781 0.10 5782 upgrade RW To which class numbers are upgraded 5783 undef 5784 downgrade RW To which class numbers are downgraded 5785 undef 5786 precision RW Global precision 5787 undef 5788 accuracy RW Global accuracy 5789 undef 5790 round_mode RW Global round mode 5791 even 5792 div_scale RW Fallback accuracy for division etc. 5793 40 5794 trap_nan RW Trap NaNs 5795 undef 5796 trap_inf RW Trap +inf/-inf 5797 undef 5798 5799=back 5800 5801=head2 Constructor methods 5802 5803=over 5804 5805=item new() 5806 5807 $x = Math::BigInt->new($str,$A,$P,$R); 5808 5809Creates a new Math::BigInt object from a scalar or another Math::BigInt object. 5810The input is accepted as decimal, hexadecimal (with leading '0x'), octal (with 5811leading ('0o') or binary (with leading '0b'). 5812 5813See L</Input> for more info on accepted input formats. 5814 5815=item from_dec() 5816 5817 $x = Math::BigInt->from_dec("314159"); # input is decimal 5818 5819Interpret input as a decimal. It is equivalent to new(), but does not accept 5820anything but strings representing finite, decimal numbers. 5821 5822=item from_hex() 5823 5824 $x = Math::BigInt->from_hex("0xcafe"); # input is hexadecimal 5825 5826Interpret input as a hexadecimal string. A "0x" or "x" prefix is optional. A 5827single underscore character may be placed right after the prefix, if present, 5828or between any two digits. If the input is invalid, a NaN is returned. 5829 5830=item from_oct() 5831 5832 $x = Math::BigInt->from_oct("0775"); # input is octal 5833 5834Interpret the input as an octal string and return the corresponding value. A 5835"0" (zero) prefix is optional. A single underscore character may be placed 5836right after the prefix, if present, or between any two digits. If the input is 5837invalid, a NaN is returned. 5838 5839=item from_bin() 5840 5841 $x = Math::BigInt->from_bin("0b10011"); # input is binary 5842 5843Interpret the input as a binary string. A "0b" or "b" prefix is optional. A 5844single underscore character may be placed right after the prefix, if present, 5845or between any two digits. If the input is invalid, a NaN is returned. 5846 5847=item from_bytes() 5848 5849 $x = Math::BigInt->from_bytes("\xf3\x6b"); # $x = 62315 5850 5851Interpret the input as a byte string, assuming big endian byte order. The 5852output is always a non-negative, finite integer. 5853 5854In some special cases, from_bytes() matches the conversion done by unpack(): 5855 5856 $b = "\x4e"; # one char byte string 5857 $x = Math::BigInt->from_bytes($b); # = 78 5858 $y = unpack "C", $b; # ditto, but scalar 5859 5860 $b = "\xf3\x6b"; # two char byte string 5861 $x = Math::BigInt->from_bytes($b); # = 62315 5862 $y = unpack "S>", $b; # ditto, but scalar 5863 5864 $b = "\x2d\xe0\x49\xad"; # four char byte string 5865 $x = Math::BigInt->from_bytes($b); # = 769673645 5866 $y = unpack "L>", $b; # ditto, but scalar 5867 5868 $b = "\x2d\xe0\x49\xad\x2d\xe0\x49\xad"; # eight char byte string 5869 $x = Math::BigInt->from_bytes($b); # = 3305723134637787565 5870 $y = unpack "Q>", $b; # ditto, but scalar 5871 5872=item from_base() 5873 5874Given a string, a base, and an optional collation sequence, interpret the 5875string as a number in the given base. The collation sequence describes the 5876value of each character in the string. 5877 5878If a collation sequence is not given, a default collation sequence is used. If 5879the base is less than or equal to 36, the collation sequence is the string 5880consisting of the 36 characters "0" to "9" and "A" to "Z". In this case, the 5881letter case in the input is ignored. If the base is greater than 36, and 5882smaller than or equal to 62, the collation sequence is the string consisting of 5883the 62 characters "0" to "9", "A" to "Z", and "a" to "z". A base larger than 62 5884requires the collation sequence to be specified explicitly. 5885 5886These examples show standard binary, octal, and hexadecimal conversion. All 5887cases return 250. 5888 5889 $x = Math::BigInt->from_base("11111010", 2); 5890 $x = Math::BigInt->from_base("372", 8); 5891 $x = Math::BigInt->from_base("fa", 16); 5892 5893When the base is less than or equal to 36, and no collation sequence is given, 5894the letter case is ignored, so both of these also return 250: 5895 5896 $x = Math::BigInt->from_base("6Y", 16); 5897 $x = Math::BigInt->from_base("6y", 16); 5898 5899When the base greater than 36, and no collation sequence is given, the default 5900collation sequence contains both uppercase and lowercase letters, so 5901the letter case in the input is not ignored: 5902 5903 $x = Math::BigInt->from_base("6S", 37); # $x is 250 5904 $x = Math::BigInt->from_base("6s", 37); # $x is 276 5905 $x = Math::BigInt->from_base("121", 3); # $x is 16 5906 $x = Math::BigInt->from_base("XYZ", 36); # $x is 44027 5907 $x = Math::BigInt->from_base("Why", 42); # $x is 58314 5908 5909The collation sequence can be any set of unique characters. These two cases 5910are equivalent 5911 5912 $x = Math::BigInt->from_base("100", 2, "01"); # $x is 4 5913 $x = Math::BigInt->from_base("|--", 2, "-|"); # $x is 4 5914 5915=item from_base_num() 5916 5917Returns a new Math::BigInt object given an array of values and a base. This 5918method is equivalent to C<from_base()>, but works on numbers in an array rather 5919than characters in a string. Unlike C<from_base()>, all input values may be 5920arbitrarily large. 5921 5922 $x = Math::BigInt->from_base_num([1, 1, 0, 1], 2) # $x is 13 5923 $x = Math::BigInt->from_base_num([3, 125, 39], 128) # $x is 65191 5924 5925=item bzero() 5926 5927 $x = Math::BigInt->bzero(); 5928 $x->bzero(); 5929 5930Returns a new Math::BigInt object representing zero. If used as an instance 5931method, assigns the value to the invocand. 5932 5933=item bone() 5934 5935 $x = Math::BigInt->bone(); # +1 5936 $x = Math::BigInt->bone("+"); # +1 5937 $x = Math::BigInt->bone("-"); # -1 5938 $x->bone(); # +1 5939 $x->bone("+"); # +1 5940 $x->bone('-'); # -1 5941 5942Creates a new Math::BigInt object representing one. The optional argument is 5943either '-' or '+', indicating whether you want plus one or minus one. If used 5944as an instance method, assigns the value to the invocand. 5945 5946=item binf() 5947 5948 $x = Math::BigInt->binf($sign); 5949 5950Creates a new Math::BigInt object representing infinity. The optional argument 5951is either '-' or '+', indicating whether you want infinity or minus infinity. 5952If used as an instance method, assigns the value to the invocand. 5953 5954 $x->binf(); 5955 $x->binf('-'); 5956 5957=item bnan() 5958 5959 $x = Math::BigInt->bnan(); 5960 5961Creates a new Math::BigInt object representing NaN (Not A Number). If used as 5962an instance method, assigns the value to the invocand. 5963 5964 $x->bnan(); 5965 5966=item bpi() 5967 5968 $x = Math::BigInt->bpi(100); # 3 5969 $x->bpi(100); # 3 5970 5971Creates a new Math::BigInt object representing PI. If used as an instance 5972method, assigns the value to the invocand. With Math::BigInt this always 5973returns 3. 5974 5975If upgrading is in effect, returns PI, rounded to N digits with the current 5976rounding mode: 5977 5978 use Math::BigFloat; 5979 use Math::BigInt upgrade => "Math::BigFloat"; 5980 print Math::BigInt->bpi(3), "\n"; # 3.14 5981 print Math::BigInt->bpi(100), "\n"; # 3.1415.... 5982 5983=item copy() 5984 5985 $x->copy(); # make a true copy of $x (unlike $y = $x) 5986 5987=item as_int() 5988 5989=item as_number() 5990 5991These methods are called when Math::BigInt encounters an object it doesn't know 5992how to handle. For instance, assume $x is a Math::BigInt, or subclass thereof, 5993and $y is defined, but not a Math::BigInt, or subclass thereof. If you do 5994 5995 $x -> badd($y); 5996 5997$y needs to be converted into an object that $x can deal with. This is done by 5998first checking if $y is something that $x might be upgraded to. If that is the 5999case, no further attempts are made. The next is to see if $y supports the 6000method C<as_int()>. If it does, C<as_int()> is called, but if it doesn't, the 6001next thing is to see if $y supports the method C<as_number()>. If it does, 6002C<as_number()> is called. The method C<as_int()> (and C<as_number()>) is 6003expected to return either an object that has the same class as $x, a subclass 6004thereof, or a string that C<ref($x)-E<gt>new()> can parse to create an object. 6005 6006C<as_number()> is an alias to C<as_int()>. C<as_number> was introduced in 6007v1.22, while C<as_int()> was introduced in v1.68. 6008 6009In Math::BigInt, C<as_int()> has the same effect as C<copy()>. 6010 6011=back 6012 6013=head2 Boolean methods 6014 6015None of these methods modify the invocand object. 6016 6017=over 6018 6019=item is_zero() 6020 6021 $x->is_zero(); # true if $x is 0 6022 6023Returns true if the invocand is zero and false otherwise. 6024 6025=item is_one( [ SIGN ]) 6026 6027 $x->is_one(); # true if $x is +1 6028 $x->is_one("+"); # ditto 6029 $x->is_one("-"); # true if $x is -1 6030 6031Returns true if the invocand is one and false otherwise. 6032 6033=item is_finite() 6034 6035 $x->is_finite(); # true if $x is not +inf, -inf or NaN 6036 6037Returns true if the invocand is a finite number, i.e., it is neither +inf, 6038-inf, nor NaN. 6039 6040=item is_inf( [ SIGN ] ) 6041 6042 $x->is_inf(); # true if $x is +inf 6043 $x->is_inf("+"); # ditto 6044 $x->is_inf("-"); # true if $x is -inf 6045 6046Returns true if the invocand is infinite and false otherwise. 6047 6048=item is_nan() 6049 6050 $x->is_nan(); # true if $x is NaN 6051 6052=item is_positive() 6053 6054=item is_pos() 6055 6056 $x->is_positive(); # true if > 0 6057 $x->is_pos(); # ditto 6058 6059Returns true if the invocand is positive and false otherwise. A C<NaN> is 6060neither positive nor negative. 6061 6062=item is_negative() 6063 6064=item is_neg() 6065 6066 $x->is_negative(); # true if < 0 6067 $x->is_neg(); # ditto 6068 6069Returns true if the invocand is negative and false otherwise. A C<NaN> is 6070neither positive nor negative. 6071 6072=item is_non_positive() 6073 6074 $x->is_non_positive(); # true if <= 0 6075 6076Returns true if the invocand is negative or zero. 6077 6078=item is_non_negative() 6079 6080 $x->is_non_negative(); # true if >= 0 6081 6082Returns true if the invocand is positive or zero. 6083 6084=item is_odd() 6085 6086 $x->is_odd(); # true if odd, false for even 6087 6088Returns true if the invocand is odd and false otherwise. C<NaN>, C<+inf>, and 6089C<-inf> are neither odd nor even. 6090 6091=item is_even() 6092 6093 $x->is_even(); # true if $x is even 6094 6095Returns true if the invocand is even and false otherwise. C<NaN>, C<+inf>, 6096C<-inf> are not integers and are neither odd nor even. 6097 6098=item is_int() 6099 6100 $x->is_int(); # true if $x is an integer 6101 6102Returns true if the invocand is an integer and false otherwise. C<NaN>, 6103C<+inf>, C<-inf> are not integers. 6104 6105=back 6106 6107=head2 Comparison methods 6108 6109None of these methods modify the invocand object. Note that a C<NaN> is neither 6110less than, greater than, or equal to anything else, even a C<NaN>. 6111 6112=over 6113 6114=item bcmp() 6115 6116 $x->bcmp($y); 6117 6118Returns -1, 0, 1 depending on whether $x is less than, equal to, or grater than 6119$y. Returns undef if any operand is a NaN. 6120 6121=item bacmp() 6122 6123 $x->bacmp($y); 6124 6125Returns -1, 0, 1 depending on whether the absolute value of $x is less than, 6126equal to, or grater than the absolute value of $y. Returns undef if any operand 6127is a NaN. 6128 6129=item beq() 6130 6131 $x -> beq($y); 6132 6133Returns true if and only if $x is equal to $y, and false otherwise. 6134 6135=item bne() 6136 6137 $x -> bne($y); 6138 6139Returns true if and only if $x is not equal to $y, and false otherwise. 6140 6141=item blt() 6142 6143 $x -> blt($y); 6144 6145Returns true if and only if $x is equal to $y, and false otherwise. 6146 6147=item ble() 6148 6149 $x -> ble($y); 6150 6151Returns true if and only if $x is less than or equal to $y, and false 6152otherwise. 6153 6154=item bgt() 6155 6156 $x -> bgt($y); 6157 6158Returns true if and only if $x is greater than $y, and false otherwise. 6159 6160=item bge() 6161 6162 $x -> bge($y); 6163 6164Returns true if and only if $x is greater than or equal to $y, and false 6165otherwise. 6166 6167=back 6168 6169=head2 Arithmetic methods 6170 6171These methods modify the invocand object and returns it. 6172 6173=over 6174 6175=item bneg() 6176 6177 $x->bneg(); 6178 6179Negate the number, e.g. change the sign between '+' and '-', or between '+inf' 6180and '-inf', respectively. Does nothing for NaN or zero. 6181 6182=item babs() 6183 6184 $x->babs(); 6185 6186Set the number to its absolute value, e.g. change the sign from '-' to '+' 6187and from '-inf' to '+inf', respectively. Does nothing for NaN or positive 6188numbers. 6189 6190=item bsgn() 6191 6192 $x->bsgn(); 6193 6194Signum function. Set the number to -1, 0, or 1, depending on whether the 6195number is negative, zero, or positive, respectively. Does not modify NaNs. 6196 6197=item bnorm() 6198 6199 $x->bnorm(); # normalize (no-op) 6200 6201Normalize the number. This is a no-op and is provided only for backwards 6202compatibility. 6203 6204=item binc() 6205 6206 $x->binc(); # increment x by 1 6207 6208=item bdec() 6209 6210 $x->bdec(); # decrement x by 1 6211 6212=item badd() 6213 6214 $x->badd($y); # addition (add $y to $x) 6215 6216=item bsub() 6217 6218 $x->bsub($y); # subtraction (subtract $y from $x) 6219 6220=item bmul() 6221 6222 $x->bmul($y); # multiplication (multiply $x by $y) 6223 6224=item bmuladd() 6225 6226 $x->bmuladd($y,$z); 6227 6228Multiply $x by $y, and then add $z to the result, 6229 6230This method was added in v1.87 of Math::BigInt (June 2007). 6231 6232=item bdiv() 6233 6234 $x->bdiv($y); # divide, set $x to quotient 6235 6236Divides $x by $y by doing floored division (F-division), where the quotient is 6237the floored (rounded towards negative infinity) quotient of the two operands. 6238In list context, returns the quotient and the remainder. The remainder is 6239either zero or has the same sign as the second operand. In scalar context, only 6240the quotient is returned. 6241 6242The quotient is always the greatest integer less than or equal to the 6243real-valued quotient of the two operands, and the remainder (when it is 6244non-zero) always has the same sign as the second operand; so, for example, 6245 6246 1 / 4 => ( 0, 1) 6247 1 / -4 => (-1, -3) 6248 -3 / 4 => (-1, 1) 6249 -3 / -4 => ( 0, -3) 6250 -11 / 2 => (-5, 1) 6251 11 / -2 => (-5, -1) 6252 6253The behavior of the overloaded operator % agrees with the behavior of Perl's 6254built-in % operator (as documented in the perlop manpage), and the equation 6255 6256 $x == ($x / $y) * $y + ($x % $y) 6257 6258holds true for any finite $x and finite, non-zero $y. 6259 6260Perl's "use integer" might change the behaviour of % and / for scalars. This is 6261because under 'use integer' Perl does what the underlying C library thinks is 6262right, and this varies. However, "use integer" does not change the way things 6263are done with Math::BigInt objects. 6264 6265=item btdiv() 6266 6267 $x->btdiv($y); # divide, set $x to quotient 6268 6269Divides $x by $y by doing truncated division (T-division), where quotient is 6270the truncated (rouneded towards zero) quotient of the two operands. In list 6271context, returns the quotient and the remainder. The remainder is either zero 6272or has the same sign as the first operand. In scalar context, only the quotient 6273is returned. 6274 6275=item bmod() 6276 6277 $x->bmod($y); # modulus (x % y) 6278 6279Returns $x modulo $y, i.e., the remainder after floored division (F-division). 6280This method is like Perl's % operator. See L</bdiv()>. 6281 6282=item btmod() 6283 6284 $x->btmod($y); # modulus 6285 6286Returns the remainer after truncated division (T-division). See L</btdiv()>. 6287 6288=item bmodinv() 6289 6290 $x->bmodinv($mod); # modular multiplicative inverse 6291 6292Returns the multiplicative inverse of C<$x> modulo C<$mod>. If 6293 6294 $y = $x -> copy() -> bmodinv($mod) 6295 6296then C<$y> is the number closest to zero, and with the same sign as C<$mod>, 6297satisfying 6298 6299 ($x * $y) % $mod = 1 % $mod 6300 6301If C<$x> and C<$y> are non-zero, they must be relative primes, i.e., 6302C<bgcd($y, $mod)==1>. 'C<NaN>' is returned when no modular multiplicative 6303inverse exists. 6304 6305=item bmodpow() 6306 6307 $num->bmodpow($exp,$mod); # modular exponentiation 6308 # ($num**$exp % $mod) 6309 6310Returns the value of C<$num> taken to the power C<$exp> in the modulus 6311C<$mod> using binary exponentiation. C<bmodpow> is far superior to 6312writing 6313 6314 $num ** $exp % $mod 6315 6316because it is much faster - it reduces internal variables into 6317the modulus whenever possible, so it operates on smaller numbers. 6318 6319C<bmodpow> also supports negative exponents. 6320 6321 bmodpow($num, -1, $mod) 6322 6323is exactly equivalent to 6324 6325 bmodinv($num, $mod) 6326 6327=item bpow() 6328 6329 $x->bpow($y); # power of arguments (x ** y) 6330 6331C<bpow()> (and the rounding functions) now modifies the first argument and 6332returns it, unlike the old code which left it alone and only returned the 6333result. This is to be consistent with C<badd()> etc. The first three modifies 6334$x, the last one won't: 6335 6336 print bpow($x,$i),"\n"; # modify $x 6337 print $x->bpow($i),"\n"; # ditto 6338 print $x **= $i,"\n"; # the same 6339 print $x ** $i,"\n"; # leave $x alone 6340 6341The form C<$x **= $y> is faster than C<$x = $x ** $y;>, though. 6342 6343=item blog() 6344 6345 $x->blog($base, $accuracy); # logarithm of x to the base $base 6346 6347If C<$base> is not defined, Euler's number (e) is used: 6348 6349 print $x->blog(undef, 100); # log(x) to 100 digits 6350 6351=item bexp() 6352 6353 $x->bexp($accuracy); # calculate e ** X 6354 6355Calculates the expression C<e ** $x> where C<e> is Euler's number. 6356 6357This method was added in v1.82 of Math::BigInt (April 2007). 6358 6359See also L</blog()>. 6360 6361=item bnok() 6362 6363 $x->bnok($y); # x over y (binomial coefficient n over k) 6364 6365Calculates the binomial coefficient n over k, also called the "choose" 6366function, which is 6367 6368 ( n ) n! 6369 | | = -------- 6370 ( k ) k!(n-k)! 6371 6372when n and k are non-negative. This method implements the full Kronenburg 6373extension (Kronenburg, M.J. "The Binomial Coefficient for Negative Arguments." 637418 May 2011. http://arxiv.org/abs/1105.3689/) illustrated by the following 6375pseudo-code: 6376 6377 if n >= 0 and k >= 0: 6378 return binomial(n, k) 6379 if k >= 0: 6380 return (-1)^k*binomial(-n+k-1, k) 6381 if k <= n: 6382 return (-1)^(n-k)*binomial(-k-1, n-k) 6383 else 6384 return 0 6385 6386The behaviour is identical to the behaviour of the Maple and Mathematica 6387function for negative integers n, k. 6388 6389=item buparrow() 6390 6391=item uparrow() 6392 6393 $a -> buparrow($n, $b); # modifies $a 6394 $x = $a -> uparrow($n, $b); # does not modify $a 6395 6396This method implements Knuth's up-arrow notation, where $n is a non-negative 6397integer representing the number of up-arrows. $n = 0 gives multiplication, $n = 63981 gives exponentiation, $n = 2 gives tetration, $n = 3 gives hexation etc. The 6399following illustrates the relation between the first values of $n. 6400 6401See L<https://en.wikipedia.org/wiki/Knuth%27s_up-arrow_notation>. 6402 6403=item backermann() 6404 6405=item ackermann() 6406 6407 $m -> backermann($n); # modifies $a 6408 $x = $m -> ackermann($n); # does not modify $a 6409 6410This method implements the Ackermann function: 6411 6412 / n + 1 if m = 0 6413 A(m, n) = | A(m-1, 1) if m > 0 and n = 0 6414 \ A(m-1, A(m, n-1)) if m > 0 and n > 0 6415 6416Its value grows rapidly, even for small inputs. For example, A(4, 2) is an 6417integer of 19729 decimal digits. 6418 6419See https://en.wikipedia.org/wiki/Ackermann_function 6420 6421=item bsin() 6422 6423 my $x = Math::BigInt->new(1); 6424 print $x->bsin(100), "\n"; 6425 6426Calculate the sine of $x, modifying $x in place. 6427 6428In Math::BigInt, unless upgrading is in effect, the result is truncated to an 6429integer. 6430 6431This method was added in v1.87 of Math::BigInt (June 2007). 6432 6433=item bcos() 6434 6435 my $x = Math::BigInt->new(1); 6436 print $x->bcos(100), "\n"; 6437 6438Calculate the cosine of $x, modifying $x in place. 6439 6440In Math::BigInt, unless upgrading is in effect, the result is truncated to an 6441integer. 6442 6443This method was added in v1.87 of Math::BigInt (June 2007). 6444 6445=item batan() 6446 6447 my $x = Math::BigFloat->new(0.5); 6448 print $x->batan(100), "\n"; 6449 6450Calculate the arcus tangens of $x, modifying $x in place. 6451 6452In Math::BigInt, unless upgrading is in effect, the result is truncated to an 6453integer. 6454 6455This method was added in v1.87 of Math::BigInt (June 2007). 6456 6457=item batan2() 6458 6459 my $x = Math::BigInt->new(1); 6460 my $y = Math::BigInt->new(1); 6461 print $y->batan2($x), "\n"; 6462 6463Calculate the arcus tangens of C<$y> divided by C<$x>, modifying $y in place. 6464 6465In Math::BigInt, unless upgrading is in effect, the result is truncated to an 6466integer. 6467 6468This method was added in v1.87 of Math::BigInt (June 2007). 6469 6470=item bsqrt() 6471 6472 $x->bsqrt(); # calculate square root 6473 6474C<bsqrt()> returns the square root truncated to an integer. 6475 6476If you want a better approximation of the square root, then use: 6477 6478 $x = Math::BigFloat->new(12); 6479 Math::BigFloat->precision(0); 6480 Math::BigFloat->round_mode('even'); 6481 print $x->copy->bsqrt(),"\n"; # 4 6482 6483 Math::BigFloat->precision(2); 6484 print $x->bsqrt(),"\n"; # 3.46 6485 print $x->bsqrt(3),"\n"; # 3.464 6486 6487=item broot() 6488 6489 $x->broot($N); 6490 6491Calculates the N'th root of C<$x>. 6492 6493=item bfac() 6494 6495 $x->bfac(); # factorial of $x 6496 6497Returns the factorial of C<$x>, i.e., $x*($x-1)*($x-2)*...*2*1, the product of 6498all positive integers up to and including C<$x>. C<$x> must be > -1. The 6499factorial of N is commonly written as N!, or N!1, when using the multifactorial 6500notation. 6501 6502=item bdfac() 6503 6504 $x->bdfac(); # double factorial of $x 6505 6506Returns the double factorial of C<$x>, i.e., $x*($x-2)*($x-4)*... C<$x> must be 6507> -2. The double factorial of N is commonly written as N!!, or N!2, when using 6508the multifactorial notation. 6509 6510=item btfac() 6511 6512 $x->btfac(); # triple factorial of $x 6513 6514Returns the triple factorial of C<$x>, i.e., $x*($x-3)*($x-6)*... C<$x> must be 6515> -3. The triple factorial of N is commonly written as N!!!, or N!3, when using 6516the multifactorial notation. 6517 6518=item bmfac() 6519 6520 $x->bmfac($k); # $k'th multifactorial of $x 6521 6522Returns the multi-factorial of C<$x>, i.e., $x*($x-$k)*($x-2*$k)*... C<$x> must 6523be > -$k. The multi-factorial of N is commonly written as N!K. 6524 6525=item bfib() 6526 6527 $F = $n->bfib(); # a single Fibonacci number 6528 @F = $n->bfib(); # a list of Fibonacci numbers 6529 6530In scalar context, returns a single Fibonacci number. In list context, returns 6531a list of Fibonacci numbers. The invocand is the last element in the output. 6532 6533The Fibonacci sequence is defined by 6534 6535 F(0) = 0 6536 F(1) = 1 6537 F(n) = F(n-1) + F(n-2) 6538 6539In list context, F(0) and F(n) is the first and last number in the output, 6540respectively. For example, if $n is 12, then C<< @F = $n->bfib() >> returns the 6541following values, F(0) to F(12): 6542 6543 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 6544 6545The sequence can also be extended to negative index n using the re-arranged 6546recurrence relation 6547 6548 F(n-2) = F(n) - F(n-1) 6549 6550giving the bidirectional sequence 6551 6552 n -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 6553 F(n) 13 -8 5 -3 2 -1 1 0 1 1 2 3 5 8 13 6554 6555If $n is -12, the following values, F(0) to F(12), are returned: 6556 6557 0, 1, -1, 2, -3, 5, -8, 13, -21, 34, -55, 89, -144 6558 6559=item blucas() 6560 6561 $F = $n->blucas(); # a single Lucas number 6562 @F = $n->blucas(); # a list of Lucas numbers 6563 6564In scalar context, returns a single Lucas number. In list context, returns a 6565list of Lucas numbers. The invocand is the last element in the output. 6566 6567The Lucas sequence is defined by 6568 6569 L(0) = 2 6570 L(1) = 1 6571 L(n) = L(n-1) + L(n-2) 6572 6573In list context, L(0) and L(n) is the first and last number in the output, 6574respectively. For example, if $n is 12, then C<< @L = $n->blucas() >> returns 6575the following values, L(0) to L(12): 6576 6577 2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322 6578 6579The sequence can also be extended to negative index n using the re-arranged 6580recurrence relation 6581 6582 L(n-2) = L(n) - L(n-1) 6583 6584giving the bidirectional sequence 6585 6586 n -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 6587 L(n) 29 -18 11 -7 4 -3 1 2 1 3 4 7 11 18 29 6588 6589If $n is -12, the following values, L(0) to L(-12), are returned: 6590 6591 2, 1, -3, 4, -7, 11, -18, 29, -47, 76, -123, 199, -322 6592 6593=item brsft() 6594 6595 $x->brsft($n); # right shift $n places in base 2 6596 $x->brsft($n, $b); # right shift $n places in base $b 6597 6598The latter is equivalent to 6599 6600 $x -> bdiv($b -> copy() -> bpow($n)) 6601 6602=item blsft() 6603 6604 $x->blsft($n); # left shift $n places in base 2 6605 $x->blsft($n, $b); # left shift $n places in base $b 6606 6607The latter is equivalent to 6608 6609 $x -> bmul($b -> copy() -> bpow($n)) 6610 6611=back 6612 6613=head2 Bitwise methods 6614 6615=over 6616 6617=item band() 6618 6619 $x->band($y); # bitwise and 6620 6621=item bior() 6622 6623 $x->bior($y); # bitwise inclusive or 6624 6625=item bxor() 6626 6627 $x->bxor($y); # bitwise exclusive or 6628 6629=item bnot() 6630 6631 $x->bnot(); # bitwise not (two's complement) 6632 6633Two's complement (bitwise not). This is equivalent to, but faster than, 6634 6635 $x->binc()->bneg(); 6636 6637=back 6638 6639=head2 Rounding methods 6640 6641=over 6642 6643=item round() 6644 6645 $x->round($A,$P,$round_mode); 6646 6647Round $x to accuracy C<$A> or precision C<$P> using the round mode 6648C<$round_mode>. 6649 6650=item bround() 6651 6652 $x->bround($N); # accuracy: preserve $N digits 6653 6654Rounds $x to an accuracy of $N digits. 6655 6656=item bfround() 6657 6658 $x->bfround($N); 6659 6660Rounds to a multiple of 10**$N. Examples: 6661 6662 Input N Result 6663 6664 123456.123456 3 123500 6665 123456.123456 2 123450 6666 123456.123456 -2 123456.12 6667 123456.123456 -3 123456.123 6668 6669=item bfloor() 6670 6671 $x->bfloor(); 6672 6673Round $x towards minus infinity, i.e., set $x to the largest integer less than 6674or equal to $x. 6675 6676=item bceil() 6677 6678 $x->bceil(); 6679 6680Round $x towards plus infinity, i.e., set $x to the smallest integer greater 6681than or equal to $x). 6682 6683=item bint() 6684 6685 $x->bint(); 6686 6687Round $x towards zero. 6688 6689=back 6690 6691=head2 Other mathematical methods 6692 6693=over 6694 6695=item bgcd() 6696 6697 $x -> bgcd($y); # GCD of $x and $y 6698 $x -> bgcd($y, $z, ...); # GCD of $x, $y, $z, ... 6699 6700Returns the greatest common divisor (GCD). 6701 6702=item blcm() 6703 6704 $x -> blcm($y); # LCM of $x and $y 6705 $x -> blcm($y, $z, ...); # LCM of $x, $y, $z, ... 6706 6707Returns the least common multiple (LCM). 6708 6709=back 6710 6711=head2 Object property methods 6712 6713=over 6714 6715=item sign() 6716 6717 $x->sign(); 6718 6719Return the sign, of $x, meaning either C<+>, C<->, C<-inf>, C<+inf> or NaN. 6720 6721If you want $x to have a certain sign, use one of the following methods: 6722 6723 $x->babs(); # '+' 6724 $x->babs()->bneg(); # '-' 6725 $x->bnan(); # 'NaN' 6726 $x->binf(); # '+inf' 6727 $x->binf('-'); # '-inf' 6728 6729=item digit() 6730 6731 $x->digit($n); # return the nth digit, counting from right 6732 6733If C<$n> is negative, returns the digit counting from left. 6734 6735=item digitsum() 6736 6737 $x->digitsum(); 6738 6739Computes the sum of the base 10 digits and returns it. 6740 6741=item bdigitsum() 6742 6743 $x->bdigitsum(); 6744 6745Computes the sum of the base 10 digits and assigns the result to the invocand. 6746 6747=item length() 6748 6749 $x->length(); 6750 ($xl, $fl) = $x->length(); 6751 6752Returns the number of digits in the decimal representation of the number. In 6753list context, returns the length of the integer and fraction part. For 6754Math::BigInt objects, the length of the fraction part is always 0. 6755 6756The following probably doesn't do what you expect: 6757 6758 $c = Math::BigInt->new(123); 6759 print $c->length(),"\n"; # prints 30 6760 6761It prints both the number of digits in the number and in the fraction part 6762since print calls C<length()> in list context. Use something like: 6763 6764 print scalar $c->length(),"\n"; # prints 3 6765 6766=item mantissa() 6767 6768 $x->mantissa(); 6769 6770Return the signed mantissa of $x as a Math::BigInt. 6771 6772=item exponent() 6773 6774 $x->exponent(); 6775 6776Return the exponent of $x as a Math::BigInt. 6777 6778=item parts() 6779 6780 $x->parts(); 6781 6782Returns the significand (mantissa) and the exponent as integers. In 6783Math::BigFloat, both are returned as Math::BigInt objects. 6784 6785=item sparts() 6786 6787Returns the significand (mantissa) and the exponent as integers. In scalar 6788context, only the significand is returned. The significand is the integer with 6789the smallest absolute value. The output of C<sparts()> corresponds to the 6790output from C<bsstr()>. 6791 6792In Math::BigInt, this method is identical to C<parts()>. 6793 6794=item nparts() 6795 6796Returns the significand (mantissa) and exponent corresponding to normalized 6797notation. In scalar context, only the significand is returned. For finite 6798non-zero numbers, the significand's absolute value is greater than or equal to 67991 and less than 10. The output of C<nparts()> corresponds to the output from 6800C<bnstr()>. In Math::BigInt, if the significand can not be represented as an 6801integer, upgrading is performed or NaN is returned. 6802 6803=item eparts() 6804 6805Returns the significand (mantissa) and exponent corresponding to engineering 6806notation. In scalar context, only the significand is returned. For finite 6807non-zero numbers, the significand's absolute value is greater than or equal to 68081 and less than 1000, and the exponent is a multiple of 3. The output of 6809C<eparts()> corresponds to the output from C<bestr()>. In Math::BigInt, if the 6810significand can not be represented as an integer, upgrading is performed or NaN 6811is returned. 6812 6813=item dparts() 6814 6815Returns the integer part and the fraction part. If the fraction part can not be 6816represented as an integer, upgrading is performed or NaN is returned. The 6817output of C<dparts()> corresponds to the output from C<bdstr()>. 6818 6819=item fparts() 6820 6821Returns the smallest possible numerator and denominator so that the numerator 6822divided by the denominator gives back the original value. For finite numbers, 6823both values are integers. Mnemonic: fraction. 6824 6825=item numerator() 6826 6827Together with L</denominator()>, returns the smallest integers so that the 6828numerator divided by the denominator reproduces the original value. With 6829Math::BigInt, numerator() simply returns a copy of the invocand. 6830 6831=item denominator() 6832 6833Together with L</numerator()>, returns the smallest integers so that the 6834numerator divided by the denominator reproduces the original value. With 6835Math::BigInt, denominator() always returns either a 1 or a NaN. 6836 6837=back 6838 6839=head2 String conversion methods 6840 6841=over 6842 6843=item bstr() 6844 6845Returns a string representing the number using decimal notation. In 6846Math::BigFloat, the output is zero padded according to the current accuracy or 6847precision, if any of those are defined. 6848 6849=item bsstr() 6850 6851Returns a string representing the number using scientific notation where both 6852the significand (mantissa) and the exponent are integers. The output 6853corresponds to the output from C<sparts()>. 6854 6855 123 is returned as "123e+0" 6856 1230 is returned as "123e+1" 6857 12300 is returned as "123e+2" 6858 12000 is returned as "12e+3" 6859 10000 is returned as "1e+4" 6860 6861=item bnstr() 6862 6863Returns a string representing the number using normalized notation, the most 6864common variant of scientific notation. For finite non-zero numbers, the 6865absolute value of the significand is greater than or equal to 1 and less than 686610. The output corresponds to the output from C<nparts()>. 6867 6868 123 is returned as "1.23e+2" 6869 1230 is returned as "1.23e+3" 6870 12300 is returned as "1.23e+4" 6871 12000 is returned as "1.2e+4" 6872 10000 is returned as "1e+4" 6873 6874=item bestr() 6875 6876Returns a string representing the number using engineering notation. For finite 6877non-zero numbers, the absolute value of the significand is greater than or 6878equal to 1 and less than 1000, and the exponent is a multiple of 3. The output 6879corresponds to the output from C<eparts()>. 6880 6881 123 is returned as "123e+0" 6882 1230 is returned as "1.23e+3" 6883 12300 is returned as "12.3e+3" 6884 12000 is returned as "12e+3" 6885 10000 is returned as "10e+3" 6886 6887=item bdstr() 6888 6889Returns a string representing the number using decimal notation. The output 6890corresponds to the output from C<dparts()>. 6891 6892 123 is returned as "123" 6893 1230 is returned as "1230" 6894 12300 is returned as "12300" 6895 12000 is returned as "12000" 6896 10000 is returned as "10000" 6897 6898=item to_hex() 6899 6900 $x->to_hex(); 6901 6902Returns a hexadecimal string representation of the number. See also from_hex(). 6903 6904=item to_bin() 6905 6906 $x->to_bin(); 6907 6908Returns a binary string representation of the number. See also from_bin(). 6909 6910=item to_oct() 6911 6912 $x->to_oct(); 6913 6914Returns an octal string representation of the number. See also from_oct(). 6915 6916=item to_bytes() 6917 6918 $x = Math::BigInt->new("1667327589"); 6919 $s = $x->to_bytes(); # $s = "cafe" 6920 6921Returns a byte string representation of the number using big endian byte 6922order. The invocand must be a non-negative, finite integer. See also from_bytes(). 6923 6924=item to_base() 6925 6926 $x = Math::BigInt->new("250"); 6927 $x->to_base(2); # returns "11111010" 6928 $x->to_base(8); # returns "372" 6929 $x->to_base(16); # returns "fa" 6930 6931Returns a string representation of the number in the given base. If a collation 6932sequence is given, the collation sequence determines which characters are used 6933in the output. 6934 6935Here are some more examples 6936 6937 $x = Math::BigInt->new("16")->to_base(3); # returns "121" 6938 $x = Math::BigInt->new("44027")->to_base(36); # returns "XYZ" 6939 $x = Math::BigInt->new("58314")->to_base(42); # returns "Why" 6940 $x = Math::BigInt->new("4")->to_base(2, "-|"); # returns "|--" 6941 6942See from_base() for information and examples. 6943 6944=item to_base_num() 6945 6946Converts the given number to the given base. This method is equivalent to 6947C<_to_base()>, but returns numbers in an array rather than characters in a 6948string. In the output, the first element is the most significant. Unlike 6949C<_to_base()>, all input values may be arbitrarily large. 6950 6951 $x = Math::BigInt->new(13); 6952 $x->to_base_num(2); # returns [1, 1, 0, 1] 6953 6954 $x = Math::BigInt->new(65191); 6955 $x->to_base_num(128); # returns [3, 125, 39] 6956 6957=item as_hex() 6958 6959 $x->as_hex(); 6960 6961As, C<to_hex()>, but with a "0x" prefix. 6962 6963=item as_bin() 6964 6965 $x->as_bin(); 6966 6967As, C<to_bin()>, but with a "0b" prefix. 6968 6969=item as_oct() 6970 6971 $x->as_oct(); 6972 6973As, C<to_oct()>, but with a "0" prefix. 6974 6975=item as_bytes() 6976 6977This is just an alias for C<to_bytes()>. 6978 6979=back 6980 6981=head2 Other conversion methods 6982 6983=over 6984 6985=item numify() 6986 6987 print $x->numify(); 6988 6989Returns a Perl scalar from $x. It is used automatically whenever a scalar is 6990needed, for instance in array index operations. 6991 6992=back 6993 6994=head2 Utility methods 6995 6996These utility methods are made public 6997 6998=over 6999 7000=item dec_str_to_dec_flt_str() 7001 7002Takes a string representing any valid number using decimal notation and converts 7003it to a string representing the same number using decimal floating point 7004notation. The output consists of five parts joined together: the sign of the 7005significand, the absolute value of the significand as the smallest possible 7006integer, the letter "e", the sign of the exponent, and the absolute value of the 7007exponent. If the input is invalid, nothing is returned. 7008 7009 $str2 = $class -> dec_str_to_dec_flt_str($str1); 7010 7011Some examples 7012 7013 Input Output 7014 31400.00e-4 +314e-2 7015 -0.00012300e8 -123e+2 7016 0 +0e+0 7017 7018=item hex_str_to_dec_flt_str() 7019 7020Takes a string representing any valid number using hexadecimal notation and 7021converts it to a string representing the same number using decimal floating 7022point notation. The output has the same format as that of 7023L</dec_str_to_dec_flt_str()>. 7024 7025 $str2 = $class -> hex_str_to_dec_flt_str($str1); 7026 7027Some examples 7028 7029 Input Output 7030 0xff +255e+0 7031 7032Some examples 7033 7034=item oct_str_to_dec_flt_str() 7035 7036Takes a string representing any valid number using octal notation and converts 7037it to a string representing the same number using decimal floating point 7038notation. The output has the same format as that of 7039L</dec_str_to_dec_flt_str()>. 7040 7041 $str2 = $class -> oct_str_to_dec_flt_str($str1); 7042 7043=item bin_str_to_dec_flt_str() 7044 7045Takes a string representing any valid number using binary notation and converts 7046it to a string representing the same number using decimal floating point 7047notation. The output has the same format as that of 7048L</dec_str_to_dec_flt_str()>. 7049 7050 $str2 = $class -> bin_str_to_dec_flt_str($str1); 7051 7052=item dec_str_to_dec_str() 7053 7054Takes a string representing any valid number using decimal notation and converts 7055it to a string representing the same number using decimal notation. If the 7056number represents an integer, the output consists of a sign and the absolute 7057value. If the number represents a non-integer, the output consists of a sign, 7058the integer part of the number, the decimal point ".", and the fraction part of 7059the number without any trailing zeros. If the input is invalid, nothing is 7060returned. 7061 7062=item hex_str_to_dec_str() 7063 7064Takes a string representing any valid number using hexadecimal notation and 7065converts it to a string representing the same number using decimal notation. The 7066output has the same format as that of L</dec_str_to_dec_str()>. 7067 7068=item oct_str_to_dec_str() 7069 7070Takes a string representing any valid number using octal notation and converts 7071it to a string representing the same number using decimal notation. The 7072output has the same format as that of L</dec_str_to_dec_str()>. 7073 7074=item bin_str_to_dec_str() 7075 7076Takes a string representing any valid number using binary notation and converts 7077it to a string representing the same number using decimal notation. The output 7078has the same format as that of L</dec_str_to_dec_str()>. 7079 7080=back 7081 7082=head1 ACCURACY and PRECISION 7083 7084Math::BigInt and Math::BigFloat have full support for accuracy and precision 7085based rounding, both automatically after every operation, as well as manually. 7086 7087This section describes the accuracy/precision handling in Math::BigInt and 7088Math::BigFloat as it used to be and as it is now, complete with an explanation 7089of all terms and abbreviations. 7090 7091Not yet implemented things (but with correct description) are marked with '!', 7092things that need to be answered are marked with '?'. 7093 7094In the next paragraph follows a short description of terms used here (because 7095these may differ from terms used by others people or documentation). 7096 7097During the rest of this document, the shortcuts A (for accuracy), P (for 7098precision), F (fallback) and R (rounding mode) are be used. 7099 7100=head2 Precision P 7101 7102Precision is a fixed number of digits before (positive) or after (negative) the 7103decimal point. For example, 123.45 has a precision of -2. 0 means an integer 7104like 123 (or 120). A precision of 2 means at least two digits to the left of 7105the decimal point are zero, so 123 with P = 1 becomes 120. Note that numbers 7106with zeros before the decimal point may have different precisions, because 1200 7107can have P = 0, 1 or 2 (depending on what the initial value was). It could also 7108have p < 0, when the digits after the decimal point are zero. 7109 7110The string output (of floating point numbers) is padded with zeros: 7111 7112 Initial value P A Result String 7113 ------------------------------------------------------------ 7114 1234.01 -3 1000 1000 7115 1234 -2 1200 1200 7116 1234.5 -1 1230 1230 7117 1234.001 1 1234 1234.0 7118 1234.01 0 1234 1234 7119 1234.01 2 1234.01 1234.01 7120 1234.01 5 1234.01 1234.01000 7121 7122For Math::BigInt objects, no padding occurs. 7123 7124=head2 Accuracy A 7125 7126Number of significant digits. Leading zeros are not counted. A number may have 7127an accuracy greater than the non-zero digits when there are zeros in it or 7128trailing zeros. For example, 123.456 has A of 6, 10203 has 5, 123.0506 has 7, 7129123.45000 has 8 and 0.000123 has 3. 7130 7131The string output (of floating point numbers) is padded with zeros: 7132 7133 Initial value P A Result String 7134 ------------------------------------------------------------ 7135 1234.01 3 1230 1230 7136 1234.01 6 1234.01 1234.01 7137 1234.1 8 1234.1 1234.1000 7138 7139For Math::BigInt objects, no padding occurs. 7140 7141=head2 Fallback F 7142 7143When both A and P are undefined, this is used as a fallback accuracy when 7144dividing numbers. 7145 7146=head2 Rounding mode R 7147 7148When rounding a number, different 'styles' or 'kinds' of rounding are possible. 7149(Note that random rounding, as in Math::Round, is not implemented.) 7150 7151=head3 Directed rounding 7152 7153These round modes always round in the same direction. 7154 7155=over 7156 7157=item 'trunc' 7158 7159Round towards zero. Remove all digits following the rounding place, i.e., 7160replace them with zeros. Thus, 987.65 rounded to tens (P=1) becomes 980, and 7161rounded to the fourth significant digit becomes 987.6 (A=4). 123.456 rounded to 7162the second place after the decimal point (P=-2) becomes 123.46. This 7163corresponds to the IEEE 754 rounding mode 'roundTowardZero'. 7164 7165=back 7166 7167=head3 Rounding to nearest 7168 7169These rounding modes round to the nearest digit. They differ in how they 7170determine which way to round in the ambiguous case when there is a tie. 7171 7172=over 7173 7174=item 'even' 7175 7176Round towards the nearest even digit, e.g., when rounding to nearest integer, 7177-5.5 becomes -6, 4.5 becomes 4, but 4.501 becomes 5. This corresponds to the 7178IEEE 754 rounding mode 'roundTiesToEven'. 7179 7180=item 'odd' 7181 7182Round towards the nearest odd digit, e.g., when rounding to nearest integer, 71834.5 becomes 5, -5.5 becomes -5, but 5.501 becomes 6. This corresponds to the 7184IEEE 754 rounding mode 'roundTiesToOdd'. 7185 7186=item '+inf' 7187 7188Round towards plus infinity, i.e., always round up. E.g., when rounding to the 7189nearest integer, 4.5 becomes 5, -5.5 becomes -5, and 4.501 also becomes 5. This 7190corresponds to the IEEE 754 rounding mode 'roundTiesToPositive'. 7191 7192=item '-inf' 7193 7194Round towards minus infinity, i.e., always round down. E.g., when rounding to 7195the nearest integer, 4.5 becomes 4, -5.5 becomes -6, but 4.501 becomes 5. This 7196corresponds to the IEEE 754 rounding mode 'roundTiesToNegative'. 7197 7198=item 'zero' 7199 7200Round towards zero, i.e., round positive numbers down and negative numbers up. 7201E.g., when rounding to the nearest integer, 4.5 becomes 4, -5.5 becomes -5, but 72024.501 becomes 5. This corresponds to the IEEE 754 rounding mode 7203'roundTiesToZero'. 7204 7205=item 'common' 7206 7207Round away from zero, i.e., round to the number with the largest absolute 7208value. E.g., when rounding to the nearest integer, -1.5 becomes -2, 1.5 becomes 72092 and 1.49 becomes 1. This corresponds to the IEEE 754 rounding mode 7210'roundTiesToAway'. 7211 7212=back 7213 7214The handling of A & P in MBI/MBF (the old core code shipped with Perl versions 7215<= 5.7.2) is like this: 7216 7217=over 7218 7219=item Precision 7220 7221 * bfround($p) is able to round to $p number of digits after the decimal 7222 point 7223 * otherwise P is unused 7224 7225=item Accuracy (significant digits) 7226 7227 * bround($a) rounds to $a significant digits 7228 * only bdiv() and bsqrt() take A as (optional) parameter 7229 + other operations simply create the same number (bneg etc), or 7230 more (bmul) of digits 7231 + rounding/truncating is only done when explicitly calling one 7232 of bround or bfround, and never for Math::BigInt (not implemented) 7233 * bsqrt() simply hands its accuracy argument over to bdiv. 7234 * the documentation and the comment in the code indicate two 7235 different ways on how bdiv() determines the maximum number 7236 of digits it should calculate, and the actual code does yet 7237 another thing 7238 POD: 7239 max($Math::BigFloat::div_scale,length(dividend)+length(divisor)) 7240 Comment: 7241 result has at most max(scale, length(dividend), length(divisor)) digits 7242 Actual code: 7243 scale = max(scale, length(dividend)-1,length(divisor)-1); 7244 scale += length(divisor) - length(dividend); 7245 So for lx = 3, ly = 9, scale = 10, scale will actually be 16 (10 7246 So for lx = 3, ly = 9, scale = 10, scale will actually be 16 7247 (10+9-3). Actually, the 'difference' added to the scale is cal- 7248 culated from the number of "significant digits" in dividend and 7249 divisor, which is derived by looking at the length of the man- 7250 tissa. Which is wrong, since it includes the + sign (oops) and 7251 actually gets 2 for '+100' and 4 for '+101'. Oops again. Thus 7252 124/3 with div_scale=1 will get you '41.3' based on the strange 7253 assumption that 124 has 3 significant digits, while 120/7 will 7254 get you '17', not '17.1' since 120 is thought to have 2 signif- 7255 icant digits. The rounding after the division then uses the 7256 remainder and $y to determine whether it must round up or down. 7257 ? I have no idea which is the right way. That's why I used a slightly more 7258 ? simple scheme and tweaked the few failing testcases to match it. 7259 7260=back 7261 7262This is how it works now: 7263 7264=over 7265 7266=item Setting/Accessing 7267 7268 * You can set the A global via Math::BigInt->accuracy() or 7269 Math::BigFloat->accuracy() or whatever class you are using. 7270 * You can also set P globally by using Math::SomeClass->precision() 7271 likewise. 7272 * Globals are classwide, and not inherited by subclasses. 7273 * to undefine A, use Math::SomeClass->accuracy(undef); 7274 * to undefine P, use Math::SomeClass->precision(undef); 7275 * Setting Math::SomeClass->accuracy() clears automatically 7276 Math::SomeClass->precision(), and vice versa. 7277 * To be valid, A must be > 0, P can have any value. 7278 * If P is negative, this means round to the P'th place to the right of the 7279 decimal point; positive values mean to the left of the decimal point. 7280 P of 0 means round to integer. 7281 * to find out the current global A, use Math::SomeClass->accuracy() 7282 * to find out the current global P, use Math::SomeClass->precision() 7283 * use $x->accuracy() respective $x->precision() for the local 7284 setting of $x. 7285 * Please note that $x->accuracy() respective $x->precision() 7286 return eventually defined global A or P, when $x's A or P is not 7287 set. 7288 7289=item Creating numbers 7290 7291 * When you create a number, you can give the desired A or P via: 7292 $x = Math::BigInt->new($number,$A,$P); 7293 * Only one of A or P can be defined, otherwise the result is NaN 7294 * If no A or P is give ($x = Math::BigInt->new($number) form), then the 7295 globals (if set) will be used. Thus changing the global defaults later on 7296 will not change the A or P of previously created numbers (i.e., A and P of 7297 $x will be what was in effect when $x was created) 7298 * If given undef for A and P, NO rounding will occur, and the globals will 7299 NOT be used. This is used by subclasses to create numbers without 7300 suffering rounding in the parent. Thus a subclass is able to have its own 7301 globals enforced upon creation of a number by using 7302 $x = Math::BigInt->new($number,undef,undef): 7303 7304 use Math::BigInt::SomeSubclass; 7305 use Math::BigInt; 7306 7307 Math::BigInt->accuracy(2); 7308 Math::BigInt::SomeSubclass->accuracy(3); 7309 $x = Math::BigInt::SomeSubclass->new(1234); 7310 7311 $x is now 1230, and not 1200. A subclass might choose to implement 7312 this otherwise, e.g. falling back to the parent's A and P. 7313 7314=item Usage 7315 7316 * If A or P are enabled/defined, they are used to round the result of each 7317 operation according to the rules below 7318 * Negative P is ignored in Math::BigInt, since Math::BigInt objects never 7319 have digits after the decimal point 7320 * Math::BigFloat uses Math::BigInt internally, but setting A or P inside 7321 Math::BigInt as globals does not tamper with the parts of a Math::BigFloat. 7322 A flag is used to mark all Math::BigFloat numbers as 'never round'. 7323 7324=item Precedence 7325 7326 * It only makes sense that a number has only one of A or P at a time. 7327 If you set either A or P on one object, or globally, the other one will 7328 be automatically cleared. 7329 * If two objects are involved in an operation, and one of them has A in 7330 effect, and the other P, this results in an error (NaN). 7331 * A takes precedence over P (Hint: A comes before P). 7332 If neither of them is defined, nothing is used, i.e. the result will have 7333 as many digits as it can (with an exception for bdiv/bsqrt) and will not 7334 be rounded. 7335 * There is another setting for bdiv() (and thus for bsqrt()). If neither of 7336 A or P is defined, bdiv() will use a fallback (F) of $div_scale digits. 7337 If either the dividend's or the divisor's mantissa has more digits than 7338 the value of F, the higher value will be used instead of F. 7339 This is to limit the digits (A) of the result (just consider what would 7340 happen with unlimited A and P in the case of 1/3 :-) 7341 * bdiv will calculate (at least) 4 more digits than required (determined by 7342 A, P or F), and, if F is not used, round the result 7343 (this will still fail in the case of a result like 0.12345000000001 with A 7344 or P of 5, but this can not be helped - or can it?) 7345 * Thus you can have the math done by on Math::Big* class in two modi: 7346 + never round (this is the default): 7347 This is done by setting A and P to undef. No math operation 7348 will round the result, with bdiv() and bsqrt() as exceptions to guard 7349 against overflows. You must explicitly call bround(), bfround() or 7350 round() (the latter with parameters). 7351 Note: Once you have rounded a number, the settings will 'stick' on it 7352 and 'infect' all other numbers engaged in math operations with it, since 7353 local settings have the highest precedence. So, to get SaferRound[tm], 7354 use a copy() before rounding like this: 7355 7356 $x = Math::BigFloat->new(12.34); 7357 $y = Math::BigFloat->new(98.76); 7358 $z = $x * $y; # 1218.6984 7359 print $x->copy()->bround(3); # 12.3 (but A is now 3!) 7360 $z = $x * $y; # still 1218.6984, without 7361 # copy would have been 1210! 7362 7363 + round after each op: 7364 After each single operation (except for testing like is_zero()), the 7365 method round() is called and the result is rounded appropriately. By 7366 setting proper values for A and P, you can have all-the-same-A or 7367 all-the-same-P modes. For example, Math::Currency might set A to undef, 7368 and P to -2, globally. 7369 7370 ?Maybe an extra option that forbids local A & P settings would be in order, 7371 ?so that intermediate rounding does not 'poison' further math? 7372 7373=item Overriding globals 7374 7375 * you will be able to give A, P and R as an argument to all the calculation 7376 routines; the second parameter is A, the third one is P, and the fourth is 7377 R (shift right by one for binary operations like badd). P is used only if 7378 the first parameter (A) is undefined. These three parameters override the 7379 globals in the order detailed as follows, i.e. the first defined value 7380 wins: 7381 (local: per object, global: global default, parameter: argument to sub) 7382 + parameter A 7383 + parameter P 7384 + local A (if defined on both of the operands: smaller one is taken) 7385 + local P (if defined on both of the operands: bigger one is taken) 7386 + global A 7387 + global P 7388 + global F 7389 * bsqrt() will hand its arguments to bdiv(), as it used to, only now for two 7390 arguments (A and P) instead of one 7391 7392=item Local settings 7393 7394 * You can set A or P locally by using $x->accuracy() or 7395 $x->precision() 7396 and thus force different A and P for different objects/numbers. 7397 * Setting A or P this way immediately rounds $x to the new value. 7398 * $x->accuracy() clears $x->precision(), and vice versa. 7399 7400=item Rounding 7401 7402 * the rounding routines will use the respective global or local settings. 7403 bround() is for accuracy rounding, while bfround() is for precision 7404 * the two rounding functions take as the second parameter one of the 7405 following rounding modes (R): 7406 'even', 'odd', '+inf', '-inf', 'zero', 'trunc', 'common' 7407 * you can set/get the global R by using Math::SomeClass->round_mode() 7408 or by setting $Math::SomeClass::round_mode 7409 * after each operation, $result->round() is called, and the result may 7410 eventually be rounded (that is, if A or P were set either locally, 7411 globally or as parameter to the operation) 7412 * to manually round a number, call $x->round($A,$P,$round_mode); 7413 this will round the number by using the appropriate rounding function 7414 and then normalize it. 7415 * rounding modifies the local settings of the number: 7416 7417 $x = Math::BigFloat->new(123.456); 7418 $x->accuracy(5); 7419 $x->bround(4); 7420 7421 Here 4 takes precedence over 5, so 123.5 is the result and $x->accuracy() 7422 will be 4 from now on. 7423 7424=item Default values 7425 7426 * R: 'even' 7427 * F: 40 7428 * A: undef 7429 * P: undef 7430 7431=item Remarks 7432 7433 * The defaults are set up so that the new code gives the same results as 7434 the old code (except in a few cases on bdiv): 7435 + Both A and P are undefined and thus will not be used for rounding 7436 after each operation. 7437 + round() is thus a no-op, unless given extra parameters A and P 7438 7439=back 7440 7441=head1 Infinity and Not a Number 7442 7443While Math::BigInt has extensive handling of inf and NaN, certain quirks 7444remain. 7445 7446=over 7447 7448=item oct()/hex() 7449 7450These perl routines currently (as of Perl v.5.8.6) cannot handle passed inf. 7451 7452 te@linux:~> perl -wle 'print 2 ** 3333' 7453 Inf 7454 te@linux:~> perl -wle 'print 2 ** 3333 == 2 ** 3333' 7455 1 7456 te@linux:~> perl -wle 'print oct(2 ** 3333)' 7457 0 7458 te@linux:~> perl -wle 'print hex(2 ** 3333)' 7459 Illegal hexadecimal digit 'I' ignored at -e line 1. 7460 0 7461 7462The same problems occur if you pass them Math::BigInt->binf() objects. Since 7463overloading these routines is not possible, this cannot be fixed from 7464Math::BigInt. 7465 7466=back 7467 7468=head1 INTERNALS 7469 7470You should neither care about nor depend on the internal representation; it 7471might change without notice. Use B<ONLY> method calls like C<< $x->sign(); >> 7472instead relying on the internal representation. 7473 7474=head2 MATH LIBRARY 7475 7476The mathematical computations are performed by a backend library. It is not 7477required to specify which backend library to use, but some backend libraries 7478are much faster than the default library. 7479 7480=head3 The default library 7481 7482The default library is L<Math::BigInt::Calc>, which is implemented in pure Perl 7483and hence does not require a compiler. 7484 7485=head3 Specifying a library 7486 7487The simple case 7488 7489 use Math::BigInt; 7490 7491is equivalent to saying 7492 7493 use Math::BigInt try => 'Calc'; 7494 7495You can use a different backend library with, e.g., 7496 7497 use Math::BigInt try => 'GMP'; 7498 7499which attempts to load the L<Math::BigInt::GMP> library, and falls back to the 7500default library if the specified library can't be loaded. 7501 7502Multiple libraries can be specified by separating them by a comma, e.g., 7503 7504 use Math::BigInt try => 'GMP,Pari'; 7505 7506If you request a specific set of libraries and do not allow fallback to the 7507default library, specify them using "only", 7508 7509 use Math::BigInt only => 'GMP,Pari'; 7510 7511If you prefer a specific set of libraries, but want to see a warning if the 7512fallback library is used, specify them using "lib", 7513 7514 use Math::BigInt lib => 'GMP,Pari'; 7515 7516The following first tries to find Math::BigInt::Foo, then Math::BigInt::Bar, and 7517if this also fails, reverts to Math::BigInt::Calc: 7518 7519 use Math::BigInt try => 'Foo,Math::BigInt::Bar'; 7520 7521=head3 Which library to use? 7522 7523B<Note>: General purpose packages should not be explicit about the library to 7524use; let the script author decide which is best. 7525 7526L<Math::BigInt::GMP>, L<Math::BigInt::Pari>, and L<Math::BigInt::GMPz> are in 7527cases involving big numbers much faster than L<Math::BigInt::Calc>. However 7528these libraries are slower when dealing with very small numbers (less than about 752920 digits) and when converting very large numbers to decimal (for instance for 7530printing, rounding, calculating their length in decimal etc.). 7531 7532So please select carefully what library you want to use. 7533 7534Different low-level libraries use different formats to store the numbers, so 7535mixing them won't work. You should not depend on the number having a specific 7536internal format. 7537 7538See the respective math library module documentation for further details. 7539 7540=head3 Loading multiple libraries 7541 7542The first library that is successfully loaded is the one that will be used. Any 7543further attempts at loading a different module will be ignored. This is to avoid 7544the situation where module A requires math library X, and module B requires math 7545library Y, causing modules A and B to be incompatible. For example, 7546 7547 use Math::BigInt; # loads default "Calc" 7548 use Math::BigFloat only => "GMP"; # ignores "GMP" 7549 7550=head2 SIGN 7551 7552The sign is either '+', '-', 'NaN', '+inf' or '-inf'. 7553 7554A sign of 'NaN' is used to represent the result when input arguments are not 7555numbers or as a result of 0/0. '+inf' and '-inf' represent plus respectively 7556minus infinity. You get '+inf' when dividing a positive number by 0, and '-inf' 7557when dividing any negative number by 0. 7558 7559=head1 EXAMPLES 7560 7561 use Math::BigInt; 7562 7563 sub bigint { Math::BigInt->new(shift); } 7564 7565 $x = Math::BigInt->bstr("1234") # string "1234" 7566 $x = "$x"; # same as bstr() 7567 $x = Math::BigInt->bneg("1234"); # Math::BigInt "-1234" 7568 $x = Math::BigInt->babs("-12345"); # Math::BigInt "12345" 7569 $x = Math::BigInt->bnorm("-0.00"); # Math::BigInt "0" 7570 $x = bigint(1) + bigint(2); # Math::BigInt "3" 7571 $x = bigint(1) + "2"; # ditto ("2" becomes a Math::BigInt) 7572 $x = bigint(1); # Math::BigInt "1" 7573 $x = $x + 5 / 2; # Math::BigInt "3" 7574 $x = $x ** 3; # Math::BigInt "27" 7575 $x *= 2; # Math::BigInt "54" 7576 $x = Math::BigInt->new(0); # Math::BigInt "0" 7577 $x--; # Math::BigInt "-1" 7578 $x = Math::BigInt->badd(4,5) # Math::BigInt "9" 7579 print $x->bsstr(); # 9e+0 7580 7581Examples for rounding: 7582 7583 use Math::BigFloat; 7584 use Test::More; 7585 7586 $x = Math::BigFloat->new(123.4567); 7587 $y = Math::BigFloat->new(123.456789); 7588 Math::BigFloat->accuracy(4); # no more A than 4 7589 7590 is ($x->copy()->bround(),123.4); # even rounding 7591 print $x->copy()->bround(),"\n"; # 123.4 7592 Math::BigFloat->round_mode('odd'); # round to odd 7593 print $x->copy()->bround(),"\n"; # 123.5 7594 Math::BigFloat->accuracy(5); # no more A than 5 7595 Math::BigFloat->round_mode('odd'); # round to odd 7596 print $x->copy()->bround(),"\n"; # 123.46 7597 $y = $x->copy()->bround(4),"\n"; # A = 4: 123.4 7598 print "$y, ",$y->accuracy(),"\n"; # 123.4, 4 7599 7600 Math::BigFloat->accuracy(undef); # A not important now 7601 Math::BigFloat->precision(2); # P important 7602 print $x->copy()->bnorm(),"\n"; # 123.46 7603 print $x->copy()->bround(),"\n"; # 123.46 7604 7605Examples for converting: 7606 7607 my $x = Math::BigInt->new('0b1'.'01' x 123); 7608 print "bin: ",$x->as_bin()," hex:",$x->as_hex()," dec: ",$x,"\n"; 7609 7610=head1 NUMERIC LITERALS 7611 7612After C<use Math::BigInt ':constant'> all numeric literals in the given scope 7613are converted to C<Math::BigInt> objects. This conversion happens at compile 7614time. Every non-integer is convert to a NaN. 7615 7616For example, 7617 7618 perl -MMath::BigInt=:constant -le 'print 2**150' 7619 7620prints the exact value of C<2**150>. Note that without conversion of constants 7621to objects the expression C<2**150> is calculated using Perl scalars, which 7622leads to an inaccurate result. 7623 7624Please note that strings are not affected, so that 7625 7626 use Math::BigInt qw/:constant/; 7627 7628 $x = "1234567890123456789012345678901234567890" 7629 + "123456789123456789"; 7630 7631does give you what you expect. You need an explicit Math::BigInt->new() around 7632at least one of the operands. You should also quote large constants to prevent 7633loss of precision: 7634 7635 use Math::BigInt; 7636 7637 $x = Math::BigInt->new("1234567889123456789123456789123456789"); 7638 7639Without the quotes Perl first converts the large number to a floating point 7640constant at compile time, and then converts the result to a Math::BigInt object 7641at run time, which results in an inaccurate result. 7642 7643=head2 Hexadecimal, octal, and binary floating point literals 7644 7645Perl (and this module) accepts hexadecimal, octal, and binary floating point 7646literals, but use them with care with Perl versions before v5.32.0, because some 7647versions of Perl silently give the wrong result. Below are some examples of 7648different ways to write the number decimal 314. 7649 7650Hexadecimal floating point literals: 7651 7652 0x1.3ap+8 0X1.3AP+8 7653 0x1.3ap8 0X1.3AP8 7654 0x13a0p-4 0X13A0P-4 7655 7656Octal floating point literals (with "0" prefix): 7657 7658 01.164p+8 01.164P+8 7659 01.164p8 01.164P8 7660 011640p-4 011640P-4 7661 7662Octal floating point literals (with "0o" prefix) (requires v5.34.0): 7663 7664 0o1.164p+8 0O1.164P+8 7665 0o1.164p8 0O1.164P8 7666 0o11640p-4 0O11640P-4 7667 7668Binary floating point literals: 7669 7670 0b1.0011101p+8 0B1.0011101P+8 7671 0b1.0011101p8 0B1.0011101P8 7672 0b10011101000p-2 0B10011101000P-2 7673 7674=head1 PERFORMANCE 7675 7676Using the form $x += $y; etc over $x = $x + $y is faster, since a copy of $x 7677must be made in the second case. For long numbers, the copy can eat up to 20% 7678of the work (in the case of addition/subtraction, less for 7679multiplication/division). If $y is very small compared to $x, the form $x += $y 7680is MUCH faster than $x = $x + $y since making the copy of $x takes more time 7681then the actual addition. 7682 7683With a technique called copy-on-write, the cost of copying with overload could 7684be minimized or even completely avoided. A test implementation of COW did show 7685performance gains for overloaded math, but introduced a performance loss due to 7686a constant overhead for all other operations. So Math::BigInt does currently 7687not COW. 7688 7689The rewritten version of this module (vs. v0.01) is slower on certain 7690operations, like C<new()>, C<bstr()> and C<numify()>. The reason are that it 7691does now more work and handles much more cases. The time spent in these 7692operations is usually gained in the other math operations so that code on the 7693average should get (much) faster. If they don't, please contact the author. 7694 7695Some operations may be slower for small numbers, but are significantly faster 7696for big numbers. Other operations are now constant (O(1), like C<bneg()>, 7697C<babs()> etc), instead of O(N) and thus nearly always take much less time. 7698These optimizations were done on purpose. 7699 7700If you find the Calc module to slow, try to install any of the replacement 7701modules and see if they help you. 7702 7703=head2 Alternative math libraries 7704 7705You can use an alternative library to drive Math::BigInt. See the section 7706L</MATH LIBRARY> for more information. 7707 7708For more benchmark results see L<http://bloodgate.com/perl/benchmarks.html>. 7709 7710=head1 SUBCLASSING 7711 7712=head2 Subclassing Math::BigInt 7713 7714The basic design of Math::BigInt allows simple subclasses with very little 7715work, as long as a few simple rules are followed: 7716 7717=over 7718 7719=item * 7720 7721The public API must remain consistent, i.e. if a sub-class is overloading 7722addition, the sub-class must use the same name, in this case badd(). The reason 7723for this is that Math::BigInt is optimized to call the object methods directly. 7724 7725=item * 7726 7727The private object hash keys like C<< $x->{sign} >> may not be changed, but 7728additional keys can be added, like C<< $x->{_custom} >>. 7729 7730=item * 7731 7732Accessor functions are available for all existing object hash keys and should 7733be used instead of directly accessing the internal hash keys. The reason for 7734this is that Math::BigInt itself has a pluggable interface which permits it to 7735support different storage methods. 7736 7737=back 7738 7739More complex sub-classes may have to replicate more of the logic internal of 7740Math::BigInt if they need to change more basic behaviors. A subclass that needs 7741to merely change the output only needs to overload C<bstr()>. 7742 7743All other object methods and overloaded functions can be directly inherited 7744from the parent class. 7745 7746At the very minimum, any subclass needs to provide its own C<new()> and can 7747store additional hash keys in the object. There are also some package globals 7748that must be defined, e.g.: 7749 7750 # Globals 7751 $accuracy = undef; 7752 $precision = -2; # round to 2 decimal places 7753 $round_mode = 'even'; 7754 $div_scale = 40; 7755 7756Additionally, you might want to provide the following two globals to allow 7757auto-upgrading and auto-downgrading to work correctly: 7758 7759 $upgrade = undef; 7760 $downgrade = undef; 7761 7762This allows Math::BigInt to correctly retrieve package globals from the 7763subclass, like C<$SubClass::precision>. See t/Math/BigInt/Subclass.pm or 7764t/Math/BigFloat/SubClass.pm completely functional subclass examples. 7765 7766Don't forget to 7767 7768 use overload; 7769 7770in your subclass to automatically inherit the overloading from the parent. If 7771you like, you can change part of the overloading, look at Math::String for an 7772example. 7773 7774=head1 UPGRADING 7775 7776When used like this: 7777 7778 use Math::BigInt upgrade => 'Foo::Bar'; 7779 7780certain operations 'upgrade' their calculation and thus the result to the class 7781Foo::Bar. Usually this is used in conjunction with Math::BigFloat: 7782 7783 use Math::BigInt upgrade => 'Math::BigFloat'; 7784 7785As a shortcut, you can use the module L<bignum>: 7786 7787 use bignum; 7788 7789Also good for one-liners: 7790 7791 perl -Mbignum -le 'print 2 ** 255' 7792 7793This makes it possible to mix arguments of different classes (as in 2.5 + 2) as 7794well es preserve accuracy (as in sqrt(3)). 7795 7796Beware: This feature is not fully implemented yet. 7797 7798=head2 Auto-upgrade 7799 7800The following methods upgrade themselves unconditionally; that is if upgrade is 7801in effect, they always hands up their work: 7802 7803 div bsqrt blog bexp bpi bsin bcos batan batan2 7804 7805All other methods upgrade themselves only when one (or all) of their arguments 7806are of the class mentioned in $upgrade. 7807 7808=head1 EXPORTS 7809 7810C<Math::BigInt> exports nothing by default, but can export the following 7811methods: 7812 7813 bgcd 7814 blcm 7815 7816=head1 CAVEATS 7817 7818Some things might not work as you expect them. Below is documented what is 7819known to be troublesome: 7820 7821=over 7822 7823=item Comparing numbers as strings 7824 7825Both C<bstr()> and C<bsstr()> as well as stringify via overload drop the 7826leading '+'. This is to be consistent with Perl and to make C<cmp> (especially 7827with overloading) to work as you expect. It also solves problems with 7828C<Test.pm> and L<Test::More>, which stringify arguments before comparing them. 7829 7830Mark Biggar said, when asked about to drop the '+' altogether, or make only 7831C<cmp> work: 7832 7833 I agree (with the first alternative), don't add the '+' on positive 7834 numbers. It's not as important anymore with the new internal form 7835 for numbers. It made doing things like abs and neg easier, but 7836 those have to be done differently now anyway. 7837 7838So, the following examples now works as expected: 7839 7840 use Test::More tests => 1; 7841 use Math::BigInt; 7842 7843 my $x = Math::BigInt -> new(3*3); 7844 my $y = Math::BigInt -> new(3*3); 7845 7846 is($x,3*3, 'multiplication'); 7847 print "$x eq 9" if $x eq $y; 7848 print "$x eq 9" if $x eq '9'; 7849 print "$x eq 9" if $x eq 3*3; 7850 7851Additionally, the following still works: 7852 7853 print "$x == 9" if $x == $y; 7854 print "$x == 9" if $x == 9; 7855 print "$x == 9" if $x == 3*3; 7856 7857There is now a C<bsstr()> method to get the string in scientific notation aka 7858C<1e+2> instead of C<100>. Be advised that overloaded 'eq' always uses bstr() 7859for comparison, but Perl represents some numbers as 100 and others as 1e+308. 7860If in doubt, convert both arguments to Math::BigInt before comparing them as 7861strings: 7862 7863 use Test::More tests => 3; 7864 use Math::BigInt; 7865 7866 $x = Math::BigInt->new('1e56'); $y = 1e56; 7867 is($x,$y); # fails 7868 is($x->bsstr(),$y); # okay 7869 $y = Math::BigInt->new($y); 7870 is($x,$y); # okay 7871 7872Alternatively, simply use C<< <=> >> for comparisons, this always gets it 7873right. There is not yet a way to get a number automatically represented as a 7874string that matches exactly the way Perl represents it. 7875 7876See also the section about L<Infinity and Not a Number> for problems in 7877comparing NaNs. 7878 7879=item int() 7880 7881C<int()> returns (at least for Perl v5.7.1 and up) another Math::BigInt, not a 7882Perl scalar: 7883 7884 $x = Math::BigInt->new(123); 7885 $y = int($x); # 123 as a Math::BigInt 7886 $x = Math::BigFloat->new(123.45); 7887 $y = int($x); # 123 as a Math::BigFloat 7888 7889If you want a real Perl scalar, use C<numify()>: 7890 7891 $y = $x->numify(); # 123 as a scalar 7892 7893This is seldom necessary, though, because this is done automatically, like when 7894you access an array: 7895 7896 $z = $array[$x]; # does work automatically 7897 7898=item Modifying and = 7899 7900Beware of: 7901 7902 $x = Math::BigFloat->new(5); 7903 $y = $x; 7904 7905This makes a second reference to the B<same> object and stores it in $y. Thus 7906anything that modifies $x (except overloaded operators) also modifies $y, and 7907vice versa. Or in other words, C<=> is only safe if you modify your 7908Math::BigInt objects only via overloaded math. As soon as you use a method call 7909it breaks: 7910 7911 $x->bmul(2); 7912 print "$x, $y\n"; # prints '10, 10' 7913 7914If you want a true copy of $x, use: 7915 7916 $y = $x->copy(); 7917 7918You can also chain the calls like this, this first makes a copy and then 7919multiply it by 2: 7920 7921 $y = $x->copy()->bmul(2); 7922 7923See also the documentation for overload.pm regarding C<=>. 7924 7925=item Overloading -$x 7926 7927The following: 7928 7929 $x = -$x; 7930 7931is slower than 7932 7933 $x->bneg(); 7934 7935since overload calls C<sub($x,0,1);> instead of C<neg($x)>. The first variant 7936needs to preserve $x since it does not know that it later gets overwritten. 7937This makes a copy of $x and takes O(N), but $x->bneg() is O(1). 7938 7939=item Mixing different object types 7940 7941With overloaded operators, it is the first (dominating) operand that determines 7942which method is called. Here are some examples showing what actually gets 7943called in various cases. 7944 7945 use Math::BigInt; 7946 use Math::BigFloat; 7947 7948 $mbf = Math::BigFloat->new(5); 7949 $mbi2 = Math::BigInt->new(5); 7950 $mbi = Math::BigInt->new(2); 7951 # what actually gets called: 7952 $float = $mbf + $mbi; # $mbf->badd($mbi) 7953 $float = $mbf / $mbi; # $mbf->bdiv($mbi) 7954 $integer = $mbi + $mbf; # $mbi->badd($mbf) 7955 $integer = $mbi2 / $mbi; # $mbi2->bdiv($mbi) 7956 $integer = $mbi2 / $mbf; # $mbi2->bdiv($mbf) 7957 7958For instance, Math::BigInt->bdiv() always returns a Math::BigInt, regardless of 7959whether the second operant is a Math::BigFloat. To get a Math::BigFloat you 7960either need to call the operation manually, make sure each operand already is a 7961Math::BigFloat, or cast to that type via Math::BigFloat->new(): 7962 7963 $float = Math::BigFloat->new($mbi2) / $mbi; # = 2.5 7964 7965Beware of casting the entire expression, as this would cast the 7966result, at which point it is too late: 7967 7968 $float = Math::BigFloat->new($mbi2 / $mbi); # = 2 7969 7970Beware also of the order of more complicated expressions like: 7971 7972 $integer = ($mbi2 + $mbi) / $mbf; # int / float => int 7973 $integer = $mbi2 / Math::BigFloat->new($mbi); # ditto 7974 7975If in doubt, break the expression into simpler terms, or cast all operands 7976to the desired resulting type. 7977 7978Scalar values are a bit different, since: 7979 7980 $float = 2 + $mbf; 7981 $float = $mbf + 2; 7982 7983both result in the proper type due to the way the overloaded math works. 7984 7985This section also applies to other overloaded math packages, like Math::String. 7986 7987One solution to you problem might be autoupgrading|upgrading. See the 7988pragmas L<bignum>, L<bigint> and L<bigrat> for an easy way to do this. 7989 7990=back 7991 7992=head1 BUGS 7993 7994Please report any bugs or feature requests to 7995C<bug-math-bigint at rt.cpan.org>, or through the web interface at 7996L<https://rt.cpan.org/Ticket/Create.html?Queue=Math-BigInt> (requires login). 7997We will be notified, and then you'll automatically be notified of progress on 7998your bug as I make changes. 7999 8000=head1 SUPPORT 8001 8002You can find documentation for this module with the perldoc command. 8003 8004 perldoc Math::BigInt 8005 8006You can also look for information at: 8007 8008=over 4 8009 8010=item * GitHub 8011 8012L<https://github.com/pjacklam/p5-Math-BigInt> 8013 8014=item * RT: CPAN's request tracker 8015 8016L<https://rt.cpan.org/Dist/Display.html?Name=Math-BigInt> 8017 8018=item * MetaCPAN 8019 8020L<https://metacpan.org/release/Math-BigInt> 8021 8022=item * CPAN Testers Matrix 8023 8024L<http://matrix.cpantesters.org/?dist=Math-BigInt> 8025 8026=item * CPAN Ratings 8027 8028L<https://cpanratings.perl.org/dist/Math-BigInt> 8029 8030=item * The Bignum mailing list 8031 8032=over 4 8033 8034=item * Post to mailing list 8035 8036C<bignum at lists.scsys.co.uk> 8037 8038=item * View mailing list 8039 8040L<http://lists.scsys.co.uk/pipermail/bignum/> 8041 8042=item * Subscribe/Unsubscribe 8043 8044L<http://lists.scsys.co.uk/cgi-bin/mailman/listinfo/bignum> 8045 8046=back 8047 8048=back 8049 8050=head1 LICENSE 8051 8052This program is free software; you may redistribute it and/or modify it under 8053the same terms as Perl itself. 8054 8055=head1 SEE ALSO 8056 8057L<Math::BigFloat> and L<Math::BigRat> as well as the backends 8058L<Math::BigInt::FastCalc>, L<Math::BigInt::GMP>, and L<Math::BigInt::Pari>. 8059 8060The pragmas L<bignum>, L<bigint> and L<bigrat> also might be of interest 8061because they solve the autoupgrading/downgrading issue, at least partly. 8062 8063=head1 AUTHORS 8064 8065=over 4 8066 8067=item * 8068 8069Mark Biggar, overloaded interface by Ilya Zakharevich, 1996-2001. 8070 8071=item * 8072 8073Completely rewritten by Tels L<http://bloodgate.com>, 2001-2008. 8074 8075=item * 8076 8077Florian Ragwitz E<lt>flora@cpan.orgE<gt>, 2010. 8078 8079=item * 8080 8081Peter John Acklam E<lt>pjacklam@gmail.comE<gt>, 2011-. 8082 8083=back 8084 8085Many people contributed in one or more ways to the final beast, see the file 8086CREDITS for an (incomplete) list. If you miss your name, please drop me a 8087mail. Thank you! 8088 8089=cut 8090