BigFloat.pm 178 KB
Newer Older
1 2
package Math::BigFloat;

3
#
4 5 6
# Mike grinned. 'Two down, infinity to go' - Mike Nostrus in 'Before and After'
#

7 8 9 10 11 12 13
# The following hash values are used internally:
# sign  : "+", "-", "+inf", "-inf", or "NaN" if not a number
#   _m  : mantissa ($CALC object)
#   _es : sign of _e
#   _e  : exponent ($CALC object)
#   _a  : accuracy
#   _p  : precision
14

15
use 5.006001;
16 17 18
use strict;
use warnings;

19
use Carp ();
20
use Math::BigInt ();
21

22
our $VERSION = '1.999808';
23 24

require Exporter;
25 26
our @ISA        = qw/Math::BigInt/;
our @EXPORT_OK  = qw/bpi/;
27 28

# $_trap_inf/$_trap_nan are internal and should never be accessed from outside
29 30 31
our ($AUTOLOAD, $accuracy, $precision, $div_scale, $round_mode, $rnd_mode,
     $upgrade, $downgrade, $_trap_nan, $_trap_inf);

32 33 34
my $class = "Math::BigFloat";

use overload
35 36 37 38 39

  # overload key: with_assign

  '+'     =>      sub { $_[0] -> copy() -> badd($_[1]); },

40 41
  '-'     =>      sub { my $c = $_[0] -> copy();
                        $_[2] ? $c -> bneg() -> badd($_[1])
42 43 44 45 46
                              : $c -> bsub($_[1]); },

  '*'     =>      sub { $_[0] -> copy() -> bmul($_[1]); },

  '/'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bdiv($_[0])
47
                              : $_[0] -> copy() -> bdiv($_[1]); },
48 49

  '%'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bmod($_[0])
50
                              : $_[0] -> copy() -> bmod($_[1]); },
51 52

  '**'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bpow($_[0])
53
                              : $_[0] -> copy() -> bpow($_[1]); },
54 55

  '<<'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> blsft($_[0])
56
                              : $_[0] -> copy() -> blsft($_[1]); },
57 58

  '>>'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> brsft($_[0])
59
                              : $_[0] -> copy() -> brsft($_[1]); },
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130

  # overload key: assign

  '+='    =>      sub { $_[0]->badd($_[1]); },

  '-='    =>      sub { $_[0]->bsub($_[1]); },

  '*='    =>      sub { $_[0]->bmul($_[1]); },

  '/='    =>      sub { scalar $_[0]->bdiv($_[1]); },

  '%='    =>      sub { $_[0]->bmod($_[1]); },

  '**='   =>      sub { $_[0]->bpow($_[1]); },


  '<<='   =>      sub { $_[0]->blsft($_[1]); },

  '>>='   =>      sub { $_[0]->brsft($_[1]); },

#  'x='    =>      sub { },

#  '.='    =>      sub { },

  # overload key: num_comparison

  '<'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> blt($_[0])
                              : $_[0] -> blt($_[1]); },

  '<='    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> ble($_[0])
                              : $_[0] -> ble($_[1]); },

  '>'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bgt($_[0])
                              : $_[0] -> bgt($_[1]); },

  '>='    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bge($_[0])
                              : $_[0] -> bge($_[1]); },

  '=='    =>      sub { $_[0] -> beq($_[1]); },

  '!='    =>      sub { $_[0] -> bne($_[1]); },

  # overload key: 3way_comparison

  '<=>'   =>      sub { my $cmp = $_[0] -> bcmp($_[1]);
                        defined($cmp) && $_[2] ? -$cmp : $cmp; },

  'cmp'   =>      sub { $_[2] ? "$_[1]" cmp $_[0] -> bstr()
                              : $_[0] -> bstr() cmp "$_[1]"; },

  # overload key: str_comparison

#  'lt'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrlt($_[0])
#                              : $_[0] -> bstrlt($_[1]); },
#
#  'le'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrle($_[0])
#                              : $_[0] -> bstrle($_[1]); },
#
#  'gt'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrgt($_[0])
#                              : $_[0] -> bstrgt($_[1]); },
#
#  'ge'    =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bstrge($_[0])
#                              : $_[0] -> bstrge($_[1]); },
#
#  'eq'    =>      sub { $_[0] -> bstreq($_[1]); },
#
#  'ne'    =>      sub { $_[0] -> bstrne($_[1]); },

  # overload key: binary

  '&'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> band($_[0])
131
                              : $_[0] -> copy() -> band($_[1]); },
132 133 134 135

  '&='    =>      sub { $_[0] -> band($_[1]); },

  '|'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bior($_[0])
136
                              : $_[0] -> copy() -> bior($_[1]); },
137 138 139 140

  '|='    =>      sub { $_[0] -> bior($_[1]); },

  '^'     =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bxor($_[0])
141
                              : $_[0] -> copy() -> bxor($_[1]); },
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177

  '^='    =>      sub { $_[0] -> bxor($_[1]); },

#  '&.'    =>      sub { },

#  '&.='   =>      sub { },

#  '|.'    =>      sub { },

#  '|.='   =>      sub { },

#  '^.'    =>      sub { },

#  '^.='   =>      sub { },

  # overload key: unary

  'neg'   =>      sub { $_[0] -> copy() -> bneg(); },

#  '!'     =>      sub { },

  '~'     =>      sub { $_[0] -> copy() -> bnot(); },

#  '~.'    =>      sub { },

  # overload key: mutators

  '++'    =>      sub { $_[0] -> binc() },

  '--'    =>      sub { $_[0] -> bdec() },

  # overload key: func

  'atan2' =>      sub { $_[2] ? ref($_[0]) -> new($_[1]) -> batan2($_[0])
                              : $_[0] -> copy() -> batan2($_[1]); },

178
  'cos'   =>      sub { $_[0] -> copy() -> bcos(); },
179

180
  'sin'   =>      sub { $_[0] -> copy() -> bsin(); },
181 182 183 184 185 186 187 188 189

  'exp'   =>      sub { $_[0] -> copy() -> bexp($_[1]); },

  'abs'   =>      sub { $_[0] -> copy() -> babs(); },

  'log'   =>      sub { $_[0] -> copy() -> blog(); },

  'sqrt'  =>      sub { $_[0] -> copy() -> bsqrt(); },

190
  'int'   =>      sub { $_[0] -> copy() -> bint(); },
191 192 193 194 195 196 197 198 199 200 201 202

  # overload key: conversion

  'bool'  =>      sub { $_[0] -> is_zero() ? '' : 1; },

  '""'    =>      sub { $_[0] -> bstr(); },

  '0+'    =>      sub { $_[0] -> numify(); },

  '='     =>      sub { $_[0]->copy(); },

  ;
203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219

##############################################################################
# global constants, flags and assorted stuff

# the following are public, but their usage is not recommended. Use the
# accessor methods instead.

# class constants, use Class->constant_name() to access
# one of 'even', 'odd', '+inf', '-inf', 'zero', 'trunc' or 'common'
$round_mode = 'even';
$accuracy   = undef;
$precision  = undef;
$div_scale  = 40;

$upgrade = undef;
$downgrade = undef;
# the package we are using for our private parts, defaults to:
220
# Math::BigInt->config('lib')
221
my $MBI = 'Math::BigInt::Calc';
222 223 224 225 226 227 228

# are NaNs ok? (otherwise it dies when encountering an NaN) set w/ config()
$_trap_nan = 0;
# the same for infinity
$_trap_inf = 0;

# constant for easier life
229
my $nan = 'NaN';
230

231
my $IMPORT = 0; # was import() called yet? used to make require work
232

233 234
# some digits of accuracy for blog(undef, 10); which we use in blog() for speed
my $LOG_10 =
235 236 237
 '2.3025850929940456840179914546843642076011014886287729760333279009675726097';
my $LOG_10_A = length($LOG_10)-1;
# ditto for log(2)
238
my $LOG_2 =
239 240
 '0.6931471805599453094172321214581765680755001343602552541206800094933936220';
my $LOG_2_A = length($LOG_2)-1;
241
my $HALF = '0.5';                       # made into an object if nec.
242 243 244 245

##############################################################################
# the old code had $rnd_mode, so we need to support it, too

246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
sub TIESCALAR {
    my ($class) = @_;
    bless \$round_mode, $class;
}

sub FETCH {
    return $round_mode;
}

sub STORE {
    $rnd_mode = $_[0]->round_mode($_[1]);
}

BEGIN {
    # when someone sets $rnd_mode, we catch this and check the value to see
    # whether it is valid or not.
    $rnd_mode   = 'even';
    tie $rnd_mode, 'Math::BigFloat';
264

265 266 267 268 269 270 271 272 273
    # we need both of them in this package:
    *as_int = \&as_number;
}

sub DESTROY {
    # going through AUTOLOAD for every DESTROY is costly, avoid it by empty sub
}

sub AUTOLOAD {
274
    # make fxxx and bxxx both work by selectively mapping fxxx() to MBF::bxxx()
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
    my $name = $AUTOLOAD;

    $name =~ s/(.*):://;        # split package
    my $c = $1 || $class;
    no strict 'refs';
    $c->import() if $IMPORT == 0;
    if (!_method_alias($name)) {
        if (!defined $name) {
            # delayed load of Carp and avoid recursion
            Carp::croak("$c: Can't call a method without name");
        }
        if (!_method_hand_up($name)) {
            # delayed load of Carp and avoid recursion
            Carp::croak("Can't call $c\-\>$name, not a valid method");
        }
        # try one level up, but subst. bxxx() for fxxx() since MBI only got bxxx()
        $name =~ s/^f/b/;
        return &{"Math::BigInt"."::$name"}(@_);
    }
    my $bname = $name;
    $bname =~ s/^f/b/;
    $c .= "::$name";
    *{$c} = \&{$bname};
    &{$c};                      # uses @_
}
300 301 302 303

##############################################################################

{
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
    # valid method aliases for AUTOLOAD
    my %methods = map { $_ => 1 }
      qw / fadd fsub fmul fdiv fround ffround fsqrt fmod fstr fsstr fpow fnorm
           fint facmp fcmp fzero fnan finf finc fdec ffac fneg
           fceil ffloor frsft flsft fone flog froot fexp
         /;
    # valid methods that can be handed up (for AUTOLOAD)
    my %hand_ups = map { $_ => 1 }
      qw / is_nan is_inf is_negative is_positive is_pos is_neg
           accuracy precision div_scale round_mode fabs fnot
           objectify upgrade downgrade
           bone binf bnan bzero
           bsub
         /;

    sub _method_alias { exists $methods{$_[0]||''}; }
    sub _method_hand_up { exists $hand_ups{$_[0]||''}; }
321 322
}

323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
sub DEBUG () { 0; }

sub isa {
    my ($self, $class) = @_;
    return if $class =~ /^Math::BigInt/; # we aren't one of these
    UNIVERSAL::isa($self, $class);
}

sub config {
    # return (later set?) configuration data as hash ref
    my $class = shift || 'Math::BigFloat';

    if (@_ == 1 && ref($_[0]) ne 'HASH') {
        my $cfg = $class->SUPER::config();
        return $cfg->{$_[0]};
    }

    my $cfg = $class->SUPER::config(@_);

    # now we need only to override the ones that are different from our parent
    $cfg->{class} = $class;
    $cfg->{with} = $MBI;
    $cfg;
}

###############################################################################
# Constructor methods
###############################################################################
351

352
sub new {
353
    # Create a new Math::BigFloat object from a string or another bigfloat object.
354 355
    # _e: exponent
    # _m: mantissa
356
    # sign  => ("+", "-", "+inf", "-inf", or "NaN")
357

358 359 360
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;
361

362
    my ($wanted, @r) = @_;
363

364
    # avoid numify-calls by not using || on $wanted!
365

366
    unless (defined $wanted) {
367
        #Carp::carp("Use of uninitialized value in new");
368
        return $self->bzero(@r);
369 370
    }

371 372
    # Using $wanted->isa("Math::BigFloat") here causes a 'Deep recursion on
    # subroutine "Math::BigFloat::as_number"' in some tests. Fixme!
373

374 375 376 377 378 379 380 381
    if (UNIVERSAL::isa($wanted, 'Math::BigFloat')) {
        my $copy = $wanted -> copy();
        if ($selfref) {                 # if new() called as instance method
            %$self = %$copy;
        } else {                        # if new() called as class method
            $self = $copy;
        }
        return $copy;
382 383
    }

384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
    $class->import() if $IMPORT == 0;             # make require work

    # If called as a class method, initialize a new object.

    $self = bless {}, $class unless $selfref;

    # shortcut for bigints and its subclasses
    if ((ref($wanted)) && $wanted -> can("as_number")) {
        $self->{_m} = $wanted->as_number()->{value};  # get us a bigint copy
        $self->{_e} = $MBI->_zero();
        $self->{_es} = '+';
        $self->{sign} = $wanted->sign();
        return $self->bnorm();
    }

    # else: got a string or something masquerading as number (with overload)

    # Handle Infs.

    if ($wanted =~ /^\s*([+-]?)inf(inity)?\s*\z/i) {
        return $downgrade->new($wanted) if $downgrade;
        my $sgn = $1 || '+';
        $self->{sign} = $sgn . 'inf';   # set a default sign for bstr()
        return $self->binf($sgn);
    }

410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
    # Handle explicit NaNs (not the ones returned due to invalid input).

    if ($wanted =~ /^\s*([+-]?)nan\s*\z/i) {
        return $downgrade->new($wanted) if $downgrade;
        $self = $class -> bnan();
        $self->round(@r) unless @r >= 2 && !defined $r[0] && !defined $r[1];
        return $self;
    }

    # Handle hexadecimal numbers.

    if ($wanted =~ /^\s*[+-]?0[Xx]/) {
        $self = $class -> from_hex($wanted);
        $self->round(@r) unless @r >= 2 && !defined $r[0] && !defined $r[1];
        return $self;
    }

    # Handle binary numbers.

    if ($wanted =~ /^\s*[+-]?0[Bb]/) {
        $self = $class -> from_bin($wanted);
        $self->round(@r) unless @r >= 2 && !defined $r[0] && !defined $r[1];
        return $self;
    }

435 436
    # Shortcut for simple forms like '12' that have no trailing zeros.
    if ($wanted =~ /^([+-]?)0*([1-9][0-9]*[1-9])$/) {
437 438
        $self->{_e}   = $MBI -> _zero();
        $self->{_es}  = '+';
439
        $self->{sign} = $1 || '+';
440 441 442 443 444
        $self->{_m}   = $MBI -> _new($2);
        if (!$downgrade) {
            $self->round(@r) unless @r >= 2 && !defined $r[0] && !defined $r[1];
            return $self;
        }
445 446
    }

447 448 449 450
    my ($mis, $miv, $mfv, $es, $ev) = Math::BigInt::_split($wanted);
    if (!ref $mis) {
        if ($_trap_nan) {
            Carp::croak("$wanted is not a number initialized to $class");
451 452
        }

453
        return $downgrade->bnan() if $downgrade;
454

455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
        $self->{_e} = $MBI->_zero();
        $self->{_es} = '+';
        $self->{_m} = $MBI->_zero();
        $self->{sign} = $nan;
    } else {
        # make integer from mantissa by adjusting exp, then convert to int
        $self->{_e} = $MBI->_new($$ev); # exponent
        $self->{_es} = $$es || '+';
        my $mantissa = "$$miv$$mfv";     # create mant.
        $mantissa =~ s/^0+(\d)/$1/;      # strip leading zeros
        $self->{_m} = $MBI->_new($mantissa); # create mant.

        # 3.123E0 = 3123E-3, and 3.123E-2 => 3123E-5
        if (CORE::length($$mfv) != 0) {
            my $len = $MBI->_new(CORE::length($$mfv));
            ($self->{_e}, $self->{_es}) =
              _e_sub($self->{_e}, $len, $self->{_es}, '+');
        }
        # we can only have trailing zeros on the mantissa if $$mfv eq ''
        else {
            # Use a regexp to count the trailing zeros in $$miv instead of
            # _zeros() because that is faster, especially when _m is not stored
            # in base 10.
            my $zeros = 0;
            $zeros = CORE::length($1) if $$miv =~ /[1-9](0*)$/;
            if ($zeros != 0) {
                my $z = $MBI->_new($zeros);
                # turn '120e2' into '12e3'
483
                $self->{_m} = $MBI->_rsft($self->{_m}, $z, 10);
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
                ($self->{_e}, $self->{_es}) =
                  _e_add($self->{_e}, $z, $self->{_es}, '+');
            }
        }
        $self->{sign} = $$mis;

        # for something like 0Ey, set y to 0, and -0 => +0
        # Check $$miv for being '0' and $$mfv eq '', because otherwise _m could not
        # have become 0. That's faster than to call $MBI->_is_zero().
        $self->{sign} = '+', $self->{_e} = $MBI->_zero()
          if $$miv eq '0' and $$mfv eq '';

        if (!$downgrade) {
            $self->round(@r) unless @r >= 2 && !defined $r[0] && !defined $r[1];
            return $self;
        }
500 501
    }

502 503 504 505 506 507 508
    # if downgrade, inf, NaN or integers go down

    if ($downgrade && $self->{_es} eq '+') {
        if ($MBI->_is_zero($self->{_e})) {
            return $downgrade->new($$mis . $MBI->_str($self->{_m}));
        }
        return $downgrade->new($self->bsstr());
509
    }
510 511 512 513 514
    $self->bnorm();
    $self->round(@r) unless @r >= 2 && !defined $r[0] && !defined $r[1];
    return $self;
}

515
sub from_hex {
516 517 518 519
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

520 521 522 523
    # Don't modify constant (read-only) objects.

    return if $selfref && $self->modify('from_hex');

524
    my $str = shift;
525

526
    # If called as a class method, initialize a new object.
527

528
    $self = $class -> bzero() unless $selfref;
529

530 531
    if ($str =~ s/
                     ^
532
                     \s*
533

534 535
                     # sign
                     ( [+-]? )
536

537 538
                     # optional "hex marker"
                     (?: 0? x )?
539

540 541 542 543 544 545 546 547 548 549 550
                     # significand using the hex digits 0..9 and a..f
                     (
                         [0-9a-fA-F]+ (?: _ [0-9a-fA-F]+ )*
                         (?:
                             \.
                             (?: [0-9a-fA-F]+ (?: _ [0-9a-fA-F]+ )* )?
                         )?
                     |
                         \.
                         [0-9a-fA-F]+ (?: _ [0-9a-fA-F]+ )*
                     )
551

552 553 554 555 556 557
                     # exponent (power of 2) using decimal digits
                     (?:
                         [Pp]
                         ( [+-]? )
                         ( \d+ (?: _ \d+ )* )
                     )?
558

559
                     \s*
560 561
                     $
                 //x)
562
    {
563 564 565 566 567 568
        my $s_sign  = $1 || '+';
        my $s_value = $2;
        my $e_sign  = $3 || '+';
        my $e_value = $4 || '0';
        $s_value =~ tr/_//d;
        $e_value =~ tr/_//d;
569

570
        # The significand must be multiplied by 2 raised to this exponent.
571

572 573
        my $two_expon = $class -> new($e_value);
        $two_expon -> bneg() if $e_sign eq '-';
574

575 576 577 578 579
        # If there is a dot in the significand, remove it and adjust the
        # exponent according to the number of digits in the fraction part of
        # the significand. Since the digits in the significand are in base 16,
        # but the exponent is only in base 2, multiply the exponent adjustment
        # value by log(16) / log(2) = 4.
580

581 582 583 584 585 586 587
        my $idx = index($s_value, '.');
        if ($idx >= 0) {
            substr($s_value, $idx, 1) = '';
            $two_expon -= $class -> new(CORE::length($s_value))
                                 -> bsub($idx)
                                 -> bmul("4");
        }
588

589 590
        $self -> {sign} = $s_sign;
        $self -> {_m}   = $MBI -> _from_hex('0x' . $s_value);
591

592 593 594 595 596 597 598
        if ($two_expon > 0) {
            my $factor = $class -> new("2") -> bpow($two_expon);
            $self -> bmul($factor);
        } elsif ($two_expon < 0) {
            my $factor = $class -> new("0.5") -> bpow(-$two_expon);
            $self -> bmul($factor);
        }
599

600
        return $self;
601 602
    }

603 604 605 606
    return $self->bnan();
}

sub from_oct {
607 608 609 610
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

611 612 613 614
    # Don't modify constant (read-only) objects.

    return if $selfref && $self->modify('from_oct');

615
    my $str = shift;
616

617
    # If called as a class method, initialize a new object.
618

619
    $self = $class -> bzero() unless $selfref;
620

621 622
    if ($str =~ s/
                     ^
623
                     \s*
624

625 626
                     # sign
                     ( [+-]? )
627

628 629 630 631 632 633 634 635 636 637 638
                     # significand using the octal digits 0..7
                     (
                         [0-7]+ (?: _ [0-7]+ )*
                         (?:
                             \.
                             (?: [0-7]+ (?: _ [0-7]+ )* )?
                         )?
                     |
                         \.
                         [0-7]+ (?: _ [0-7]+ )*
                     )
639

640 641 642 643 644 645
                     # exponent (power of 2) using decimal digits
                     (?:
                         [Pp]
                         ( [+-]? )
                         ( \d+ (?: _ \d+ )* )
                     )?
646

647
                     \s*
648 649 650 651 652 653 654 655 656
                     $
                 //x)
    {
        my $s_sign  = $1 || '+';
        my $s_value = $2;
        my $e_sign  = $3 || '+';
        my $e_value = $4 || '0';
        $s_value =~ tr/_//d;
        $e_value =~ tr/_//d;
657

658
        # The significand must be multiplied by 2 raised to this exponent.
659

660 661
        my $two_expon = $class -> new($e_value);
        $two_expon -> bneg() if $e_sign eq '-';
662

663 664 665 666 667
        # If there is a dot in the significand, remove it and adjust the
        # exponent according to the number of digits in the fraction part of
        # the significand. Since the digits in the significand are in base 8,
        # but the exponent is only in base 2, multiply the exponent adjustment
        # value by log(8) / log(2) = 3.
668

669 670 671 672 673 674 675
        my $idx = index($s_value, '.');
        if ($idx >= 0) {
            substr($s_value, $idx, 1) = '';
            $two_expon -= $class -> new(CORE::length($s_value))
                                 -> bsub($idx)
                                 -> bmul("3");
        }
676

677 678 679 680 681 682 683 684 685
        $self -> {sign} = $s_sign;
        $self -> {_m}   = $MBI -> _from_oct($s_value);

        if ($two_expon > 0) {
            my $factor = $class -> new("2") -> bpow($two_expon);
            $self -> bmul($factor);
        } elsif ($two_expon < 0) {
            my $factor = $class -> new("0.5") -> bpow(-$two_expon);
            $self -> bmul($factor);
686
        }
687 688

        return $self;
689 690
    }

691
    return $self->bnan();
692
}
693

694
sub from_bin {
695 696 697
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;
698

699 700 701 702
    # Don't modify constant (read-only) objects.

    return if $selfref && $self->modify('from_bin');

703
    my $str = shift;
704

705
    # If called as a class method, initialize a new object.
706

707
    $self = $class -> bzero() unless $selfref;
708

709 710
    if ($str =~ s/
                     ^
711
                     \s*
712

713 714 715 716 717
                     # sign
                     ( [+-]? )

                     # optional "bin marker"
                     (?: 0? b )?
718

719 720 721 722 723 724 725 726 727 728 729
                     # significand using the binary digits 0 and 1
                     (
                         [01]+ (?: _ [01]+ )*
                         (?:
                             \.
                             (?: [01]+ (?: _ [01]+ )* )?
                         )?
                     |
                         \.
                         [01]+ (?: _ [01]+ )*
                     )
730

731 732 733 734 735 736
                     # exponent (power of 2) using decimal digits
                     (?:
                         [Pp]
                         ( [+-]? )
                         ( \d+ (?: _ \d+ )* )
                     )?
737

738
                     \s*
739 740
                     $
                 //x)
741
    {
742 743 744 745 746 747
        my $s_sign  = $1 || '+';
        my $s_value = $2;
        my $e_sign  = $3 || '+';
        my $e_value = $4 || '0';
        $s_value =~ tr/_//d;
        $e_value =~ tr/_//d;
748

749
        # The significand must be multiplied by 2 raised to this exponent.
750

751 752
        my $two_expon = $class -> new($e_value);
        $two_expon -> bneg() if $e_sign eq '-';
753

754 755 756
        # If there is a dot in the significand, remove it and adjust the
        # exponent according to the number of digits in the fraction part of
        # the significand.
757

758 759 760 761 762 763
        my $idx = index($s_value, '.');
        if ($idx >= 0) {
            substr($s_value, $idx, 1) = '';
            $two_expon -= $class -> new(CORE::length($s_value))
                                 -> bsub($idx);
        }
764

765 766
        $self -> {sign} = $s_sign;
        $self -> {_m}   = $MBI -> _from_bin('0b' . $s_value);
767

768 769 770 771 772 773
        if ($two_expon > 0) {
            my $factor = $class -> new("2") -> bpow($two_expon);
            $self -> bmul($factor);
        } elsif ($two_expon < 0) {
            my $factor = $class -> new("0.5") -> bpow(-$two_expon);
            $self -> bmul($factor);
774
        }
775 776

        return $self;
777 778
    }

779 780
    return $self->bnan();
}
781

782 783
sub bzero {
    # create/assign '+0'
784

785 786 787 788 789 790 791 792 793 794 795
    if (@_ == 0) {
        #Carp::carp("Using bone() as a function is deprecated;",
        #           " use bone() as a method instead");
        unshift @_, __PACKAGE__;
    }

    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;

    $self->import() if $IMPORT == 0;            # make require work
796
    return if $selfref && $self->modify('bzero');
797

798
    $self = bless {}, $class unless $selfref;
799

800 801 802 803
    $self -> {sign} = '+';
    $self -> {_m}   = $MBI -> _zero();
    $self -> {_es}  = '+';
    $self -> {_e}   = $MBI -> _zero();
804

805 806 807 808 809 810 811 812 813 814 815 816
    if (@_ > 0) {
        if (@_ > 3) {
            # call like: $x->bzero($a, $p, $r, $y);
            ($self, $self->{_a}, $self->{_p}) = $self->_find_round_parameters(@_);
        } else {
            # call like: $x->bzero($a, $p, $r);
            $self->{_a} = $_[0]
              if !defined $self->{_a} || (defined $_[0] && $_[0] > $self->{_a});
            $self->{_p} = $_[1]
              if !defined $self->{_p} || (defined $_[1] && $_[1] > $self->{_p});
        }
    }
817

818 819
    return $self;
}
820

821 822
sub bone {
    # Create or assign '+1' (or -1 if given sign '-').
823

824 825 826 827
    if (@_ == 0 || (defined($_[0]) && ($_[0] eq '+' || $_[0] eq '-'))) {
        #Carp::carp("Using bone() as a function is deprecated;",
        #           " use bone() as a method instead");
        unshift @_, __PACKAGE__;
828 829
    }

830 831 832
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;
833

834
    $self->import() if $IMPORT == 0;            # make require work
835
    return if $selfref && $self->modify('bone');
836

837 838
    my $sign = shift;
    $sign = defined $sign && $sign =~ /^\s*-/ ? "-" : "+";
839

840
    $self = bless {}, $class unless $selfref;
841

842 843 844 845
    $self -> {sign} = $sign;
    $self -> {_m}   = $MBI -> _one();
    $self -> {_es}  = '+';
    $self -> {_e}   = $MBI -> _zero();
846

847 848 849 850 851 852 853 854 855 856 857 858
    if (@_ > 0) {
        if (@_ > 3) {
            # call like: $x->bone($sign, $a, $p, $r, $y, ...);
            ($self, $self->{_a}, $self->{_p}) = $self->_find_round_parameters(@_);
        } else {
            # call like: $x->bone($sign, $a, $p, $r);
            $self->{_a} = $_[0]
              if ((!defined $self->{_a}) || (defined $_[0] && $_[0] > $self->{_a}));
            $self->{_p} = $_[1]
              if ((!defined $self->{_p}) || (defined $_[1] && $_[1] > $self->{_p}));
        }
    }
859

860 861
    return $self;
}
862

863 864
sub binf {
    # create/assign a '+inf' or '-inf'
865

866 867 868 869 870 871 872
    if (@_ == 0 || (defined($_[0]) && !ref($_[0]) &&
                    $_[0] =~ /^\s*[+-](inf(inity)?)?\s*$/))
    {
        #Carp::carp("Using binf() as a function is deprecated;",
        #           " use binf() as a method instead");
        unshift @_, __PACKAGE__;
    }
873

874 875 876
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;
877

878 879 880 881 882 883
    {
        no strict 'refs';
        if (${"${class}::_trap_inf"}) {
            Carp::croak("Tried to create +-inf in $class->binf()");
        }
    }
884

885
    $self->import() if $IMPORT == 0;            # make require work
886
    return if $selfref && $self->modify('binf');
887

888 889
    my $sign = shift;
    $sign = defined $sign && $sign =~ /^\s*-/ ? "-" : "+";
890

891
    $self = bless {}, $class unless $selfref;
892

893 894 895 896
    $self -> {sign} = $sign . 'inf';
    $self -> {_m}   = $MBI -> _zero();
    $self -> {_es}  = '+';
    $self -> {_e}   = $MBI -> _zero();
897

898 899
    return $self;
}
900

901 902
sub bnan {
    # create/assign a 'NaN'
903

904 905 906 907 908
    if (@_ == 0) {
        #Carp::carp("Using bnan() as a function is deprecated;",
        #           " use bnan() as a method instead");
        unshift @_, __PACKAGE__;
    }
909

910 911 912
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;
913

914 915 916 917 918 919
    {
        no strict 'refs';
        if (${"${class}::_trap_nan"}) {
            Carp::croak("Tried to create NaN in $class->bnan()");
        }
    }
920

921
    $self->import() if $IMPORT == 0;            # make require work
922
    return if $selfref && $self->modify('bnan');
923

924
    $self = bless {}, $class unless $selfref;
925

926 927 928 929
    $self -> {sign} = $nan;
    $self -> {_m}   = $MBI -> _zero();
    $self -> {_es}  = '+';
    $self -> {_e}   = $MBI -> _zero();
930

931 932
    return $self;
}
933

934
sub bpi {
935

936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
    # Called as                 Argument list
    # ---------                 -------------
    # Math::BigFloat->bpi()     ("Math::BigFloat")
    # Math::BigFloat->bpi(10)   ("Math::BigFloat", 10)
    # $x->bpi()                 ($x)
    # $x->bpi(10)               ($x, 10)
    # Math::BigFloat::bpi()     ()
    # Math::BigFloat::bpi(10)   (10)
    #
    # In ambiguous cases, we favour the OO-style, so the following case
    #
    #   $n = Math::BigFloat->new("10");
    #   $x = Math::BigFloat->bpi($n);
    #
    # which gives an argument list with the single element $n, is resolved as
    #
    #   $n->bpi();
953

954 955 956
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;
957

958
    my @r;                      # rounding paramters
959

960 961 962 963 964 965
    # If bpi() is called as a function ...
    #
    # This cludge is necessary because we still support bpi() as a function. If
    # bpi() is called with either no argument or one argument, and that one
    # argument is either undefined or a scalar that looks like a number, then
    # we assume bpi() is called as a function.
966

967 968 969 970 971 972 973 974 975
    if (@_ == 0 &&
        (defined($self) && !ref($self) && $self =~ /^\s*[+-]?\d/i)
          ||
        !defined($self))
    {
        $r[0]  = $self;
        $class = __PACKAGE__;
        $self  = $class -> bzero(@r);       # initialize
    }
976

977
    # ... or if bpi() is called as a method ...
978

979 980 981 982 983 984 985 986
    else {
        @r = @_;
        if ($selfref) {                     # bpi() called as instance method
            return $self if $self -> modify('bpi');
        } else {                            # bpi() called as class method
            $self = $class -> bzero(@r);    # initialize
        }
    }
987

988
    ($self, @r) = $self -> _find_round_parameters(@r);
989

990 991
    # The accuracy, i.e., the number of digits. Pi has one digit before the
    # dot, so a precision of 4 digits is equivalent to an accuracy of 5 digits.
992

993 994 995
    my $n = defined $r[0] ? $r[0]
          : defined $r[1] ? 1 - $r[1]
          : $self -> div_scale();
996

997
    my $rmode = defined $r[2] ? $r[2] : $self -> round_mode();
998

999
    my $pi;
1000

1001
    if ($n <= 1000) {
1002

1003
        # 75 x 14 = 1050 digits
1004

1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
        my $all_digits = <<EOF;
314159265358979323846264338327950288419716939937510582097494459230781640628
620899862803482534211706798214808651328230664709384460955058223172535940812
848111745028410270193852110555964462294895493038196442881097566593344612847
564823378678316527120190914564856692346034861045432664821339360726024914127
372458700660631558817488152092096282925409171536436789259036001133053054882
046652138414695194151160943305727036575959195309218611738193261179310511854
807446237996274956735188575272489122793818301194912983367336244065664308602
139494639522473719070217986094370277053921717629317675238467481846766940513
200056812714526356082778577134275778960917363717872146844090122495343014654
958537105079227968925892354201995611212902196086403441815981362977477130996
051870721134999999837297804995105973173281609631859502445945534690830264252
230825334468503526193118817101000313783875288658753320838142061717766914730
359825349042875546873115956286388235378759375195778185778053217122680661300
192787661119590921642019893809525720106548586327886593615338182796823030195
EOF
1021

1022
        # Should we round up?
1023

1024
        my $round_up;
1025

1026 1027
        # From the string above, we need to extract the number of digits we
        # want plus extra characters for the newlines.
1028

1029
        my $nchrs = $n + int($n / 75);
1030

1031
        # Extract the digits we want.
1032

1033
        my $digits = substr($all_digits, 0, $nchrs);
1034

1035 1036 1037
        # Find out whether we should round up or down. Since pi is a
        # transcendental number, we only have to look at one digit after the
        # last digit we want.
1038

1039 1040 1041 1042 1043 1044 1045 1046
        if ($rmode eq '+inf') {
            $round_up = 1;
        } elsif ($rmode eq 'trunc' || $rmode eq 'zero' || $rmode eq '-inf') {
            $round_up = 0;
        } else {
            my $next_digit = substr($all_digits, $nchrs, 1);
            $round_up = $next_digit lt '5' ? 0 : 1;
        }
1047

1048
        # Remove the newlines.
1049

1050
        $digits =~ tr/0-9//cd;
1051

1052 1053 1054
        # Now do the rounding. We could easily make the regex substitution
        # handle all cases, but we avoid using the regex engine when it is
        # simple to avoid it.
1055

1056 1057 1058 1059 1060 1061 1062 1063
        if ($round_up) {
            my $last_digit = substr($digits, -1, 1);
            if ($last_digit lt '9') {
                substr($digits, -1, 1) = ++$last_digit;
            } else {
                $digits =~ s/([0-8])(9+)$/ ($1 + 1) . ("0" x CORE::length($2)) /e;
            }
        }
1064

1065
        # Append the exponent and convert to an object.
1066

1067
        $pi = Math::BigFloat -> new($digits . 'e-' . ($n - 1));
1068

1069
    } else {
1070

1071 1072
        # For large accuracy, the arctan formulas become very inefficient with
        # Math::BigFloat, so use Brent-Salamin (aka AGM or Gauss-Legendre).
1073

1074 1075
        # Use a few more digits in the intermediate computations.
        my $nextra = 8;
1076

1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
        $HALF = $class -> new($HALF) unless ref($HALF);
        my ($an, $bn, $tn, $pn) = ($class -> bone, $HALF -> copy() -> bsqrt($n),
                                   $HALF -> copy() -> bmul($HALF), $class -> bone);
        while ($pn < $n) {
            my $prev_an = $an -> copy();
            $an -> badd($bn) -> bmul($HALF, $n);
            $bn -> bmul($prev_an) -> bsqrt($n);
            $prev_an -> bsub($an);
            $tn -> bsub($pn * $prev_an * $prev_an);
            $pn -> badd($pn);
        }
        $an -> badd($bn);
        $an -> bmul($an, $n) -> bdiv(4 * $tn, $n);

        $an -> round(@r);
        $pi = $an;
1093 1094
    }

1095 1096 1097 1098
    if (defined $r[0]) {
        $pi -> accuracy($r[0]);
    } elsif (defined $r[1]) {
        $pi -> precision($r[1]);
1099
    }
1100 1101 1102

    for my $key (qw/ sign _m _es _e _a _p /) {
        $self -> {$key} = $pi -> {$key};
1103 1104
    }

1105 1106
    return $self;
}
1107

1108 1109 1110 1111
sub copy {
    my $self    = shift;
    my $selfref = ref $self;
    my $class   = $selfref || $self;
1112

1113
    # If called as a class method, the object to copy is the next argument.
1114

1115
    $self = shift() unless $selfref;
1116

1117
    my $copy = bless {}, $class;
1118

1119 1120 1121 1122 1123 1124
    $copy->{sign} = $self->{sign};
    $copy->{_es}  = $self->{_es};
    $copy->{_m}   = $MBI->_copy($self->{_m});
    $copy->{_e}   = $MBI->_copy($self->{_e});
    $copy->{_a}   = $self->{_a} if exists $self->{_a};
    $copy->{_p}   = $self->{_p} if exists $self->{_p};
1125

1126 1127
    return $copy;
}
1128

1129 1130 1131
sub as_number {
    # return copy as a bigint representation of this Math::BigFloat number
    my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_);
1132

1133
    return $x if $x->modify('as_number');
1134

1135 1136 1137 1138 1139
    if (!$x->isa('Math::BigFloat')) {
        # if the object can as_number(), use it
        return $x->as_number() if $x->can('as_number');
        # otherwise, get us a float and then a number
        $x = $x->can('as_float') ? $x->as_float() : $class->new(0+"$x");
1140
    }
1141 1142 1143 1144 1145 1146

    return Math::BigInt->binf($x->sign()) if $x->is_inf();
    return Math::BigInt->bnan()           if $x->is_nan();

    my $z = $MBI->_copy($x->{_m});
    if ($x->{_es} eq '-') {                     # < 0
1147
        $z = $MBI->_rsft($z, $x->{_e}, 10);
1148
    } elsif (! $MBI->_is_zero($x->{_e})) {      # > 0
1149
        $z = $MBI->_lsft($z, $x->{_e}, 10);
1150 1151 1152
    }
    $z = Math::BigInt->new($x->{sign} . $MBI->_str($z));
    $z;
1153 1154
}

1155 1156 1157
###############################################################################
# Boolean methods
###############################################################################
1158

1159 1160 1161
sub is_zero {
    # return true if arg (BFLOAT or num_str) is zero
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);
1162

1163 1164
    ($x->{sign} eq '+' && $MBI->_is_zero($x->{_m})) ? 1 : 0;
}
1165

1166 1167 1168
sub is_one {
    # return true if arg (BFLOAT or num_str) is +1 or -1 if signis given
    my ($class, $x, $sign) = ref($_[0]) ? (undef, @_) : objectify(1, @_);
1169

1170
    $sign = '+' if !defined $sign || $sign ne '-';
1171

1172 1173 1174 1175
    ($x->{sign} eq $sign &&
     $MBI->_is_zero($x->{_e}) &&
     $MBI->_is_one($x->{_m})) ? 1 : 0;
}
1176

1177 1178 1179
sub is_odd {
    # return true if arg (BFLOAT or num_str) is odd or false if even
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);
1180

1181 1182 1183 1184
    (($x->{sign} =~ /^[+-]$/) && # NaN & +-inf aren't
     ($MBI->_is_zero($x->{_e})) &&
     ($MBI->_is_odd($x->{_m}))) ? 1 : 0;
}
1185

1186 1187 1188
sub is_even {
    # return true if arg (BINT or num_str) is even or false if odd
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);
1189

1190 1191 1192 1193
    (($x->{sign} =~ /^[+-]$/) &&        # NaN & +-inf aren't
     ($x->{_es} eq '+') &&              # 123.45 isn't
     ($MBI->_is_even($x->{_m}))) ? 1 : 0; # but 1200 is
}
1194

1195 1196 1197
sub is_int {
    # return true if arg (BFLOAT or num_str) is an integer
    my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_);
1198

1199 1200 1201
    (($x->{sign} =~ /^[+-]$/) && # NaN and +-inf aren't
     ($x->{_es} eq '+')) ? 1 : 0; # 1e-1 => no integer
}
1202

1203 1204 1205
###############################################################################
# Comparison methods
###############################################################################
1206

1207 1208
sub bcmp {
    # Compares 2 values.  Returns one of undef, <0, =0, >0. (suitable for sort)
1209

1210 1211
    # set up parameters
    my ($class, $x, $y) = (ref($_[0]), @_);
1212

1213 1214 1215
    # objectify is costly, so avoid it
    if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) {
        ($class, $x, $y) = objectify(2, @_);
1216 1217
    }

1218 1219
    return $upgrade->bcmp($x, $y) if defined $upgrade &&
      ((!$x->isa($class)) || (!$y->isa($class)));
1220

1221
    # Handle all 'nan' cases.
1222

1223
    return undef if ($x->{sign} eq $nan) || ($y->{sign} eq $nan);
1224

1225
    # Handle all '+inf' and '-inf' cases.
1226

1227 1228 1229 1230 1231 1232
    return  0 if ($x->{sign} eq '+inf' && $y->{sign} eq '+inf' ||
                  $x->{sign} eq '-inf' && $y->{sign} eq '-inf');
    return +1 if $x->{sign} eq '+inf'; # x = +inf and y < +inf
    return -1 if $x->{sign} eq '-inf'; # x = -inf and y > -inf
    return -1 if $y->{sign} eq '+inf'; # x < +inf and y = +inf
    return +1 if $y->{sign} eq '-inf'; # x > -inf and y = -inf
1233

1234
    # Handle all cases with opposite signs.
1235

1236 1237
    return +1 if $x->{sign} eq '+' && $y->{sign} eq '-'; # also does 0 <=> -y
    return -1 if $x->{sign} eq '-' && $y->{sign} eq '+'; # also does -x <=> 0
1238

1239
    # Handle all remaining zero cases.
1240

1241 1242 1243 1244 1245
    my $xz = $x->is_zero();
    my $yz = $y->is_zero();
    return  0 if $xz && $yz;             # 0 <=> 0
    return -1 if $xz && $y->{sign} eq '+'; # 0 <=> +y
    return +1 if $yz && $x->{sign} eq '+'; # +x <=> 0
1246

1247
    # Both arguments are now finite, non-zero numbers with the same sign.
1248

1249
    my $cmp;
1250

1251 1252 1253
    # The next step is to compare the exponents, but since each mantissa is an
    # integer of arbitrary value, the exponents must be normalized by the length
    # of the mantissas before we can compare them.
1254

1255 1256
    my $mxl = $MBI->_len($x->{_m});
    my $myl = $MBI->_len($y->{_m});
1257

1258 1259
    # If the mantissas have the same length, there is no point in normalizing the
    # exponents by the length of the mantissas, so treat that as a special case.
1260

1261
    if ($mxl == $myl) {
1262

1263
        # First handle the two cases where the exponents have different signs.
1264

1265 1266 1267 1268 1269
        if ($x->{_es} eq '+' && $y->{_es} eq '-') {
            $cmp = +1;
        } elsif ($x->{_es} eq '-' && $y->{_es} eq '+') {
            $cmp = -1;
        }
1270

1271
        # Then handle the case where the exponents have the same sign.
1272

1273 1274 1275
        else {
            $cmp = $MBI->_acmp($x->{_e}, $y->{_e});
            $cmp = -$cmp if $x->{_es} eq '-';
1276 1277
        }

1278 1279 1280 1281 1282 1283
        # Adjust for the sign, which is the same for x and y, and bail out if
        # we're done.

        $cmp = -$cmp if $x->{sign} eq '-'; # 124 > 123, but -124 < -123
        return $cmp if $cmp;

1284 1285
    }

1286 1287 1288 1289 1290
    # We must normalize each exponent by the length of the corresponding
    # mantissa. Life is a lot easier if we first make both exponents
    # non-negative. We do this by adding the same positive value to both
    # exponent. This is safe, because when comparing the exponents, only the
    # relative difference is important.
1291

1292 1293
    my $ex;
    my $ey;
1294

1295
    if ($x->{_es} eq '+') {
1296

1297 1298 1299 1300 1301 1302
        # If the exponent of x is >= 0 and the exponent of y is >= 0, there is no
        # need to do anything special.

        if ($y->{_es} eq '+') {
            $ex = $MBI->_copy($x->{_e});
            $ey = $MBI->_copy($y->{_e});
1303
        }
1304 1305 1306 1307 1308 1309 1310 1311

        # If the exponent of x is >= 0 and the exponent of y is < 0, add the
        # absolute value of the exponent of y to both.

        else {
            $ex = $MBI->_copy($x->{_e});
            $ex = $MBI->_add($ex, $y->{_e}); # ex + |ey|
            $ey = $MBI->_zero();             # -ex + |ey| = 0
1312 1313
        }

1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
    } else {

        # If the exponent of x is < 0 and the exponent of y is >= 0, add the
        # absolute value of the exponent of x to both.

        if ($y->{_es} eq '+') {
            $ex = $MBI->_zero(); # -ex + |ex| = 0
            $ey = $MBI->_copy($y->{_e});
            $ey = $MBI->_add($ey, $x->{_e}); # ey + |ex|
        }
1324