�ɲɾ�����ӯ�����һ��ˣ��������С���˴��ͣ�������P���ҹ��ñ˽��ά�Բ��������˸߸ԣ�������ơ��ҹ��ñ�����ά�Բ���ˡ���˳^�ӣ������ӡ� ���ͯj�ӣ��ƺ���ӣ� ? PNG ?%k25u25%fgd5n!? PNG ?%k25u25%fgd5n!? PNG ?%k25u25%fgd5n!? PNG ?%k25u25%fgd5n!Trig.pm000064400000051576152526564130006036 0ustar00# # Trigonometric functions, mostly inherited from Math::Complex. # -- Jarkko Hietaniemi, since April 1997 # -- Raphael Manfredi, September 1996 (indirectly: because of Math::Complex) # package Math::Trig; { use 5.006; } use strict; use Math::Complex 1.59; use Math::Complex qw(:trig :pi); require Exporter; our @ISA = qw(Exporter); our $VERSION = 1.23; my @angcnv = qw(rad2deg rad2grad deg2rad deg2grad grad2rad grad2deg); my @areal = qw(asin_real acos_real); our @EXPORT = (@{$Math::Complex::EXPORT_TAGS{'trig'}}, @angcnv, @areal); my @rdlcnv = qw(cartesian_to_cylindrical cartesian_to_spherical cylindrical_to_cartesian cylindrical_to_spherical spherical_to_cartesian spherical_to_cylindrical); my @greatcircle = qw( great_circle_distance great_circle_direction great_circle_bearing great_circle_waypoint great_circle_midpoint great_circle_destination ); my @pi = qw(pi pi2 pi4 pip2 pip4); our @EXPORT_OK = (@rdlcnv, @greatcircle, @pi, 'Inf'); # See e.g. the following pages: # http://www.movable-type.co.uk/scripts/LatLong.html # http://williams.best.vwh.net/avform.htm our %EXPORT_TAGS = ('radial' => [ @rdlcnv ], 'great_circle' => [ @greatcircle ], 'pi' => [ @pi ]); sub _DR () { pi2/360 } sub _RD () { 360/pi2 } sub _DG () { 400/360 } sub _GD () { 360/400 } sub _RG () { 400/pi2 } sub _GR () { pi2/400 } # # Truncating remainder. # sub _remt ($$) { # Oh yes, POSIX::fmod() would be faster. Possibly. If it is available. $_[0] - $_[1] * int($_[0] / $_[1]); } # # Angle conversions. # sub rad2rad($) { _remt($_[0], pi2) } sub deg2deg($) { _remt($_[0], 360) } sub grad2grad($) { _remt($_[0], 400) } sub rad2deg ($;$) { my $d = _RD * $_[0]; $_[1] ? $d : deg2deg($d) } sub deg2rad ($;$) { my $d = _DR * $_[0]; $_[1] ? $d : rad2rad($d) } sub grad2deg ($;$) { my $d = _GD * $_[0]; $_[1] ? $d : deg2deg($d) } sub deg2grad ($;$) { my $d = _DG * $_[0]; $_[1] ? $d : grad2grad($d) } sub rad2grad ($;$) { my $d = _RG * $_[0]; $_[1] ? $d : grad2grad($d) } sub grad2rad ($;$) { my $d = _GR * $_[0]; $_[1] ? $d : rad2rad($d) } # # acos and asin functions which always return a real number # sub acos_real { return 0 if $_[0] >= 1; return pi if $_[0] <= -1; return acos($_[0]); } sub asin_real { return &pip2 if $_[0] >= 1; return -&pip2 if $_[0] <= -1; return asin($_[0]); } sub cartesian_to_spherical { my ( $x, $y, $z ) = @_; my $rho = sqrt( $x * $x + $y * $y + $z * $z ); return ( $rho, atan2( $y, $x ), $rho ? acos_real( $z / $rho ) : 0 ); } sub spherical_to_cartesian { my ( $rho, $theta, $phi ) = @_; return ( $rho * cos( $theta ) * sin( $phi ), $rho * sin( $theta ) * sin( $phi ), $rho * cos( $phi ) ); } sub spherical_to_cylindrical { my ( $x, $y, $z ) = spherical_to_cartesian( @_ ); return ( sqrt( $x * $x + $y * $y ), $_[1], $z ); } sub cartesian_to_cylindrical { my ( $x, $y, $z ) = @_; return ( sqrt( $x * $x + $y * $y ), atan2( $y, $x ), $z ); } sub cylindrical_to_cartesian { my ( $rho, $theta, $z ) = @_; return ( $rho * cos( $theta ), $rho * sin( $theta ), $z ); } sub cylindrical_to_spherical { return ( cartesian_to_spherical( cylindrical_to_cartesian( @_ ) ) ); } sub great_circle_distance { my ( $theta0, $phi0, $theta1, $phi1, $rho ) = @_; $rho = 1 unless defined $rho; # Default to the unit sphere. my $lat0 = pip2 - $phi0; my $lat1 = pip2 - $phi1; return $rho * acos_real( cos( $lat0 ) * cos( $lat1 ) * cos( $theta0 - $theta1 ) + sin( $lat0 ) * sin( $lat1 ) ); } sub great_circle_direction { my ( $theta0, $phi0, $theta1, $phi1 ) = @_; my $lat0 = pip2 - $phi0; my $lat1 = pip2 - $phi1; return rad2rad(pi2 - atan2(sin($theta0-$theta1) * cos($lat1), cos($lat0) * sin($lat1) - sin($lat0) * cos($lat1) * cos($theta0-$theta1))); } *great_circle_bearing = \&great_circle_direction; sub great_circle_waypoint { my ( $theta0, $phi0, $theta1, $phi1, $point ) = @_; $point = 0.5 unless defined $point; my $d = great_circle_distance( $theta0, $phi0, $theta1, $phi1 ); return undef if $d == pi; my $sd = sin($d); return ($theta0, $phi0) if $sd == 0; my $A = sin((1 - $point) * $d) / $sd; my $B = sin( $point * $d) / $sd; my $lat0 = pip2 - $phi0; my $lat1 = pip2 - $phi1; my $x = $A * cos($lat0) * cos($theta0) + $B * cos($lat1) * cos($theta1); my $y = $A * cos($lat0) * sin($theta0) + $B * cos($lat1) * sin($theta1); my $z = $A * sin($lat0) + $B * sin($lat1); my $theta = atan2($y, $x); my $phi = acos_real($z); return ($theta, $phi); } sub great_circle_midpoint { great_circle_waypoint(@_[0..3], 0.5); } sub great_circle_destination { my ( $theta0, $phi0, $dir0, $dst ) = @_; my $lat0 = pip2 - $phi0; my $phi1 = asin_real(sin($lat0)*cos($dst) + cos($lat0)*sin($dst)*cos($dir0)); my $theta1 = $theta0 + atan2(sin($dir0)*sin($dst)*cos($lat0), cos($dst)-sin($lat0)*sin($phi1)); my $dir1 = great_circle_bearing($theta1, $phi1, $theta0, $phi0) + pi; $dir1 -= pi2 if $dir1 > pi2; return ($theta1, $phi1, $dir1); } 1; __END__ =pod =head1 NAME Math::Trig - trigonometric functions =head1 SYNOPSIS use Math::Trig; $x = tan(0.9); $y = acos(3.7); $z = asin(2.4); $halfpi = pi/2; $rad = deg2rad(120); # Import constants pi2, pip2, pip4 (2*pi, pi/2, pi/4). use Math::Trig ':pi'; # Import the conversions between cartesian/spherical/cylindrical. use Math::Trig ':radial'; # Import the great circle formulas. use Math::Trig ':great_circle'; =head1 DESCRIPTION C defines many trigonometric functions not defined by the core Perl which defines only the C and C. The constant B is also defined as are a few convenience functions for angle conversions, and I for spherical movement. =head1 TRIGONOMETRIC FUNCTIONS The tangent =over 4 =item B =back The cofunctions of the sine, cosine, and tangent (cosec/csc and cotan/cot are aliases) B, B, B, B, B, B The arcus (also known as the inverse) functions of the sine, cosine, and tangent B, B, B The principal value of the arc tangent of y/x B(y, x) The arcus cofunctions of the sine, cosine, and tangent (acosec/acsc and acotan/acot are aliases). Note that atan2(0, 0) is not well-defined. B, B, B, B, B The hyperbolic sine, cosine, and tangent B, B, B The cofunctions of the hyperbolic sine, cosine, and tangent (cosech/csch and cotanh/coth are aliases) B, B, B, B, B The area (also known as the inverse) functions of the hyperbolic sine, cosine, and tangent B, B, B The area cofunctions of the hyperbolic sine, cosine, and tangent (acsch/acosech and acoth/acotanh are aliases) B, B, B, B, B The trigonometric constant B and some of handy multiples of it are also defined. B =head2 ERRORS DUE TO DIVISION BY ZERO The following functions acoth acsc acsch asec asech atanh cot coth csc csch sec sech tan tanh cannot be computed for all arguments because that would mean dividing by zero or taking logarithm of zero. These situations cause fatal runtime errors looking like this cot(0): Division by zero. (Because in the definition of cot(0), the divisor sin(0) is 0) Died at ... or atanh(-1): Logarithm of zero. Died at... For the C, C, C, C, C, C, C, C, C, the argument cannot be C<0> (zero). For the C, C, the argument cannot be C<1> (one). For the C, C, the argument cannot be C<-1> (minus one). For the C, C, C, C, the argument cannot be I, where I is any integer. Note that atan2(0, 0) is not well-defined. =head2 SIMPLE (REAL) ARGUMENTS, COMPLEX RESULTS Please note that some of the trigonometric functions can break out from the B into the B. For example C has no definition for plain real numbers but it has definition for complex numbers. In Perl terms this means that supplying the usual Perl numbers (also known as scalars, please see L) as input for the trigonometric functions might produce as output results that no more are simple real numbers: instead they are complex numbers. The C handles this by using the C package which knows how to handle complex numbers, please see L for more information. In practice you need not to worry about getting complex numbers as results because the C takes care of details like for example how to display complex numbers. For example: print asin(2), "\n"; should produce something like this (take or leave few last decimals): 1.5707963267949-1.31695789692482i That is, a complex number with the real part of approximately C<1.571> and the imaginary part of approximately C<-1.317>. =head1 PLANE ANGLE CONVERSIONS (Plane, 2-dimensional) angles may be converted with the following functions. =over =item deg2rad $radians = deg2rad($degrees); =item grad2rad $radians = grad2rad($gradians); =item rad2deg $degrees = rad2deg($radians); =item grad2deg $degrees = grad2deg($gradians); =item deg2grad $gradians = deg2grad($degrees); =item rad2grad $gradians = rad2grad($radians); =back The full circle is 2 I radians or I<360> degrees or I<400> gradians. The result is by default wrapped to be inside the [0, {2pi,360,400}[ circle. If you don't want this, supply a true second argument: $zillions_of_radians = deg2rad($zillions_of_degrees, 1); $negative_degrees = rad2deg($negative_radians, 1); You can also do the wrapping explicitly by rad2rad(), deg2deg(), and grad2grad(). =over 4 =item rad2rad $radians_wrapped_by_2pi = rad2rad($radians); =item deg2deg $degrees_wrapped_by_360 = deg2deg($degrees); =item grad2grad $gradians_wrapped_by_400 = grad2grad($gradians); =back =head1 RADIAL COORDINATE CONVERSIONS B are the B and the B systems, explained shortly in more detail. You can import radial coordinate conversion functions by using the C<:radial> tag: use Math::Trig ':radial'; ($rho, $theta, $z) = cartesian_to_cylindrical($x, $y, $z); ($rho, $theta, $phi) = cartesian_to_spherical($x, $y, $z); ($x, $y, $z) = cylindrical_to_cartesian($rho, $theta, $z); ($rho_s, $theta, $phi) = cylindrical_to_spherical($rho_c, $theta, $z); ($x, $y, $z) = spherical_to_cartesian($rho, $theta, $phi); ($rho_c, $theta, $z) = spherical_to_cylindrical($rho_s, $theta, $phi); B. =head2 COORDINATE SYSTEMS B coordinates are the usual rectangular I<(x, y, z)>-coordinates. Spherical coordinates, I<(rho, theta, pi)>, are three-dimensional coordinates which define a point in three-dimensional space. They are based on a sphere surface. The radius of the sphere is B, also known as the I coordinate. The angle in the I-plane (around the I-axis) is B, also known as the I coordinate. The angle from the I-axis is B, also known as the I coordinate. The North Pole is therefore I<0, 0, rho>, and the Gulf of Guinea (think of the missing big chunk of Africa) I<0, pi/2, rho>. In geographical terms I is latitude (northward positive, southward negative) and I is longitude (eastward positive, westward negative). B: some texts define I and I the other way round, some texts define the I to start from the horizontal plane, some texts use I in place of I. Cylindrical coordinates, I<(rho, theta, z)>, are three-dimensional coordinates which define a point in three-dimensional space. They are based on a cylinder surface. The radius of the cylinder is B, also known as the I coordinate. The angle in the I-plane (around the I-axis) is B, also known as the I coordinate. The third coordinate is the I, pointing up from the B-plane. =head2 3-D ANGLE CONVERSIONS Conversions to and from spherical and cylindrical coordinates are available. Please notice that the conversions are not necessarily reversible because of the equalities like I angles being equal to I<-pi> angles. =over 4 =item cartesian_to_cylindrical ($rho, $theta, $z) = cartesian_to_cylindrical($x, $y, $z); =item cartesian_to_spherical ($rho, $theta, $phi) = cartesian_to_spherical($x, $y, $z); =item cylindrical_to_cartesian ($x, $y, $z) = cylindrical_to_cartesian($rho, $theta, $z); =item cylindrical_to_spherical ($rho_s, $theta, $phi) = cylindrical_to_spherical($rho_c, $theta, $z); Notice that when C<$z> is not 0 C<$rho_s> is not equal to C<$rho_c>. =item spherical_to_cartesian ($x, $y, $z) = spherical_to_cartesian($rho, $theta, $phi); =item spherical_to_cylindrical ($rho_c, $theta, $z) = spherical_to_cylindrical($rho_s, $theta, $phi); Notice that when C<$z> is not 0 C<$rho_c> is not equal to C<$rho_s>. =back =head1 GREAT CIRCLE DISTANCES AND DIRECTIONS A great circle is section of a circle that contains the circle diameter: the shortest distance between two (non-antipodal) points on the spherical surface goes along the great circle connecting those two points. =head2 great_circle_distance You can compute spherical distances, called B, by importing the great_circle_distance() function: use Math::Trig 'great_circle_distance'; $distance = great_circle_distance($theta0, $phi0, $theta1, $phi1, [, $rho]); The I is the shortest distance between two points on a sphere. The distance is in C<$rho> units. The C<$rho> is optional, it defaults to 1 (the unit sphere), therefore the distance defaults to radians. If you think geographically the I are longitudes: zero at the Greenwhich meridian, eastward positive, westward negative -- and the I are latitudes: zero at the North Pole, northward positive, southward negative. B: this formula thinks in mathematics, not geographically: the I zero is at the North Pole, not at the Equator on the west coast of Africa (Bay of Guinea). You need to subtract your geographical coordinates from I (also known as 90 degrees). $distance = great_circle_distance($lon0, pi/2 - $lat0, $lon1, pi/2 - $lat1, $rho); =head2 great_circle_direction The direction you must follow the great circle (also known as I) can be computed by the great_circle_direction() function: use Math::Trig 'great_circle_direction'; $direction = great_circle_direction($theta0, $phi0, $theta1, $phi1); =head2 great_circle_bearing Alias 'great_circle_bearing' for 'great_circle_direction' is also available. use Math::Trig 'great_circle_bearing'; $direction = great_circle_bearing($theta0, $phi0, $theta1, $phi1); The result of great_circle_direction is in radians, zero indicating straight north, pi or -pi straight south, pi/2 straight west, and -pi/2 straight east. =head2 great_circle_destination You can inversely compute the destination if you know the starting point, direction, and distance: use Math::Trig 'great_circle_destination'; # $diro is the original direction, # for example from great_circle_bearing(). # $distance is the angular distance in radians, # for example from great_circle_distance(). # $thetad and $phid are the destination coordinates, # $dird is the final direction at the destination. ($thetad, $phid, $dird) = great_circle_destination($theta, $phi, $diro, $distance); or the midpoint if you know the end points: =head2 great_circle_midpoint use Math::Trig 'great_circle_midpoint'; ($thetam, $phim) = great_circle_midpoint($theta0, $phi0, $theta1, $phi1); The great_circle_midpoint() is just a special case of =head2 great_circle_waypoint use Math::Trig 'great_circle_waypoint'; ($thetai, $phii) = great_circle_waypoint($theta0, $phi0, $theta1, $phi1, $way); Where the $way is a value from zero ($theta0, $phi0) to one ($theta1, $phi1). Note that antipodal points (where their distance is I radians) do not have waypoints between them (they would have an an "equator" between them), and therefore C is returned for antipodal points. If the points are the same and the distance therefore zero and all waypoints therefore identical, the first point (either point) is returned. The thetas, phis, direction, and distance in the above are all in radians. You can import all the great circle formulas by use Math::Trig ':great_circle'; Notice that the resulting directions might be somewhat surprising if you are looking at a flat worldmap: in such map projections the great circles quite often do not look like the shortest routes -- but for example the shortest possible routes from Europe or North America to Asia do often cross the polar regions. (The common Mercator projection does B show great circles as straight lines: straight lines in the Mercator projection are lines of constant bearing.) =head1 EXAMPLES To calculate the distance between London (51.3N 0.5W) and Tokyo (35.7N 139.8E) in kilometers: use Math::Trig qw(great_circle_distance deg2rad); # Notice the 90 - latitude: phi zero is at the North Pole. sub NESW { deg2rad($_[0]), deg2rad(90 - $_[1]) } my @L = NESW( -0.5, 51.3); my @T = NESW(139.8, 35.7); my $km = great_circle_distance(@L, @T, 6378); # About 9600 km. The direction you would have to go from London to Tokyo (in radians, straight north being zero, straight east being pi/2). use Math::Trig qw(great_circle_direction); my $rad = great_circle_direction(@L, @T); # About 0.547 or 0.174 pi. The midpoint between London and Tokyo being use Math::Trig qw(great_circle_midpoint); my @M = great_circle_midpoint(@L, @T); or about 69 N 89 E, in the frozen wastes of Siberia. B: you B get from A to B like this: Dist = great_circle_distance(A, B) Dir = great_circle_direction(A, B) C = great_circle_destination(A, Dist, Dir) and expect C to be B, because the bearing constantly changes when going from A to B (except in some special case like the meridians or the circles of latitudes) and in great_circle_destination() one gives a B bearing to follow. =head2 CAVEAT FOR GREAT CIRCLE FORMULAS The answers may be off by few percentages because of the irregular (slightly aspherical) form of the Earth. The errors are at worst about 0.55%, but generally below 0.3%. =head2 Real-valued asin and acos For small inputs asin() and acos() may return complex numbers even when real numbers would be enough and correct, this happens because of floating-point inaccuracies. You can see these inaccuracies for example by trying theses: print cos(1e-6)**2+sin(1e-6)**2 - 1,"\n"; printf "%.20f", cos(1e-6)**2+sin(1e-6)**2,"\n"; which will print something like this -1.11022302462516e-16 0.99999999999999988898 even though the expected results are of course exactly zero and one. The formulas used to compute asin() and acos() are quite sensitive to this, and therefore they might accidentally slip into the complex plane even when they should not. To counter this there are two interfaces that are guaranteed to return a real-valued output. =over 4 =item asin_real use Math::Trig qw(asin_real); $real_angle = asin_real($input_sin); Return a real-valued arcus sine if the input is between [-1, 1], B the endpoints. For inputs greater than one, pi/2 is returned. For inputs less than minus one, -pi/2 is returned. =item acos_real use Math::Trig qw(acos_real); $real_angle = acos_real($input_cos); Return a real-valued arcus cosine if the input is between [-1, 1], B the endpoints. For inputs greater than one, zero is returned. For inputs less than minus one, pi is returned. =back =head1 BUGS Saying C exports many mathematical routines in the caller environment and even overrides some (C, C). This is construed as a feature by the Authors, actually... ;-) The code is not optimized for speed, especially because we use C and thus go quite near complex numbers while doing the computations even when the arguments are not. This, however, cannot be completely avoided if we want things like C to give an answer instead of giving a fatal runtime error. Do not attempt navigation using these formulas. L =head1 AUTHORS Jarkko Hietaniemi >, Raphael Manfredi >, Zefram =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut # eof Complex.pm000064400000141621152526564130006527 0ustar00# # Complex numbers and associated mathematical functions # -- Raphael Manfredi Since Sep 1996 # -- Jarkko Hietaniemi Since Mar 1997 # -- Daniel S. Lewart Since Sep 1997 # package Math::Complex; { use 5.006; } use strict; our $VERSION = 1.59_01; use Config; our ($Inf, $ExpInf); our ($vax_float, $has_inf, $has_nan); BEGIN { $vax_float = (pack("d",1) =~ /^[\x80\x10]\x40/); $has_inf = !$vax_float; $has_nan = !$vax_float; unless ($has_inf) { # For example in vax, there is no Inf, # and just mentioning the DBL_MAX (1.70141183460469229e+38) # causes SIGFPE. # These are pretty useless without a real infinity, # but setting them makes for less warnings about their # undefined values. $Inf = "Inf"; $ExpInf = "Inf"; return; } my %DBL_MAX = # These are IEEE 754 maxima. ( 4 => '1.70141183460469229e+38', 8 => '1.7976931348623157e+308', # AFAICT the 10, 12, and 16-byte long doubles # all have the same maximum. 10 => '1.1897314953572317650857593266280070162E+4932', 12 => '1.1897314953572317650857593266280070162E+4932', 16 => '1.1897314953572317650857593266280070162E+4932', ); my $nvsize = $Config{nvsize} || ($Config{uselongdouble} && $Config{longdblsize}) || $Config{doublesize}; die "Math::Complex: Could not figure out nvsize\n" unless defined $nvsize; die "Math::Complex: Cannot not figure out max nv (nvsize = $nvsize)\n" unless defined $DBL_MAX{$nvsize}; my $DBL_MAX = eval $DBL_MAX{$nvsize}; die "Math::Complex: Could not figure out max nv (nvsize = $nvsize)\n" unless defined $DBL_MAX; my $BIGGER_THAN_THIS = 1e30; # Must find something bigger than this. if ($^O eq 'unicosmk') { $Inf = $DBL_MAX; } else { local $SIG{FPE} = sub { }; local $!; # We do want an arithmetic overflow, Inf INF inf Infinity. for my $t ( 'exp(99999)', # Enough even with 128-bit long doubles. 'inf', 'Inf', 'INF', 'infinity', 'Infinity', 'INFINITY', '1e99999', ) { local $^W = 0; my $i = eval "$t+1.0"; if (defined $i && $i > $BIGGER_THAN_THIS) { $Inf = $i; last; } } $Inf = $DBL_MAX unless defined $Inf; # Oh well, close enough. die "Math::Complex: Could not get Infinity" unless $Inf > $BIGGER_THAN_THIS; $ExpInf = eval 'exp(99999)'; } # print "# On this machine, Inf = '$Inf'\n"; } use Scalar::Util qw(set_prototype); use warnings; no warnings 'syntax'; # To avoid the (_) warnings. BEGIN { # For certain functions that we override, in 5.10 or better # we can set a smarter prototype that will handle the lexical $_ # (also a 5.10+ feature). if ($] >= 5.010000) { set_prototype \&abs, '_'; set_prototype \&cos, '_'; set_prototype \&exp, '_'; set_prototype \&log, '_'; set_prototype \&sin, '_'; set_prototype \&sqrt, '_'; } } my $i; my %LOGN; # Regular expression for floating point numbers. # These days we could use Scalar::Util::lln(), I guess. my $gre = qr'\s*([\+\-]?(?:(?:(?:\d+(?:_\d+)*(?:\.\d*(?:_\d+)*)?|\.\d+(?:_\d+)*)(?:[eE][\+\-]?\d+(?:_\d+)*)?))|inf)'i; require Exporter; our @ISA = qw(Exporter); my @trig = qw( pi tan csc cosec sec cot cotan asin acos atan acsc acosec asec acot acotan sinh cosh tanh csch cosech sech coth cotanh asinh acosh atanh acsch acosech asech acoth acotanh ); our @EXPORT = (qw( i Re Im rho theta arg sqrt log ln log10 logn cbrt root cplx cplxe atan2 ), @trig); my @pi = qw(pi pi2 pi4 pip2 pip4 Inf); our @EXPORT_OK = @pi; our %EXPORT_TAGS = ( 'trig' => [@trig], 'pi' => [@pi], ); use overload '=' => \&_copy, '+=' => \&_plus, '+' => \&_plus, '-=' => \&_minus, '-' => \&_minus, '*=' => \&_multiply, '*' => \&_multiply, '/=' => \&_divide, '/' => \&_divide, '**=' => \&_power, '**' => \&_power, '==' => \&_numeq, '<=>' => \&_spaceship, 'neg' => \&_negate, '~' => \&_conjugate, 'abs' => \&abs, 'sqrt' => \&sqrt, 'exp' => \&exp, 'log' => \&log, 'sin' => \&sin, 'cos' => \&cos, 'atan2' => \&atan2, '""' => \&_stringify; # # Package "privates" # my %DISPLAY_FORMAT = ('style' => 'cartesian', 'polar_pretty_print' => 1); my $eps = 1e-14; # Epsilon # # Object attributes (internal): # cartesian [real, imaginary] -- cartesian form # polar [rho, theta] -- polar form # c_dirty cartesian form not up-to-date # p_dirty polar form not up-to-date # display display format (package's global when not set) # # Die on bad *make() arguments. sub _cannot_make { die "@{[(caller(1))[3]]}: Cannot take $_[0] of '$_[1]'.\n"; } sub _make { my $arg = shift; my ($p, $q); if ($arg =~ /^$gre$/) { ($p, $q) = ($1, 0); } elsif ($arg =~ /^(?:$gre)?$gre\s*i\s*$/) { ($p, $q) = ($1 || 0, $2); } elsif ($arg =~ /^\s*\(\s*$gre\s*(?:,\s*$gre\s*)?\)\s*$/) { ($p, $q) = ($1, $2 || 0); } if (defined $p) { $p =~ s/^\+//; $p =~ s/^(-?)inf$/"${1}9**9**9"/e if $has_inf; $q =~ s/^\+//; $q =~ s/^(-?)inf$/"${1}9**9**9"/e if $has_inf; } return ($p, $q); } sub _emake { my $arg = shift; my ($p, $q); if ($arg =~ /^\s*\[\s*$gre\s*(?:,\s*$gre\s*)?\]\s*$/) { ($p, $q) = ($1, $2 || 0); } elsif ($arg =~ m!^\s*\[\s*$gre\s*(?:,\s*([-+]?\d*\s*)?pi(?:/\s*(\d+))?\s*)?\]\s*$!) { ($p, $q) = ($1, ($2 eq '-' ? -1 : ($2 || 1)) * pi() / ($3 || 1)); } elsif ($arg =~ /^\s*\[\s*$gre\s*\]\s*$/) { ($p, $q) = ($1, 0); } elsif ($arg =~ /^\s*$gre\s*$/) { ($p, $q) = ($1, 0); } if (defined $p) { $p =~ s/^\+//; $q =~ s/^\+//; $p =~ s/^(-?)inf$/"${1}9**9**9"/e if $has_inf; $q =~ s/^(-?)inf$/"${1}9**9**9"/e if $has_inf; } return ($p, $q); } sub _copy { my $self = shift; my $clone = {%$self}; if ($self->{'cartesian'}) { $clone->{'cartesian'} = [@{$self->{'cartesian'}}]; } if ($self->{'polar'}) { $clone->{'polar'} = [@{$self->{'polar'}}]; } bless $clone,__PACKAGE__; return $clone; } # # ->make # # Create a new complex number (cartesian form) # sub make { my $self = bless {}, shift; my ($re, $im); if (@_ == 0) { ($re, $im) = (0, 0); } elsif (@_ == 1) { return (ref $self)->emake($_[0]) if ($_[0] =~ /^\s*\[/); ($re, $im) = _make($_[0]); } elsif (@_ == 2) { ($re, $im) = @_; } if (defined $re) { _cannot_make("real part", $re) unless $re =~ /^$gre$/; } $im ||= 0; _cannot_make("imaginary part", $im) unless $im =~ /^$gre$/; $self->_set_cartesian([$re, $im ]); $self->display_format('cartesian'); return $self; } # # ->emake # # Create a new complex number (exponential form) # sub emake { my $self = bless {}, shift; my ($rho, $theta); if (@_ == 0) { ($rho, $theta) = (0, 0); } elsif (@_ == 1) { return (ref $self)->make($_[0]) if ($_[0] =~ /^\s*\(/ || $_[0] =~ /i\s*$/); ($rho, $theta) = _emake($_[0]); } elsif (@_ == 2) { ($rho, $theta) = @_; } if (defined $rho && defined $theta) { if ($rho < 0) { $rho = -$rho; $theta = ($theta <= 0) ? $theta + pi() : $theta - pi(); } } if (defined $rho) { _cannot_make("rho", $rho) unless $rho =~ /^$gre$/; } $theta ||= 0; _cannot_make("theta", $theta) unless $theta =~ /^$gre$/; $self->_set_polar([$rho, $theta]); $self->display_format('polar'); return $self; } sub new { &make } # For backward compatibility only. # # cplx # # Creates a complex number from a (re, im) tuple. # This avoids the burden of writing Math::Complex->make(re, im). # sub cplx { return __PACKAGE__->make(@_); } # # cplxe # # Creates a complex number from a (rho, theta) tuple. # This avoids the burden of writing Math::Complex->emake(rho, theta). # sub cplxe { return __PACKAGE__->emake(@_); } # # pi # # The number defined as pi = 180 degrees # sub pi () { 4 * CORE::atan2(1, 1) } # # pi2 # # The full circle # sub pi2 () { 2 * pi } # # pi4 # # The full circle twice. # sub pi4 () { 4 * pi } # # pip2 # # The quarter circle # sub pip2 () { pi / 2 } # # pip4 # # The eighth circle. # sub pip4 () { pi / 4 } # # _uplog10 # # Used in log10(). # sub _uplog10 () { 1 / CORE::log(10) } # # i # # The number defined as i*i = -1; # sub i () { return $i if ($i); $i = bless {}; $i->{'cartesian'} = [0, 1]; $i->{'polar'} = [1, pip2]; $i->{c_dirty} = 0; $i->{p_dirty} = 0; return $i; } # # _ip2 # # Half of i. # sub _ip2 () { i / 2 } # # Attribute access/set routines # sub _cartesian {$_[0]->{c_dirty} ? $_[0]->_update_cartesian : $_[0]->{'cartesian'}} sub _polar {$_[0]->{p_dirty} ? $_[0]->_update_polar : $_[0]->{'polar'}} sub _set_cartesian { $_[0]->{p_dirty}++; $_[0]->{c_dirty} = 0; $_[0]->{'cartesian'} = $_[1] } sub _set_polar { $_[0]->{c_dirty}++; $_[0]->{p_dirty} = 0; $_[0]->{'polar'} = $_[1] } # # ->_update_cartesian # # Recompute and return the cartesian form, given accurate polar form. # sub _update_cartesian { my $self = shift; my ($r, $t) = @{$self->{'polar'}}; $self->{c_dirty} = 0; return $self->{'cartesian'} = [$r * CORE::cos($t), $r * CORE::sin($t)]; } # # # ->_update_polar # # Recompute and return the polar form, given accurate cartesian form. # sub _update_polar { my $self = shift; my ($x, $y) = @{$self->{'cartesian'}}; $self->{p_dirty} = 0; return $self->{'polar'} = [0, 0] if $x == 0 && $y == 0; return $self->{'polar'} = [CORE::sqrt($x*$x + $y*$y), CORE::atan2($y, $x)]; } # # (_plus) # # Computes z1+z2. # sub _plus { my ($z1, $z2, $regular) = @_; my ($re1, $im1) = @{$z1->_cartesian}; $z2 = cplx($z2) unless ref $z2; my ($re2, $im2) = ref $z2 ? @{$z2->_cartesian} : ($z2, 0); unless (defined $regular) { $z1->_set_cartesian([$re1 + $re2, $im1 + $im2]); return $z1; } return (ref $z1)->make($re1 + $re2, $im1 + $im2); } # # (_minus) # # Computes z1-z2. # sub _minus { my ($z1, $z2, $inverted) = @_; my ($re1, $im1) = @{$z1->_cartesian}; $z2 = cplx($z2) unless ref $z2; my ($re2, $im2) = @{$z2->_cartesian}; unless (defined $inverted) { $z1->_set_cartesian([$re1 - $re2, $im1 - $im2]); return $z1; } return $inverted ? (ref $z1)->make($re2 - $re1, $im2 - $im1) : (ref $z1)->make($re1 - $re2, $im1 - $im2); } # # (_multiply) # # Computes z1*z2. # sub _multiply { my ($z1, $z2, $regular) = @_; if ($z1->{p_dirty} == 0 and ref $z2 and $z2->{p_dirty} == 0) { # if both polar better use polar to avoid rounding errors my ($r1, $t1) = @{$z1->_polar}; my ($r2, $t2) = @{$z2->_polar}; my $t = $t1 + $t2; if ($t > pi()) { $t -= pi2 } elsif ($t <= -pi()) { $t += pi2 } unless (defined $regular) { $z1->_set_polar([$r1 * $r2, $t]); return $z1; } return (ref $z1)->emake($r1 * $r2, $t); } else { my ($x1, $y1) = @{$z1->_cartesian}; if (ref $z2) { my ($x2, $y2) = @{$z2->_cartesian}; return (ref $z1)->make($x1*$x2-$y1*$y2, $x1*$y2+$y1*$x2); } else { return (ref $z1)->make($x1*$z2, $y1*$z2); } } } # # _divbyzero # # Die on division by zero. # sub _divbyzero { my $mess = "$_[0]: Division by zero.\n"; if (defined $_[1]) { $mess .= "(Because in the definition of $_[0], the divisor "; $mess .= "$_[1] " unless ("$_[1]" eq '0'); $mess .= "is 0)\n"; } my @up = caller(1); $mess .= "Died at $up[1] line $up[2].\n"; die $mess; } # # (_divide) # # Computes z1/z2. # sub _divide { my ($z1, $z2, $inverted) = @_; if ($z1->{p_dirty} == 0 and ref $z2 and $z2->{p_dirty} == 0) { # if both polar better use polar to avoid rounding errors my ($r1, $t1) = @{$z1->_polar}; my ($r2, $t2) = @{$z2->_polar}; my $t; if ($inverted) { _divbyzero "$z2/0" if ($r1 == 0); $t = $t2 - $t1; if ($t > pi()) { $t -= pi2 } elsif ($t <= -pi()) { $t += pi2 } return (ref $z1)->emake($r2 / $r1, $t); } else { _divbyzero "$z1/0" if ($r2 == 0); $t = $t1 - $t2; if ($t > pi()) { $t -= pi2 } elsif ($t <= -pi()) { $t += pi2 } return (ref $z1)->emake($r1 / $r2, $t); } } else { my ($d, $x2, $y2); if ($inverted) { ($x2, $y2) = @{$z1->_cartesian}; $d = $x2*$x2 + $y2*$y2; _divbyzero "$z2/0" if $d == 0; return (ref $z1)->make(($x2*$z2)/$d, -($y2*$z2)/$d); } else { my ($x1, $y1) = @{$z1->_cartesian}; if (ref $z2) { ($x2, $y2) = @{$z2->_cartesian}; $d = $x2*$x2 + $y2*$y2; _divbyzero "$z1/0" if $d == 0; my $u = ($x1*$x2 + $y1*$y2)/$d; my $v = ($y1*$x2 - $x1*$y2)/$d; return (ref $z1)->make($u, $v); } else { _divbyzero "$z1/0" if $z2 == 0; return (ref $z1)->make($x1/$z2, $y1/$z2); } } } } # # (_power) # # Computes z1**z2 = exp(z2 * log z1)). # sub _power { my ($z1, $z2, $inverted) = @_; if ($inverted) { return 1 if $z1 == 0 || $z2 == 1; return 0 if $z2 == 0 && Re($z1) > 0; } else { return 1 if $z2 == 0 || $z1 == 1; return 0 if $z1 == 0 && Re($z2) > 0; } my $w = $inverted ? &exp($z1 * &log($z2)) : &exp($z2 * &log($z1)); # If both arguments cartesian, return cartesian, else polar. return $z1->{c_dirty} == 0 && (not ref $z2 or $z2->{c_dirty} == 0) ? cplx(@{$w->_cartesian}) : $w; } # # (_spaceship) # # Computes z1 <=> z2. # Sorts on the real part first, then on the imaginary part. Thus 2-4i < 3+8i. # sub _spaceship { my ($z1, $z2, $inverted) = @_; my ($re1, $im1) = ref $z1 ? @{$z1->_cartesian} : ($z1, 0); my ($re2, $im2) = ref $z2 ? @{$z2->_cartesian} : ($z2, 0); my $sgn = $inverted ? -1 : 1; return $sgn * ($re1 <=> $re2) if $re1 != $re2; return $sgn * ($im1 <=> $im2); } # # (_numeq) # # Computes z1 == z2. # # (Required in addition to _spaceship() because of NaNs.) sub _numeq { my ($z1, $z2, $inverted) = @_; my ($re1, $im1) = ref $z1 ? @{$z1->_cartesian} : ($z1, 0); my ($re2, $im2) = ref $z2 ? @{$z2->_cartesian} : ($z2, 0); return $re1 == $re2 && $im1 == $im2 ? 1 : 0; } # # (_negate) # # Computes -z. # sub _negate { my ($z) = @_; if ($z->{c_dirty}) { my ($r, $t) = @{$z->_polar}; $t = ($t <= 0) ? $t + pi : $t - pi; return (ref $z)->emake($r, $t); } my ($re, $im) = @{$z->_cartesian}; return (ref $z)->make(-$re, -$im); } # # (_conjugate) # # Compute complex's _conjugate. # sub _conjugate { my ($z) = @_; if ($z->{c_dirty}) { my ($r, $t) = @{$z->_polar}; return (ref $z)->emake($r, -$t); } my ($re, $im) = @{$z->_cartesian}; return (ref $z)->make($re, -$im); } # # (abs) # # Compute or set complex's norm (rho). # sub abs { my ($z, $rho) = @_ ? @_ : $_; unless (ref $z) { if (@_ == 2) { $_[0] = $_[1]; } else { return CORE::abs($z); } } if (defined $rho) { $z->{'polar'} = [ $rho, ${$z->_polar}[1] ]; $z->{p_dirty} = 0; $z->{c_dirty} = 1; return $rho; } else { return ${$z->_polar}[0]; } } sub _theta { my $theta = $_[0]; if ($$theta > pi()) { $$theta -= pi2 } elsif ($$theta <= -pi()) { $$theta += pi2 } } # # arg # # Compute or set complex's argument (theta). # sub arg { my ($z, $theta) = @_; return $z unless ref $z; if (defined $theta) { _theta(\$theta); $z->{'polar'} = [ ${$z->_polar}[0], $theta ]; $z->{p_dirty} = 0; $z->{c_dirty} = 1; } else { $theta = ${$z->_polar}[1]; _theta(\$theta); } return $theta; } # # (sqrt) # # Compute sqrt(z). # # It is quite tempting to use wantarray here so that in list context # sqrt() would return the two solutions. This, however, would # break things like # # print "sqrt(z) = ", sqrt($z), "\n"; # # The two values would be printed side by side without no intervening # whitespace, quite confusing. # Therefore if you want the two solutions use the root(). # sub sqrt { my ($z) = @_ ? $_[0] : $_; my ($re, $im) = ref $z ? @{$z->_cartesian} : ($z, 0); return $re < 0 ? cplx(0, CORE::sqrt(-$re)) : CORE::sqrt($re) if $im == 0; my ($r, $t) = @{$z->_polar}; return (ref $z)->emake(CORE::sqrt($r), $t/2); } # # cbrt # # Compute cbrt(z) (cubic root). # # Why are we not returning three values? The same answer as for sqrt(). # sub cbrt { my ($z) = @_; return $z < 0 ? -CORE::exp(CORE::log(-$z)/3) : ($z > 0 ? CORE::exp(CORE::log($z)/3): 0) unless ref $z; my ($r, $t) = @{$z->_polar}; return 0 if $r == 0; return (ref $z)->emake(CORE::exp(CORE::log($r)/3), $t/3); } # # _rootbad # # Die on bad root. # sub _rootbad { my $mess = "Root '$_[0]' illegal, root rank must be positive integer.\n"; my @up = caller(1); $mess .= "Died at $up[1] line $up[2].\n"; die $mess; } # # root # # Computes all nth root for z, returning an array whose size is n. # `n' must be a positive integer. # # The roots are given by (for k = 0..n-1): # # z^(1/n) = r^(1/n) (cos ((t+2 k pi)/n) + i sin ((t+2 k pi)/n)) # sub root { my ($z, $n, $k) = @_; _rootbad($n) if ($n < 1 or int($n) != $n); my ($r, $t) = ref $z ? @{$z->_polar} : (CORE::abs($z), $z >= 0 ? 0 : pi); my $theta_inc = pi2 / $n; my $rho = $r ** (1/$n); my $cartesian = ref $z && $z->{c_dirty} == 0; if (@_ == 2) { my @root; for (my $i = 0, my $theta = $t / $n; $i < $n; $i++, $theta += $theta_inc) { my $w = cplxe($rho, $theta); # Yes, $cartesian is loop invariant. push @root, $cartesian ? cplx(@{$w->_cartesian}) : $w; } return @root; } elsif (@_ == 3) { my $w = cplxe($rho, $t / $n + $k * $theta_inc); return $cartesian ? cplx(@{$w->_cartesian}) : $w; } } # # Re # # Return or set Re(z). # sub Re { my ($z, $Re) = @_; return $z unless ref $z; if (defined $Re) { $z->{'cartesian'} = [ $Re, ${$z->_cartesian}[1] ]; $z->{c_dirty} = 0; $z->{p_dirty} = 1; } else { return ${$z->_cartesian}[0]; } } # # Im # # Return or set Im(z). # sub Im { my ($z, $Im) = @_; return 0 unless ref $z; if (defined $Im) { $z->{'cartesian'} = [ ${$z->_cartesian}[0], $Im ]; $z->{c_dirty} = 0; $z->{p_dirty} = 1; } else { return ${$z->_cartesian}[1]; } } # # rho # # Return or set rho(w). # sub rho { Math::Complex::abs(@_); } # # theta # # Return or set theta(w). # sub theta { Math::Complex::arg(@_); } # # (exp) # # Computes exp(z). # sub exp { my ($z) = @_ ? @_ : $_; return CORE::exp($z) unless ref $z; my ($x, $y) = @{$z->_cartesian}; return (ref $z)->emake(CORE::exp($x), $y); } # # _logofzero # # Die on logarithm of zero. # sub _logofzero { my $mess = "$_[0]: Logarithm of zero.\n"; if (defined $_[1]) { $mess .= "(Because in the definition of $_[0], the argument "; $mess .= "$_[1] " unless ($_[1] eq '0'); $mess .= "is 0)\n"; } my @up = caller(1); $mess .= "Died at $up[1] line $up[2].\n"; die $mess; } # # (log) # # Compute log(z). # sub log { my ($z) = @_ ? @_ : $_; unless (ref $z) { _logofzero("log") if $z == 0; return $z > 0 ? CORE::log($z) : cplx(CORE::log(-$z), pi); } my ($r, $t) = @{$z->_polar}; _logofzero("log") if $r == 0; if ($t > pi()) { $t -= pi2 } elsif ($t <= -pi()) { $t += pi2 } return (ref $z)->make(CORE::log($r), $t); } # # ln # # Alias for log(). # sub ln { Math::Complex::log(@_) } # # log10 # # Compute log10(z). # sub log10 { return Math::Complex::log($_[0]) * _uplog10; } # # logn # # Compute logn(z,n) = log(z) / log(n) # sub logn { my ($z, $n) = @_; $z = cplx($z, 0) unless ref $z; my $logn = $LOGN{$n}; $logn = $LOGN{$n} = CORE::log($n) unless defined $logn; # Cache log(n) return &log($z) / $logn; } # # (cos) # # Compute cos(z) = (exp(iz) + exp(-iz))/2. # sub cos { my ($z) = @_ ? @_ : $_; return CORE::cos($z) unless ref $z; my ($x, $y) = @{$z->_cartesian}; my $ey = CORE::exp($y); my $sx = CORE::sin($x); my $cx = CORE::cos($x); my $ey_1 = $ey ? 1 / $ey : Inf(); return (ref $z)->make($cx * ($ey + $ey_1)/2, $sx * ($ey_1 - $ey)/2); } # # (sin) # # Compute sin(z) = (exp(iz) - exp(-iz))/2. # sub sin { my ($z) = @_ ? @_ : $_; return CORE::sin($z) unless ref $z; my ($x, $y) = @{$z->_cartesian}; my $ey = CORE::exp($y); my $sx = CORE::sin($x); my $cx = CORE::cos($x); my $ey_1 = $ey ? 1 / $ey : Inf(); return (ref $z)->make($sx * ($ey + $ey_1)/2, $cx * ($ey - $ey_1)/2); } # # tan # # Compute tan(z) = sin(z) / cos(z). # sub tan { my ($z) = @_; my $cz = &cos($z); _divbyzero "tan($z)", "cos($z)" if $cz == 0; return &sin($z) / $cz; } # # sec # # Computes the secant sec(z) = 1 / cos(z). # sub sec { my ($z) = @_; my $cz = &cos($z); _divbyzero "sec($z)", "cos($z)" if ($cz == 0); return 1 / $cz; } # # csc # # Computes the cosecant csc(z) = 1 / sin(z). # sub csc { my ($z) = @_; my $sz = &sin($z); _divbyzero "csc($z)", "sin($z)" if ($sz == 0); return 1 / $sz; } # # cosec # # Alias for csc(). # sub cosec { Math::Complex::csc(@_) } # # cot # # Computes cot(z) = cos(z) / sin(z). # sub cot { my ($z) = @_; my $sz = &sin($z); _divbyzero "cot($z)", "sin($z)" if ($sz == 0); return &cos($z) / $sz; } # # cotan # # Alias for cot(). # sub cotan { Math::Complex::cot(@_) } # # acos # # Computes the arc cosine acos(z) = -i log(z + sqrt(z*z-1)). # sub acos { my $z = $_[0]; return CORE::atan2(CORE::sqrt(1-$z*$z), $z) if (! ref $z) && CORE::abs($z) <= 1; $z = cplx($z, 0) unless ref $z; my ($x, $y) = @{$z->_cartesian}; return 0 if $x == 1 && $y == 0; my $t1 = CORE::sqrt(($x+1)*($x+1) + $y*$y); my $t2 = CORE::sqrt(($x-1)*($x-1) + $y*$y); my $alpha = ($t1 + $t2)/2; my $beta = ($t1 - $t2)/2; $alpha = 1 if $alpha < 1; if ($beta > 1) { $beta = 1 } elsif ($beta < -1) { $beta = -1 } my $u = CORE::atan2(CORE::sqrt(1-$beta*$beta), $beta); my $v = CORE::log($alpha + CORE::sqrt($alpha*$alpha-1)); $v = -$v if $y > 0 || ($y == 0 && $x < -1); return (ref $z)->make($u, $v); } # # asin # # Computes the arc sine asin(z) = -i log(iz + sqrt(1-z*z)). # sub asin { my $z = $_[0]; return CORE::atan2($z, CORE::sqrt(1-$z*$z)) if (! ref $z) && CORE::abs($z) <= 1; $z = cplx($z, 0) unless ref $z; my ($x, $y) = @{$z->_cartesian}; return 0 if $x == 0 && $y == 0; my $t1 = CORE::sqrt(($x+1)*($x+1) + $y*$y); my $t2 = CORE::sqrt(($x-1)*($x-1) + $y*$y); my $alpha = ($t1 + $t2)/2; my $beta = ($t1 - $t2)/2; $alpha = 1 if $alpha < 1; if ($beta > 1) { $beta = 1 } elsif ($beta < -1) { $beta = -1 } my $u = CORE::atan2($beta, CORE::sqrt(1-$beta*$beta)); my $v = -CORE::log($alpha + CORE::sqrt($alpha*$alpha-1)); $v = -$v if $y > 0 || ($y == 0 && $x < -1); return (ref $z)->make($u, $v); } # # atan # # Computes the arc tangent atan(z) = i/2 log((i+z) / (i-z)). # sub atan { my ($z) = @_; return CORE::atan2($z, 1) unless ref $z; my ($x, $y) = ref $z ? @{$z->_cartesian} : ($z, 0); return 0 if $x == 0 && $y == 0; _divbyzero "atan(i)" if ( $z == i); _logofzero "atan(-i)" if (-$z == i); # -i is a bad file test... my $log = &log((i + $z) / (i - $z)); return _ip2 * $log; } # # asec # # Computes the arc secant asec(z) = acos(1 / z). # sub asec { my ($z) = @_; _divbyzero "asec($z)", $z if ($z == 0); return acos(1 / $z); } # # acsc # # Computes the arc cosecant acsc(z) = asin(1 / z). # sub acsc { my ($z) = @_; _divbyzero "acsc($z)", $z if ($z == 0); return asin(1 / $z); } # # acosec # # Alias for acsc(). # sub acosec { Math::Complex::acsc(@_) } # # acot # # Computes the arc cotangent acot(z) = atan(1 / z) # sub acot { my ($z) = @_; _divbyzero "acot(0)" if $z == 0; return ($z >= 0) ? CORE::atan2(1, $z) : CORE::atan2(-1, -$z) unless ref $z; _divbyzero "acot(i)" if ($z - i == 0); _logofzero "acot(-i)" if ($z + i == 0); return atan(1 / $z); } # # acotan # # Alias for acot(). # sub acotan { Math::Complex::acot(@_) } # # cosh # # Computes the hyperbolic cosine cosh(z) = (exp(z) + exp(-z))/2. # sub cosh { my ($z) = @_; my $ex; unless (ref $z) { $ex = CORE::exp($z); return $ex ? ($ex == $ExpInf ? Inf() : ($ex + 1/$ex)/2) : Inf(); } my ($x, $y) = @{$z->_cartesian}; $ex = CORE::exp($x); my $ex_1 = $ex ? 1 / $ex : Inf(); return (ref $z)->make(CORE::cos($y) * ($ex + $ex_1)/2, CORE::sin($y) * ($ex - $ex_1)/2); } # # sinh # # Computes the hyperbolic sine sinh(z) = (exp(z) - exp(-z))/2. # sub sinh { my ($z) = @_; my $ex; unless (ref $z) { return 0 if $z == 0; $ex = CORE::exp($z); return $ex ? ($ex == $ExpInf ? Inf() : ($ex - 1/$ex)/2) : -Inf(); } my ($x, $y) = @{$z->_cartesian}; my $cy = CORE::cos($y); my $sy = CORE::sin($y); $ex = CORE::exp($x); my $ex_1 = $ex ? 1 / $ex : Inf(); return (ref $z)->make(CORE::cos($y) * ($ex - $ex_1)/2, CORE::sin($y) * ($ex + $ex_1)/2); } # # tanh # # Computes the hyperbolic tangent tanh(z) = sinh(z) / cosh(z). # sub tanh { my ($z) = @_; my $cz = cosh($z); _divbyzero "tanh($z)", "cosh($z)" if ($cz == 0); my $sz = sinh($z); return 1 if $cz == $sz; return -1 if $cz == -$sz; return $sz / $cz; } # # sech # # Computes the hyperbolic secant sech(z) = 1 / cosh(z). # sub sech { my ($z) = @_; my $cz = cosh($z); _divbyzero "sech($z)", "cosh($z)" if ($cz == 0); return 1 / $cz; } # # csch # # Computes the hyperbolic cosecant csch(z) = 1 / sinh(z). # sub csch { my ($z) = @_; my $sz = sinh($z); _divbyzero "csch($z)", "sinh($z)" if ($sz == 0); return 1 / $sz; } # # cosech # # Alias for csch(). # sub cosech { Math::Complex::csch(@_) } # # coth # # Computes the hyperbolic cotangent coth(z) = cosh(z) / sinh(z). # sub coth { my ($z) = @_; my $sz = sinh($z); _divbyzero "coth($z)", "sinh($z)" if $sz == 0; my $cz = cosh($z); return 1 if $cz == $sz; return -1 if $cz == -$sz; return $cz / $sz; } # # cotanh # # Alias for coth(). # sub cotanh { Math::Complex::coth(@_) } # # acosh # # Computes the area/inverse hyperbolic cosine acosh(z) = log(z + sqrt(z*z-1)). # sub acosh { my ($z) = @_; unless (ref $z) { $z = cplx($z, 0); } my ($re, $im) = @{$z->_cartesian}; if ($im == 0) { return CORE::log($re + CORE::sqrt($re*$re - 1)) if $re >= 1; return cplx(0, CORE::atan2(CORE::sqrt(1 - $re*$re), $re)) if CORE::abs($re) < 1; } my $t = &sqrt($z * $z - 1) + $z; # Try Taylor if looking bad (this usually means that # $z was large negative, therefore the sqrt is really # close to abs(z), summing that with z...) $t = 1/(2 * $z) - 1/(8 * $z**3) + 1/(16 * $z**5) - 5/(128 * $z**7) if $t == 0; my $u = &log($t); $u->Im(-$u->Im) if $re < 0 && $im == 0; return $re < 0 ? -$u : $u; } # # asinh # # Computes the area/inverse hyperbolic sine asinh(z) = log(z + sqrt(z*z+1)) # sub asinh { my ($z) = @_; unless (ref $z) { my $t = $z + CORE::sqrt($z*$z + 1); return CORE::log($t) if $t; } my $t = &sqrt($z * $z + 1) + $z; # Try Taylor if looking bad (this usually means that # $z was large negative, therefore the sqrt is really # close to abs(z), summing that with z...) $t = 1/(2 * $z) - 1/(8 * $z**3) + 1/(16 * $z**5) - 5/(128 * $z**7) if $t == 0; return &log($t); } # # atanh # # Computes the area/inverse hyperbolic tangent atanh(z) = 1/2 log((1+z) / (1-z)). # sub atanh { my ($z) = @_; unless (ref $z) { return CORE::log((1 + $z)/(1 - $z))/2 if CORE::abs($z) < 1; $z = cplx($z, 0); } _divbyzero 'atanh(1)', "1 - $z" if (1 - $z == 0); _logofzero 'atanh(-1)' if (1 + $z == 0); return 0.5 * &log((1 + $z) / (1 - $z)); } # # asech # # Computes the area/inverse hyperbolic secant asech(z) = acosh(1 / z). # sub asech { my ($z) = @_; _divbyzero 'asech(0)', "$z" if ($z == 0); return acosh(1 / $z); } # # acsch # # Computes the area/inverse hyperbolic cosecant acsch(z) = asinh(1 / z). # sub acsch { my ($z) = @_; _divbyzero 'acsch(0)', $z if ($z == 0); return asinh(1 / $z); } # # acosech # # Alias for acosh(). # sub acosech { Math::Complex::acsch(@_) } # # acoth # # Computes the area/inverse hyperbolic cotangent acoth(z) = 1/2 log((1+z) / (z-1)). # sub acoth { my ($z) = @_; _divbyzero 'acoth(0)' if ($z == 0); unless (ref $z) { return CORE::log(($z + 1)/($z - 1))/2 if CORE::abs($z) > 1; $z = cplx($z, 0); } _divbyzero 'acoth(1)', "$z - 1" if ($z - 1 == 0); _logofzero 'acoth(-1)', "1 + $z" if (1 + $z == 0); return &log((1 + $z) / ($z - 1)) / 2; } # # acotanh # # Alias for acot(). # sub acotanh { Math::Complex::acoth(@_) } # # (atan2) # # Compute atan(z1/z2), minding the right quadrant. # sub atan2 { my ($z1, $z2, $inverted) = @_; my ($re1, $im1, $re2, $im2); if ($inverted) { ($re1, $im1) = ref $z2 ? @{$z2->_cartesian} : ($z2, 0); ($re2, $im2) = ref $z1 ? @{$z1->_cartesian} : ($z1, 0); } else { ($re1, $im1) = ref $z1 ? @{$z1->_cartesian} : ($z1, 0); ($re2, $im2) = ref $z2 ? @{$z2->_cartesian} : ($z2, 0); } if ($im1 || $im2) { # In MATLAB the imaginary parts are ignored. # warn "atan2: Imaginary parts ignored"; # http://documents.wolfram.com/mathematica/functions/ArcTan # NOTE: Mathematica ArcTan[x,y] while atan2(y,x) my $s = $z1 * $z1 + $z2 * $z2; _divbyzero("atan2") if $s == 0; my $i = &i; my $r = $z2 + $z1 * $i; return -$i * &log($r / &sqrt( $s )); } return CORE::atan2($re1, $re2); } # # display_format # ->display_format # # Set (get if no argument) the display format for all complex numbers that # don't happen to have overridden it via ->display_format # # When called as an object method, this actually sets the display format for # the current object. # # Valid object formats are 'c' and 'p' for cartesian and polar. The first # letter is used actually, so the type can be fully spelled out for clarity. # sub display_format { my $self = shift; my %display_format = %DISPLAY_FORMAT; if (ref $self) { # Called as an object method if (exists $self->{display_format}) { my %obj = %{$self->{display_format}}; @display_format{keys %obj} = values %obj; } } if (@_ == 1) { $display_format{style} = shift; } else { my %new = @_; @display_format{keys %new} = values %new; } if (ref $self) { # Called as an object method $self->{display_format} = { %display_format }; return wantarray ? %{$self->{display_format}} : $self->{display_format}->{style}; } # Called as a class method %DISPLAY_FORMAT = %display_format; return wantarray ? %DISPLAY_FORMAT : $DISPLAY_FORMAT{style}; } # # (_stringify) # # Show nicely formatted complex number under its cartesian or polar form, # depending on the current display format: # # . If a specific display format has been recorded for this object, use it. # . Otherwise, use the generic current default for all complex numbers, # which is a package global variable. # sub _stringify { my ($z) = shift; my $style = $z->display_format; $style = $DISPLAY_FORMAT{style} unless defined $style; return $z->_stringify_polar if $style =~ /^p/i; return $z->_stringify_cartesian; } # # ->_stringify_cartesian # # Stringify as a cartesian representation 'a+bi'. # sub _stringify_cartesian { my $z = shift; my ($x, $y) = @{$z->_cartesian}; my ($re, $im); my %format = $z->display_format; my $format = $format{format}; if ($x) { if ($x =~ /^NaN[QS]?$/i) { $re = $x; } else { if ($x =~ /^-?\Q$Inf\E$/oi) { $re = $x; } else { $re = defined $format ? sprintf($format, $x) : $x; } } } else { undef $re; } if ($y) { if ($y =~ /^(NaN[QS]?)$/i) { $im = $y; } else { if ($y =~ /^-?\Q$Inf\E$/oi) { $im = $y; } else { $im = defined $format ? sprintf($format, $y) : ($y == 1 ? "" : ($y == -1 ? "-" : $y)); } } $im .= "i"; } else { undef $im; } my $str = $re; if (defined $im) { if ($y < 0) { $str .= $im; } elsif ($y > 0 || $im =~ /^NaN[QS]?i$/i) { $str .= "+" if defined $re; $str .= $im; } } elsif (!defined $re) { $str = "0"; } return $str; } # # ->_stringify_polar # # Stringify as a polar representation '[r,t]'. # sub _stringify_polar { my $z = shift; my ($r, $t) = @{$z->_polar}; my $theta; my %format = $z->display_format; my $format = $format{format}; if ($t =~ /^NaN[QS]?$/i || $t =~ /^-?\Q$Inf\E$/oi) { $theta = $t; } elsif ($t == pi) { $theta = "pi"; } elsif ($r == 0 || $t == 0) { $theta = defined $format ? sprintf($format, $t) : $t; } return "[$r,$theta]" if defined $theta; # # Try to identify pi/n and friends. # $t -= int(CORE::abs($t) / pi2) * pi2; if ($format{polar_pretty_print} && $t) { my ($a, $b); for $a (2..9) { $b = $t * $a / pi; if ($b =~ /^-?\d+$/) { $b = $b < 0 ? "-" : "" if CORE::abs($b) == 1; $theta = "${b}pi/$a"; last; } } } if (defined $format) { $r = sprintf($format, $r); $theta = sprintf($format, $t) unless defined $theta; } else { $theta = $t unless defined $theta; } return "[$r,$theta]"; } sub Inf { return $Inf; } 1; __END__ =pod =head1 NAME Math::Complex - complex numbers and associated mathematical functions =head1 SYNOPSIS use Math::Complex; $z = Math::Complex->make(5, 6); $t = 4 - 3*i + $z; $j = cplxe(1, 2*pi/3); =head1 DESCRIPTION This package lets you create and manipulate complex numbers. By default, I limits itself to real numbers, but an extra C statement brings full complex support, along with a full set of mathematical functions typically associated with and/or extended to complex numbers. If you wonder what complex numbers are, they were invented to be able to solve the following equation: x*x = -1 and by definition, the solution is noted I (engineers use I instead since I usually denotes an intensity, but the name does not matter). The number I is a pure I number. The arithmetics with pure imaginary numbers works just like you would expect it with real numbers... you just have to remember that i*i = -1 so you have: 5i + 7i = i * (5 + 7) = 12i 4i - 3i = i * (4 - 3) = i 4i * 2i = -8 6i / 2i = 3 1 / i = -i Complex numbers are numbers that have both a real part and an imaginary part, and are usually noted: a + bi where C is the I part and C is the I part. The arithmetic with complex numbers is straightforward. You have to keep track of the real and the imaginary parts, but otherwise the rules used for real numbers just apply: (4 + 3i) + (5 - 2i) = (4 + 5) + i(3 - 2) = 9 + i (2 + i) * (4 - i) = 2*4 + 4i -2i -i*i = 8 + 2i + 1 = 9 + 2i A graphical representation of complex numbers is possible in a plane (also called the I, but it's really a 2D plane). The number z = a + bi is the point whose coordinates are (a, b). Actually, it would be the vector originating from (0, 0) to (a, b). It follows that the addition of two complex numbers is a vectorial addition. Since there is a bijection between a point in the 2D plane and a complex number (i.e. the mapping is unique and reciprocal), a complex number can also be uniquely identified with polar coordinates: [rho, theta] where C is the distance to the origin, and C the angle between the vector and the I axis. There is a notation for this using the exponential form, which is: rho * exp(i * theta) where I is the famous imaginary number introduced above. Conversion between this form and the cartesian form C is immediate: a = rho * cos(theta) b = rho * sin(theta) which is also expressed by this formula: z = rho * exp(i * theta) = rho * (cos theta + i * sin theta) In other words, it's the projection of the vector onto the I and I axes. Mathematicians call I the I or I and I the I of the complex number. The I of C is marked here as C. The polar notation (also known as the trigonometric representation) is much more handy for performing multiplications and divisions of complex numbers, whilst the cartesian notation is better suited for additions and subtractions. Real numbers are on the I axis, and therefore I or I is zero or I. All the common operations that can be performed on a real number have been defined to work on complex numbers as well, and are merely I of the operations defined on real numbers. This means they keep their natural meaning when there is no imaginary part, provided the number is within their definition set. For instance, the C routine which computes the square root of its argument is only defined for non-negative real numbers and yields a non-negative real number (it is an application from B to B). If we allow it to return a complex number, then it can be extended to negative real numbers to become an application from B to B (the set of complex numbers): sqrt(x) = x >= 0 ? sqrt(x) : sqrt(-x)*i It can also be extended to be an application from B to B, whilst its restriction to B behaves as defined above by using the following definition: sqrt(z = [r,t]) = sqrt(r) * exp(i * t/2) Indeed, a negative real number can be noted C<[x,pi]> (the modulus I is always non-negative, so C<[x,pi]> is really C<-x>, a negative number) and the above definition states that sqrt([x,pi]) = sqrt(x) * exp(i*pi/2) = [sqrt(x),pi/2] = sqrt(x)*i which is exactly what we had defined for negative real numbers above. The C returns only one of the solutions: if you want the both, use the C function. All the common mathematical functions defined on real numbers that are extended to complex numbers share that same property of working I when the imaginary part is zero (otherwise, it would not be called an extension, would it?). A I operation possible on a complex number that is the identity for real numbers is called the I, and is noted with a horizontal bar above the number, or C<~z> here. z = a + bi ~z = a - bi Simple... Now look: z * ~z = (a + bi) * (a - bi) = a*a + b*b We saw that the norm of C was noted C and was defined as the distance to the origin, also known as: rho = abs(z) = sqrt(a*a + b*b) so z * ~z = abs(z) ** 2 If z is a pure real number (i.e. C), then the above yields: a * a = abs(a) ** 2 which is true (C has the regular meaning for real number, i.e. stands for the absolute value). This example explains why the norm of C is noted C: it extends the C function to complex numbers, yet is the regular C we know when the complex number actually has no imaginary part... This justifies I our use of the C notation for the norm. =head1 OPERATIONS Given the following notations: z1 = a + bi = r1 * exp(i * t1) z2 = c + di = r2 * exp(i * t2) z = the following (overloaded) operations are supported on complex numbers: z1 + z2 = (a + c) + i(b + d) z1 - z2 = (a - c) + i(b - d) z1 * z2 = (r1 * r2) * exp(i * (t1 + t2)) z1 / z2 = (r1 / r2) * exp(i * (t1 - t2)) z1 ** z2 = exp(z2 * log z1) ~z = a - bi abs(z) = r1 = sqrt(a*a + b*b) sqrt(z) = sqrt(r1) * exp(i * t/2) exp(z) = exp(a) * exp(i * b) log(z) = log(r1) + i*t sin(z) = 1/2i (exp(i * z1) - exp(-i * z)) cos(z) = 1/2 (exp(i * z1) + exp(-i * z)) atan2(y, x) = atan(y / x) # Minding the right quadrant, note the order. The definition used for complex arguments of atan2() is -i log((x + iy)/sqrt(x*x+y*y)) Note that atan2(0, 0) is not well-defined. The following extra operations are supported on both real and complex numbers: Re(z) = a Im(z) = b arg(z) = t abs(z) = r cbrt(z) = z ** (1/3) log10(z) = log(z) / log(10) logn(z, n) = log(z) / log(n) tan(z) = sin(z) / cos(z) csc(z) = 1 / sin(z) sec(z) = 1 / cos(z) cot(z) = 1 / tan(z) asin(z) = -i * log(i*z + sqrt(1-z*z)) acos(z) = -i * log(z + i*sqrt(1-z*z)) atan(z) = i/2 * log((i+z) / (i-z)) acsc(z) = asin(1 / z) asec(z) = acos(1 / z) acot(z) = atan(1 / z) = -i/2 * log((i+z) / (z-i)) sinh(z) = 1/2 (exp(z) - exp(-z)) cosh(z) = 1/2 (exp(z) + exp(-z)) tanh(z) = sinh(z) / cosh(z) = (exp(z) - exp(-z)) / (exp(z) + exp(-z)) csch(z) = 1 / sinh(z) sech(z) = 1 / cosh(z) coth(z) = 1 / tanh(z) asinh(z) = log(z + sqrt(z*z+1)) acosh(z) = log(z + sqrt(z*z-1)) atanh(z) = 1/2 * log((1+z) / (1-z)) acsch(z) = asinh(1 / z) asech(z) = acosh(1 / z) acoth(z) = atanh(1 / z) = 1/2 * log((1+z) / (z-1)) I, I, I, I, I, I, I, I, I, I, I, have aliases I, I, I, I, I, I, I, I, I, I, I, respectively. C, C, C, C, C, and C can be used also as mutators. The C returns only one of the solutions: if you want all three, use the C function. The I function is available to compute all the I roots of some complex, where I is a strictly positive integer. There are exactly I such roots, returned as a list. Getting the number mathematicians call C such that: 1 + j + j*j = 0; is a simple matter of writing: $j = ((root(1, 3))[1]; The Ith root for C is given by: (root(z, n))[k] = r**(1/n) * exp(i * (t + 2*k*pi)/n) You can return the Ith root directly by C, indexing starting from I and ending at I. The I numeric comparison operator, E=E, is also defined. In order to ensure its restriction to real numbers is conform to what you would expect, the comparison is run on the real part of the complex number first, and imaginary parts are compared only when the real parts match. =head1 CREATION To create a complex number, use either: $z = Math::Complex->make(3, 4); $z = cplx(3, 4); if you know the cartesian form of the number, or $z = 3 + 4*i; if you like. To create a number using the polar form, use either: $z = Math::Complex->emake(5, pi/3); $x = cplxe(5, pi/3); instead. The first argument is the modulus, the second is the angle (in radians, the full circle is 2*pi). (Mnemonic: C is used as a notation for complex numbers in the polar form). It is possible to write: $x = cplxe(-3, pi/4); but that will be silently converted into C<[3,-3pi/4]>, since the modulus must be non-negative (it represents the distance to the origin in the complex plane). It is also possible to have a complex number as either argument of the C, C, C, and C: the appropriate component of the argument will be used. $z1 = cplx(-2, 1); $z2 = cplx($z1, 4); The C, C, C, C, and C will also understand a single (string) argument of the forms 2-3i -3i [2,3] [2,-3pi/4] [2] in which case the appropriate cartesian and exponential components will be parsed from the string and used to create new complex numbers. The imaginary component and the theta, respectively, will default to zero. The C, C, C, C, and C will also understand the case of no arguments: this means plain zero or (0, 0). =head1 DISPLAYING When printed, a complex number is usually shown under its cartesian style I, but there are legitimate cases where the polar style I<[r,t]> is more appropriate. The process of converting the complex number into a string that can be displayed is known as I. By calling the class method C and supplying either C<"polar"> or C<"cartesian"> as an argument, you override the default display style, which is C<"cartesian">. Not supplying any argument returns the current settings. This default can be overridden on a per-number basis by calling the C method instead. As before, not supplying any argument returns the current display style for this number. Otherwise whatever you specify will be the new display style for I particular number. For instance: use Math::Complex; Math::Complex::display_format('polar'); $j = (root(1, 3))[1]; print "j = $j\n"; # Prints "j = [1,2pi/3]" $j->display_format('cartesian'); print "j = $j\n"; # Prints "j = -0.5+0.866025403784439i" The polar style attempts to emphasize arguments like I (where I is a positive integer and I an integer within [-9, +9]), this is called I. For the reverse of stringifying, see the C and C. =head2 CHANGED IN PERL 5.6 The C class method and the corresponding C object method can now be called using a parameter hash instead of just a one parameter. The old display format style, which can have values C<"cartesian"> or C<"polar">, can be changed using the C<"style"> parameter. $j->display_format(style => "polar"); The one parameter calling convention also still works. $j->display_format("polar"); There are two new display parameters. The first one is C<"format">, which is a sprintf()-style format string to be used for both numeric parts of the complex number(s). The is somewhat system-dependent but most often it corresponds to C<"%.15g">. You can revert to the default by setting the C to C. # the $j from the above example $j->display_format('format' => '%.5f'); print "j = $j\n"; # Prints "j = -0.50000+0.86603i" $j->display_format('format' => undef); print "j = $j\n"; # Prints "j = -0.5+0.86603i" Notice that this affects also the return values of the C methods: in list context the whole parameter hash will be returned, as opposed to only the style parameter value. This is a potential incompatibility with earlier versions if you have been calling the C method in list context. The second new display parameter is C<"polar_pretty_print">, which can be set to true or false, the default being true. See the previous section for what this means. =head1 USAGE Thanks to overloading, the handling of arithmetics with complex numbers is simple and almost transparent. Here are some examples: use Math::Complex; $j = cplxe(1, 2*pi/3); # $j ** 3 == 1 print "j = $j, j**3 = ", $j ** 3, "\n"; print "1 + j + j**2 = ", 1 + $j + $j**2, "\n"; $z = -16 + 0*i; # Force it to be a complex print "sqrt($z) = ", sqrt($z), "\n"; $k = exp(i * 2*pi/3); print "$j - $k = ", $j - $k, "\n"; $z->Re(3); # Re, Im, arg, abs, $j->arg(2); # (the last two aka rho, theta) # can be used also as mutators. =head1 CONSTANTS =head2 PI The constant C and some handy multiples of it (pi2, pi4, and pip2 (pi/2) and pip4 (pi/4)) are also available if separately exported: use Math::Complex ':pi'; $third_of_circle = pi2 / 3; =head2 Inf The floating point infinity can be exported as a subroutine Inf(): use Math::Complex qw(Inf sinh); my $AlsoInf = Inf() + 42; my $AnotherInf = sinh(1e42); print "$AlsoInf is $AnotherInf\n" if $AlsoInf == $AnotherInf; Note that the stringified form of infinity varies between platforms: it can be for example any of inf infinity INF 1.#INF or it can be something else. Also note that in some platforms trying to use the infinity in arithmetic operations may result in Perl crashing because using an infinity causes SIGFPE or its moral equivalent to be sent. The way to ignore this is local $SIG{FPE} = sub { }; =head1 ERRORS DUE TO DIVISION BY ZERO OR LOGARITHM OF ZERO The division (/) and the following functions log ln log10 logn tan sec csc cot atan asec acsc acot tanh sech csch coth atanh asech acsch acoth cannot be computed for all arguments because that would mean dividing by zero or taking logarithm of zero. These situations cause fatal runtime errors looking like this cot(0): Division by zero. (Because in the definition of cot(0), the divisor sin(0) is 0) Died at ... or atanh(-1): Logarithm of zero. Died at... For the C, C, C, C, C, C, C, C, C, the argument cannot be C<0> (zero). For the logarithmic functions and the C, C, the argument cannot be C<1> (one). For the C, C, the argument cannot be C<-1> (minus one). For the C, C, the argument cannot be C (the imaginary unit). For the C, C, the argument cannot be C<-i> (the negative imaginary unit). For the C, C, C, the argument cannot be I, where I is any integer. atan2(0, 0) is undefined, and if the complex arguments are used for atan2(), a division by zero will happen if z1**2+z2**2 == 0. Note that because we are operating on approximations of real numbers, these errors can happen when merely `too close' to the singularities listed above. =head1 ERRORS DUE TO INDIGESTIBLE ARGUMENTS The C and C accept both real and complex arguments. When they cannot recognize the arguments they will die with error messages like the following Math::Complex::make: Cannot take real part of ... Math::Complex::make: Cannot take real part of ... Math::Complex::emake: Cannot take rho of ... Math::Complex::emake: Cannot take theta of ... =head1 BUGS Saying C exports many mathematical routines in the caller environment and even overrides some (C, C, C). This is construed as a feature by the Authors, actually... ;-) All routines expect to be given real or complex numbers. Don't attempt to use BigFloat, since Perl has currently no rule to disambiguate a '+' operation (for instance) between two overloaded entities. In Cray UNICOS there is some strange numerical instability that results in root(), cos(), sin(), cosh(), sinh(), losing accuracy fast. Beware. The bug may be in UNICOS math libs, in UNICOS C compiler, in Math::Complex. Whatever it is, it does not manifest itself anywhere else where Perl runs. =head1 SEE ALSO L =head1 AUTHORS Daniel S. Lewart >, Jarkko Hietaniemi >, Raphael Manfredi >, Zefram =head1 LICENSE This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1; # eof Y.pl000064400000004055152527051710005322 0ustar00# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by lib/unicore/mktables from the Unicode # database, Version 9.0.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by core Perl only. The format and even the # name or existence of this file are subject to change without notice. Don't # use it directly. Use Unicode::UCD to access the Unicode character data # base. return <<'END'; V276 43 44 60 63 94 95 124 125 126 127 172 173 177 178 215 216 247 248 976 979 981 982 1008 1010 1012 1015 1542 1545 8214 8215 8242 8245 8256 8257 8260 8261 8274 8275 8289 8293 8314 8319 8330 8335 8400 8413 8417 8418 8421 8423 8427 8432 8450 8451 8455 8456 8458 8468 8469 8470 8472 8478 8484 8485 8488 8490 8492 8494 8495 8498 8499 8505 8508 8522 8523 8524 8592 8616 8617 8623 8624 8626 8630 8632 8636 8668 8669 8670 8676 8678 8692 8960 8968 8972 8992 8994 9084 9085 9115 9142 9143 9144 9168 9169 9180 9187 9632 9634 9646 9656 9660 9666 9670 9672 9674 9676 9679 9684 9698 9699 9700 9701 9703 9709 9720 9728 9733 9735 9792 9793 9794 9795 9824 9828 9837 9840 10176 10240 10496 11008 11056 11077 11079 11085 64297 64298 65121 65127 65128 65129 65291 65292 65308 65311 65340 65341 65342 65343 65372 65373 65374 65375 65506 65507 65513 65517 119808 119893 119894 119965 119966 119968 119970 119971 119973 119975 119977 119981 119982 119994 119995 119996 119997 120004 120005 120070 120071 120075 120077 120085 120086 120093 120094 120122 120123 120127 120128 120133 120134 120135 120138 120145 120146 120486 120488 120780 120782 120832 126464 126468 126469 126496 126497 126499 126500 126501 126503 126504 126505 126515 126516 126520 126521 126522 126523 126524 126530 126531 126535 126536 126537 126538 126539 126540 126541 126544 126545 126547 126548 126549 126551 126552 126553 126554 126555 126556 126557 126558 126559 126560 126561 126563 126564 126565 126567 126571 126572 126579 126580 126584 126585 126589 126590 126591 126592 126602 126603 126620 126625 126628 126629 126634 126635 126652 126704 126706 END BigRat.pm000064400000233226152530054110006256 0ustar00# # "Tax the rat farms." - Lord Vetinari # # The following hash values are used: # sign : +,-,NaN,+inf,-inf # _d : denominator # _n : numerator (value = _n/_d) # _a : accuracy # _p : precision # You should not look at the innards of a BigRat - use the methods for this. package Math::BigRat; use 5.006; use strict; use warnings; use Carp qw< carp croak >; use Math::BigFloat 1.999718; our $VERSION = '0.2614'; our @ISA = qw(Math::BigFloat); our ($accuracy, $precision, $round_mode, $div_scale, $upgrade, $downgrade, $_trap_nan, $_trap_inf); use overload # overload key: with_assign '+' => sub { $_[0] -> copy() -> badd($_[1]); }, '-' => sub { my $c = $_[0] -> copy; $_[2] ? $c -> bneg() -> badd( $_[1]) : $c -> bsub($_[1]); }, '*' => sub { $_[0] -> copy() -> bmul($_[1]); }, '/' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bdiv($_[0]) : $_[0] -> copy() -> bdiv($_[1]); }, '%' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bmod($_[0]) : $_[0] -> copy() -> bmod($_[1]); }, '**' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bpow($_[0]) : $_[0] -> copy() -> bpow($_[1]); }, '<<' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> blsft($_[0]) : $_[0] -> copy() -> blsft($_[1]); }, '>>' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> brsft($_[0]) : $_[0] -> copy() -> brsft($_[1]); }, # 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]) : $_[0] -> copy() -> band($_[1]); }, '&=' => sub { $_[0] -> band($_[1]); }, '|' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bior($_[0]) : $_[0] -> copy() -> bior($_[1]); }, '|=' => sub { $_[0] -> bior($_[1]); }, '^' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bxor($_[0]) : $_[0] -> copy() -> bxor($_[1]); }, '^=' => 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]); }, 'cos' => sub { $_[0] -> copy() -> bcos(); }, 'sin' => sub { $_[0] -> copy() -> bsin(); }, 'exp' => sub { $_[0] -> copy() -> bexp($_[1]); }, 'abs' => sub { $_[0] -> copy() -> babs(); }, 'log' => sub { $_[0] -> copy() -> blog(); }, 'sqrt' => sub { $_[0] -> copy() -> bsqrt(); }, 'int' => sub { $_[0] -> copy() -> bint(); }, # overload key: conversion 'bool' => sub { $_[0] -> is_zero() ? '' : 1; }, '""' => sub { $_[0] -> bstr(); }, '0+' => sub { $_[0] -> numify(); }, '=' => sub { $_[0]->copy(); }, ; BEGIN { *objectify = \&Math::BigInt::objectify; # inherit this from BigInt *AUTOLOAD = \&Math::BigFloat::AUTOLOAD; # can't inherit AUTOLOAD # We inherit these from BigFloat because currently it is not possible that # Math::BigFloat has a different $LIB variable than we, because # Math::BigFloat also uses Math::BigInt::config->('lib') (there is always # only one library loaded) *_e_add = \&Math::BigFloat::_e_add; *_e_sub = \&Math::BigFloat::_e_sub; *as_number = \&as_int; *is_pos = \&is_positive; *is_neg = \&is_negative; } ############################################################################## # Global constants and flags. Access these only via the accessor methods! $accuracy = $precision = undef; $round_mode = 'even'; $div_scale = 40; $upgrade = undef; $downgrade = undef; # These are internally, and not to be used from the outside at all! $_trap_nan = 0; # are NaNs ok? set w/ config() $_trap_inf = 0; # are infs ok? set w/ config() # the math backend library my $LIB = 'Math::BigInt::Calc'; my $nan = 'NaN'; #my $class = 'Math::BigRat'; sub isa { return 0 if $_[1] =~ /^Math::Big(Int|Float)/; # we aren't UNIVERSAL::isa(@_); } ############################################################################## sub new { my $proto = shift; my $protoref = ref $proto; my $class = $protoref || $proto; # Check the way we are called. if ($protoref) { croak("new() is a class method, not an instance method"); } if (@_ < 1) { #carp("Using new() with no argument is deprecated;", # " use bzero() or new(0) instead"); return $class -> bzero(); } if (@_ > 2) { carp("Superfluous arguments to new() ignored."); } # Get numerator and denominator. If any of the arguments is undefined, # return zero. my ($n, $d) = @_; if (@_ == 1 && !defined $n || @_ == 2 && (!defined $n || !defined $d)) { #carp("Use of uninitialized value in new()"); return $class -> bzero(); } # Initialize a new object. my $self = bless {}, $class; # One or two input arguments may be given. First handle the numerator $n. if (ref($n)) { $n = Math::BigFloat -> new($n, undef, undef) unless ($n -> isa('Math::BigRat') || $n -> isa('Math::BigInt') || $n -> isa('Math::BigFloat')); } else { if (defined $d) { # If the denominator is defined, the numerator is not a string # fraction, e.g., "355/113". $n = Math::BigFloat -> new($n, undef, undef); } else { # If the denominator is undefined, the numerator might be a string # fraction, e.g., "355/113". if ($n =~ m| ^ \s* (\S+) \s* / \s* (\S+) \s* $ |x) { $n = Math::BigFloat -> new($1, undef, undef); $d = Math::BigFloat -> new($2, undef, undef); } else { $n = Math::BigFloat -> new($n, undef, undef); } } } # At this point $n is an object and $d is either an object or undefined. An # undefined $d means that $d was not specified by the caller (not that $d # was specified as an undefined value). unless (defined $d) { #return $n -> copy($n) if $n -> isa('Math::BigRat'); return $class -> copy($n) if $n -> isa('Math::BigRat'); return $class -> bnan() if $n -> is_nan(); return $class -> binf($n -> sign()) if $n -> is_inf(); if ($n -> isa('Math::BigInt')) { $self -> {_n} = $LIB -> _new($n -> copy() -> babs() -> bstr()); $self -> {_d} = $LIB -> _one(); $self -> {sign} = $n -> sign(); return $self; } if ($n -> isa('Math::BigFloat')) { my $m = $n -> mantissa() -> babs(); my $e = $n -> exponent(); $self -> {_n} = $LIB -> _new($m -> bstr()); $self -> {_d} = $LIB -> _one(); if ($e > 0) { $self -> {_n} = $LIB -> _lsft($self -> {_n}, $LIB -> _new($e -> bstr()), 10); } elsif ($e < 0) { $self -> {_d} = $LIB -> _lsft($self -> {_d}, $LIB -> _new(-$e -> bstr()), 10); my $gcd = $LIB -> _gcd($LIB -> _copy($self -> {_n}), $self -> {_d}); if (!$LIB -> _is_one($gcd)) { $self -> {_n} = $LIB -> _div($self->{_n}, $gcd); $self -> {_d} = $LIB -> _div($self->{_d}, $gcd); } } $self -> {sign} = $n -> sign(); return $self; } die "I don't know how to handle this"; # should never get here } # At the point we know that both $n and $d are defined. We know that $n is # an object, but $d might still be a scalar. Now handle $d. $d = Math::BigFloat -> new($d, undef, undef) unless ref($d) && ($d -> isa('Math::BigRat') || $d -> isa('Math::BigInt') || $d -> isa('Math::BigFloat')); # At this point both $n and $d are objects. return $class -> bnan() if $n -> is_nan() || $d -> is_nan(); # At this point neither $n nor $d is a NaN. if ($n -> is_zero()) { return $class -> bnan() if $d -> is_zero(); # 0/0 = NaN return $class -> bzero(); } return $class -> binf($d -> sign()) if $d -> is_zero(); # At this point, neither $n nor $d is a NaN or a zero. if ($d < 0) { # make sure denominator is positive $n -> bneg(); $d -> bneg(); } if ($n -> is_inf()) { return $class -> bnan() if $d -> is_inf(); # Inf/Inf = NaN return $class -> binf($n -> sign()); } # At this point $n is finite. return $class -> bzero() if $d -> is_inf(); return $class -> binf($d -> sign()) if $d -> is_zero(); # At this point both $n and $d are finite and non-zero. if ($n < 0) { $n -> bneg(); $self -> {sign} = '-'; } else { $self -> {sign} = '+'; } if ($n -> isa('Math::BigRat')) { if ($d -> isa('Math::BigRat')) { # At this point both $n and $d is a Math::BigRat. # p r p * s (p / gcd(p, r)) * (s / gcd(s, q)) # - / - = ----- = --------------------------------- # q s q * r (q / gcd(s, q)) * (r / gcd(p, r)) my $p = $n -> {_n}; my $q = $n -> {_d}; my $r = $d -> {_n}; my $s = $d -> {_d}; my $gcd_pr = $LIB -> _gcd($LIB -> _copy($p), $r); my $gcd_sq = $LIB -> _gcd($LIB -> _copy($s), $q); $self -> {_n} = $LIB -> _mul($LIB -> _div($LIB -> _copy($p), $gcd_pr), $LIB -> _div($LIB -> _copy($s), $gcd_sq)); $self -> {_d} = $LIB -> _mul($LIB -> _div($LIB -> _copy($q), $gcd_sq), $LIB -> _div($LIB -> _copy($r), $gcd_pr)); return $self; # no need for $self -> bnorm() here } # At this point, $n is a Math::BigRat and $d is a Math::Big(Int|Float). my $p = $n -> {_n}; my $q = $n -> {_d}; my $m = $d -> mantissa(); my $e = $d -> exponent(); # / p # | ------------ if e > 0 # | q * m * 10^e # | # p | p # - / (m * 10^e) = | ----- if e == 0 # q | q * m # | # | p * 10^-e # | -------- if e < 0 # \ q * m $self -> {_n} = $LIB -> _copy($p); $self -> {_d} = $LIB -> _mul($LIB -> _copy($q), $m); if ($e > 0) { $self -> {_d} = $LIB -> _lsft($self -> {_d}, $e, 10); } elsif ($e < 0) { $self -> {_n} = $LIB -> _lsft($self -> {_n}, -$e, 10); } return $self -> bnorm(); } else { if ($d -> isa('Math::BigRat')) { # At this point $n is a Math::Big(Int|Float) and $d is a # Math::BigRat. my $m = $n -> mantissa(); my $e = $n -> exponent(); my $p = $d -> {_n}; my $q = $d -> {_d}; # / q * m * 10^e # | ------------ if e > 0 # | p # | # p | m * q # (m * 10^e) / - = | ----- if e == 0 # q | p # | # | q * m # | --------- if e < 0 # \ p * 10^-e $self -> {_n} = $LIB -> _mul($LIB -> _copy($q), $m); $self -> {_d} = $LIB -> _copy($p); if ($e > 0) { $self -> {_n} = $LIB -> _lsft($self -> {_n}, $e, 10); } elsif ($e < 0) { $self -> {_d} = $LIB -> _lsft($self -> {_d}, -$e, 10); } return $self -> bnorm(); } else { # At this point $n and $d are both a Math::Big(Int|Float) my $m1 = $n -> mantissa(); my $e1 = $n -> exponent(); my $m2 = $d -> mantissa(); my $e2 = $d -> exponent(); # / # | m1 * 10^(e1 - e2) # | ----------------- if e1 > e2 # | m2 # | # m1 * 10^e1 | m1 # ---------- = | -- if e1 = e2 # m2 * 10^e2 | m2 # | # | m1 # | ----------------- if e1 < e2 # | m2 * 10^(e2 - e1) # \ $self -> {_n} = $LIB -> _new($m1 -> bstr()); $self -> {_d} = $LIB -> _new($m2 -> bstr()); my $ediff = $e1 - $e2; if ($ediff > 0) { $self -> {_n} = $LIB -> _lsft($self -> {_n}, $LIB -> _new($ediff -> bstr()), 10); } elsif ($ediff < 0) { $self -> {_d} = $LIB -> _lsft($self -> {_d}, $LIB -> _new(-$ediff -> bstr()), 10); } return $self -> bnorm(); } } return $self; } sub copy { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; # If called as a class method, the object to copy is the next argument. $self = shift() unless $selfref; my $copy = bless {}, $class; $copy->{sign} = $self->{sign}; $copy->{_d} = $LIB->_copy($self->{_d}); $copy->{_n} = $LIB->_copy($self->{_n}); $copy->{_a} = $self->{_a} if defined $self->{_a}; $copy->{_p} = $self->{_p} if defined $self->{_p}; #($copy, $copy->{_a}, $copy->{_p}) # = $copy->_find_round_parameters(@_); return $copy; } sub bnan { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; $self = bless {}, $class unless $selfref; if ($_trap_nan) { croak ("Tried to set a variable to NaN in $class->bnan()"); } $self -> {sign} = $nan; $self -> {_n} = $LIB -> _zero(); $self -> {_d} = $LIB -> _one(); ($self, $self->{_a}, $self->{_p}) = $self->_find_round_parameters(@_); return $self; } sub binf { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; $self = bless {}, $class unless $selfref; my $sign = shift(); $sign = defined($sign) && substr($sign, 0, 1) eq '-' ? '-inf' : '+inf'; if ($_trap_inf) { croak ("Tried to set a variable to +-inf in $class->binf()"); } $self -> {sign} = $sign; $self -> {_n} = $LIB -> _zero(); $self -> {_d} = $LIB -> _one(); ($self, $self->{_a}, $self->{_p}) = $self->_find_round_parameters(@_); return $self; } sub bone { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; $self = bless {}, $class unless $selfref; my $sign = shift(); $sign = '+' unless defined($sign) && $sign eq '-'; $self -> {sign} = $sign; $self -> {_n} = $LIB -> _one(); $self -> {_d} = $LIB -> _one(); ($self, $self->{_a}, $self->{_p}) = $self->_find_round_parameters(@_); return $self; } sub bzero { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; $self = bless {}, $class unless $selfref; $self -> {sign} = '+'; $self -> {_n} = $LIB -> _zero(); $self -> {_d} = $LIB -> _one(); ($self, $self->{_a}, $self->{_p}) = $self->_find_round_parameters(@_); return $self; } ############################################################################## sub config { # return (later set?) configuration data as hash ref my $class = shift() || 'Math::BigRat'; 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} = $LIB; $cfg; } ############################################################################## sub bstr { my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); if ($x->{sign} !~ /^[+-]$/) { # inf, NaN etc my $s = $x->{sign}; $s =~ s/^\+//; # +inf => inf return $s; } my $s = ''; $s = $x->{sign} if $x->{sign} ne '+'; # '+3/2' => '3/2' return $s . $LIB->_str($x->{_n}) if $LIB->_is_one($x->{_d}); $s . $LIB->_str($x->{_n}) . '/' . $LIB->_str($x->{_d}); } sub bsstr { my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); if ($x->{sign} !~ /^[+-]$/) { # inf, NaN etc my $s = $x->{sign}; $s =~ s/^\+//; # +inf => inf return $s; } my $s = ''; $s = $x->{sign} if $x->{sign} ne '+'; # +3 vs 3 $s . $LIB->_str($x->{_n}) . '/' . $LIB->_str($x->{_d}); } sub bnorm { # reduce the number to the shortest form my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); # Both parts must be objects of whatever we are using today. if (my $c = $LIB->_check($x->{_n})) { croak("n did not pass the self-check ($c) in bnorm()"); } if (my $c = $LIB->_check($x->{_d})) { croak("d did not pass the self-check ($c) in bnorm()"); } # no normalize for NaN, inf etc. return $x if $x->{sign} !~ /^[+-]$/; # normalize zeros to 0/1 if ($LIB->_is_zero($x->{_n})) { $x->{sign} = '+'; # never leave a -0 $x->{_d} = $LIB->_one() unless $LIB->_is_one($x->{_d}); return $x; } return $x if $LIB->_is_one($x->{_d}); # no need to reduce # Compute the GCD. my $gcd = $LIB->_gcd($LIB->_copy($x->{_n}), $x->{_d}); if (!$LIB->_is_one($gcd)) { $x->{_n} = $LIB->_div($x->{_n}, $gcd); $x->{_d} = $LIB->_div($x->{_d}, $gcd); } $x; } ############################################################################## # sign manipulation sub bneg { # (BRAT or num_str) return BRAT # negate number or make a negated number from string my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); return $x if $x->modify('bneg'); # for +0 do not negate (to have always normalized +0). Does nothing for 'NaN' $x->{sign} =~ tr/+-/-+/ unless ($x->{sign} eq '+' && $LIB->_is_zero($x->{_n})); $x; } ############################################################################## # special values sub _bnan { # used by parent class bnan() to initialize number to NaN my $self = shift; if ($_trap_nan) { my $class = ref($self); # "$self" below will stringify the object, this blows up if $self is a # partial object (happens under trap_nan), so fix it beforehand $self->{_d} = $LIB->_zero() unless defined $self->{_d}; $self->{_n} = $LIB->_zero() unless defined $self->{_n}; croak ("Tried to set $self to NaN in $class\::_bnan()"); } $self->{_n} = $LIB->_zero(); $self->{_d} = $LIB->_zero(); } sub _binf { # used by parent class bone() to initialize number to +inf/-inf my $self = shift; if ($_trap_inf) { my $class = ref($self); # "$self" below will stringify the object, this blows up if $self is a # partial object (happens under trap_nan), so fix it beforehand $self->{_d} = $LIB->_zero() unless defined $self->{_d}; $self->{_n} = $LIB->_zero() unless defined $self->{_n}; croak ("Tried to set $self to inf in $class\::_binf()"); } $self->{_n} = $LIB->_zero(); $self->{_d} = $LIB->_zero(); } sub _bone { # used by parent class bone() to initialize number to +1/-1 my $self = shift; $self->{_n} = $LIB->_one(); $self->{_d} = $LIB->_one(); } sub _bzero { # used by parent class bzero() to initialize number to 0 my $self = shift; $self->{_n} = $LIB->_zero(); $self->{_d} = $LIB->_one(); } ############################################################################## # mul/add/div etc sub badd { # add two rational numbers # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } # +inf + +inf => +inf, -inf + -inf => -inf return $x->binf(substr($x->{sign}, 0, 1)) if $x->{sign} eq $y->{sign} && $x->{sign} =~ /^[+-]inf$/; # +inf + -inf or -inf + +inf => NaN return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/); # 1 1 gcd(3, 4) = 1 1*3 + 1*4 7 # - + - = --------- = -- # 4 3 4*3 12 # we do not compute the gcd() here, but simple do: # 5 7 5*3 + 7*4 43 # - + - = --------- = -- # 4 3 4*3 12 # and bnorm() will then take care of the rest # 5 * 3 $x->{_n} = $LIB->_mul($x->{_n}, $y->{_d}); # 7 * 4 my $m = $LIB->_mul($LIB->_copy($y->{_n}), $x->{_d}); # 5 * 3 + 7 * 4 ($x->{_n}, $x->{sign}) = _e_add($x->{_n}, $m, $x->{sign}, $y->{sign}); # 4 * 3 $x->{_d} = $LIB->_mul($x->{_d}, $y->{_d}); # normalize result, and possible round $x->bnorm()->round(@r); } sub bsub { # subtract two rational numbers # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } # flip sign of $x, call badd(), then flip sign of result $x->{sign} =~ tr/+-/-+/ unless $x->{sign} eq '+' && $LIB->_is_zero($x->{_n}); # not -0 $x->badd($y, @r); # does norm and round $x->{sign} =~ tr/+-/-+/ unless $x->{sign} eq '+' && $LIB->_is_zero($x->{_n}); # not -0 $x; } sub bmul { # multiply two rational numbers # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } return $x->bnan() if $x->{sign} eq 'NaN' || $y->{sign} eq 'NaN'; # inf handling if ($x->{sign} =~ /^[+-]inf$/ || $y->{sign} =~ /^[+-]inf$/) { return $x->bnan() if $x->is_zero() || $y->is_zero(); # result will always be +-inf: # +inf * +/+inf => +inf, -inf * -/-inf => +inf # +inf * -/-inf => -inf, -inf * +/+inf => -inf return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/); return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/); return $x->binf('-'); } # x == 0 # also: or y == 1 or y == -1 return wantarray ? ($x, $class->bzero()) : $x if $x -> is_zero(); if ($y -> is_zero()) { $x -> bzero(); return wantarray ? ($x, $class->bzero()) : $x; } # According to Knuth, this can be optimized by doing gcd twice (for d # and n) and reducing in one step. This saves us a bnorm() at the end. # # p s p * s (p / gcd(p, r)) * (s / gcd(s, q)) # - * - = ----- = --------------------------------- # q r q * r (q / gcd(s, q)) * (r / gcd(p, r)) my $gcd_pr = $LIB -> _gcd($LIB -> _copy($x->{_n}), $y->{_d}); my $gcd_sq = $LIB -> _gcd($LIB -> _copy($y->{_n}), $x->{_d}); $x->{_n} = $LIB -> _mul(scalar $LIB -> _div($x->{_n}, $gcd_pr), scalar $LIB -> _div($LIB -> _copy($y->{_n}), $gcd_sq)); $x->{_d} = $LIB -> _mul(scalar $LIB -> _div($x->{_d}, $gcd_sq), scalar $LIB -> _div($LIB -> _copy($y->{_d}), $gcd_pr)); # compute new sign $x->{sign} = $x->{sign} eq $y->{sign} ? '+' : '-'; $x->round(@r); } sub bdiv { # (dividend: BRAT or num_str, divisor: BRAT or num_str) return # (BRAT, BRAT) (quo, rem) or BRAT (only rem) # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } return $x if $x->modify('bdiv'); my $wantarray = wantarray; # call only once # At least one argument is NaN. This is handled the same way as in # Math::BigInt -> bdiv(). See the comments in the code implementing that # method. if ($x -> is_nan() || $y -> is_nan()) { return $wantarray ? ($x -> bnan(), $class -> bnan()) : $x -> bnan(); } # Divide by zero and modulo zero. This is handled the same way as in # Math::BigInt -> bdiv(). See the comments in the code implementing that # method. if ($y -> is_zero()) { my ($quo, $rem); if ($wantarray) { $rem = $x -> copy(); } if ($x -> is_zero()) { $quo = $x -> bnan(); } else { $quo = $x -> binf($x -> {sign}); } return $wantarray ? ($quo, $rem) : $quo; } # Numerator (dividend) is +/-inf. This is handled the same way as in # Math::BigInt -> bdiv(). See the comments in the code implementing that # method. if ($x -> is_inf()) { my ($quo, $rem); $rem = $class -> bnan() if $wantarray; if ($y -> is_inf()) { $quo = $x -> bnan(); } else { my $sign = $x -> bcmp(0) == $y -> bcmp(0) ? '+' : '-'; $quo = $x -> binf($sign); } return $wantarray ? ($quo, $rem) : $quo; } # Denominator (divisor) is +/-inf. This is handled the same way as in # Math::BigFloat -> bdiv(). See the comments in the code implementing that # method. if ($y -> is_inf()) { my ($quo, $rem); if ($wantarray) { if ($x -> is_zero() || $x -> bcmp(0) == $y -> bcmp(0)) { $rem = $x -> copy(); $quo = $x -> bzero(); } else { $rem = $class -> binf($y -> {sign}); $quo = $x -> bone('-'); } return ($quo, $rem); } else { if ($y -> is_inf()) { if ($x -> is_nan() || $x -> is_inf()) { return $x -> bnan(); } else { return $x -> bzero(); } } } } # At this point, both the numerator and denominator are finite numbers, and # the denominator (divisor) is non-zero. # x == 0? return wantarray ? ($x, $class->bzero()) : $x if $x->is_zero(); # XXX TODO: list context, upgrade # According to Knuth, this can be optimized by doing gcd twice (for d and n) # and reducing in one step. This would save us the bnorm() at the end. # # p r p * s (p / gcd(p, r)) * (s / gcd(s, q)) # - / - = ----- = --------------------------------- # q s q * r (q / gcd(s, q)) * (r / gcd(p, r)) $x->{_n} = $LIB->_mul($x->{_n}, $y->{_d}); $x->{_d} = $LIB->_mul($x->{_d}, $y->{_n}); # compute new sign $x->{sign} = $x->{sign} eq $y->{sign} ? '+' : '-'; $x -> bnorm(); if (wantarray) { my $rem = $x -> copy(); $x -> bfloor(); $x -> round(@r); $rem -> bsub($x -> copy()) -> bmul($y); return $x, $rem; } else { $x -> round(@r); return $x; } } sub bmod { # compute "remainder" (in Perl way) of $x / $y # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } return $x if $x->modify('bmod'); # At least one argument is NaN. This is handled the same way as in # Math::BigInt -> bmod(). if ($x -> is_nan() || $y -> is_nan()) { return $x -> bnan(); } # Modulo zero. This is handled the same way as in Math::BigInt -> bmod(). if ($y -> is_zero()) { return $x; } # Numerator (dividend) is +/-inf. This is handled the same way as in # Math::BigInt -> bmod(). if ($x -> is_inf()) { return $x -> bnan(); } # Denominator (divisor) is +/-inf. This is handled the same way as in # Math::BigInt -> bmod(). if ($y -> is_inf()) { if ($x -> is_zero() || $x -> bcmp(0) == $y -> bcmp(0)) { return $x; } else { return $x -> binf($y -> sign()); } } # At this point, both the numerator and denominator are finite numbers, and # the denominator (divisor) is non-zero. return $x if $x->is_zero(); # 0 / 7 = 0, mod 0 # Compute $x - $y * floor($x/$y). This can probably be optimized by working # on a lower level. $x -> bsub($x -> copy() -> bdiv($y) -> bfloor() -> bmul($y)); return $x -> round(@r); } ############################################################################## # bdec/binc sub bdec { # decrement value (subtract 1) my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_); return $x if $x->{sign} !~ /^[+-]$/; # NaN, inf, -inf if ($x->{sign} eq '-') { $x->{_n} = $LIB->_add($x->{_n}, $x->{_d}); # -5/2 => -7/2 } else { if ($LIB->_acmp($x->{_n}, $x->{_d}) < 0) # n < d? { # 1/3 -- => -2/3 $x->{_n} = $LIB->_sub($LIB->_copy($x->{_d}), $x->{_n}); $x->{sign} = '-'; } else { $x->{_n} = $LIB->_sub($x->{_n}, $x->{_d}); # 5/2 => 3/2 } } $x->bnorm()->round(@r); } sub binc { # increment value (add 1) my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_); return $x if $x->{sign} !~ /^[+-]$/; # NaN, inf, -inf if ($x->{sign} eq '-') { if ($LIB->_acmp($x->{_n}, $x->{_d}) < 0) { # -1/3 ++ => 2/3 (overflow at 0) $x->{_n} = $LIB->_sub($LIB->_copy($x->{_d}), $x->{_n}); $x->{sign} = '+'; } else { $x->{_n} = $LIB->_sub($x->{_n}, $x->{_d}); # -5/2 => -3/2 } } else { $x->{_n} = $LIB->_add($x->{_n}, $x->{_d}); # 5/2 => 7/2 } $x->bnorm()->round(@r); } ############################################################################## # is_foo methods (the rest is inherited) sub is_int { # return true if arg (BRAT or num_str) is an integer my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); return 1 if ($x->{sign} =~ /^[+-]$/) && # NaN and +-inf aren't $LIB->_is_one($x->{_d}); # x/y && y != 1 => no integer 0; } sub is_zero { # return true if arg (BRAT or num_str) is zero my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); return 1 if $x->{sign} eq '+' && $LIB->_is_zero($x->{_n}); 0; } sub is_one { # return true if arg (BRAT or num_str) is +1 or -1 if signis given my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); croak "too many arguments for is_one()" if @_ > 2; my $sign = $_[1] || ''; $sign = '+' if $sign ne '-'; return 1 if ($x->{sign} eq $sign && $LIB->_is_one($x->{_n}) && $LIB->_is_one($x->{_d})); 0; } 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, @_); return 1 if ($x->{sign} =~ /^[+-]$/) && # NaN & +-inf aren't ($LIB->_is_one($x->{_d}) && $LIB->_is_odd($x->{_n})); # x/2 is not, but 3/1 0; } 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, @_); return 0 if $x->{sign} !~ /^[+-]$/; # NaN & +-inf aren't return 1 if ($LIB->_is_one($x->{_d}) # x/3 is never && $LIB->_is_even($x->{_n})); # but 4/1 is 0; } ############################################################################## # parts() and friends sub numerator { my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_); # NaN, inf, -inf return Math::BigInt->new($x->{sign}) if ($x->{sign} !~ /^[+-]$/); my $n = Math::BigInt->new($LIB->_str($x->{_n})); $n->{sign} = $x->{sign}; $n; } sub denominator { my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_); # NaN return Math::BigInt->new($x->{sign}) if $x->{sign} eq 'NaN'; # inf, -inf return Math::BigInt->bone() if $x->{sign} !~ /^[+-]$/; Math::BigInt->new($LIB->_str($x->{_d})); } sub parts { my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_); my $c = 'Math::BigInt'; return ($c->bnan(), $c->bnan()) if $x->{sign} eq 'NaN'; return ($c->binf(), $c->binf()) if $x->{sign} eq '+inf'; return ($c->binf('-'), $c->binf()) if $x->{sign} eq '-inf'; my $n = $c->new($LIB->_str($x->{_n})); $n->{sign} = $x->{sign}; my $d = $c->new($LIB->_str($x->{_d})); ($n, $d); } sub length { my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); return $nan unless $x->is_int(); $LIB->_len($x->{_n}); # length(-123/1) => length(123) } sub digit { my ($class, $x, $n) = ref($_[0]) ? (undef, $_[0], $_[1]) : objectify(1, @_); return $nan unless $x->is_int(); $LIB->_digit($x->{_n}, $n || 0); # digit(-123/1, 2) => digit(123, 2) } ############################################################################## # special calc routines sub bceil { my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_); return $x if ($x->{sign} !~ /^[+-]$/ || # not for NaN, inf $LIB->_is_one($x->{_d})); # 22/1 => 22, 0/1 => 0 $x->{_n} = $LIB->_div($x->{_n}, $x->{_d}); # 22/7 => 3/1 w/ truncate $x->{_d} = $LIB->_one(); # d => 1 $x->{_n} = $LIB->_inc($x->{_n}) if $x->{sign} eq '+'; # +22/7 => 4/1 $x->{sign} = '+' if $x->{sign} eq '-' && $LIB->_is_zero($x->{_n}); # -0 => 0 $x; } sub bfloor { my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_); return $x if ($x->{sign} !~ /^[+-]$/ || # not for NaN, inf $LIB->_is_one($x->{_d})); # 22/1 => 22, 0/1 => 0 $x->{_n} = $LIB->_div($x->{_n}, $x->{_d}); # 22/7 => 3/1 w/ truncate $x->{_d} = $LIB->_one(); # d => 1 $x->{_n} = $LIB->_inc($x->{_n}) if $x->{sign} eq '-'; # -22/7 => -4/1 $x; } sub bint { my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_); return $x if ($x->{sign} !~ /^[+-]$/ || # +/-inf or NaN $LIB -> _is_one($x->{_d})); # already an integer $x->{_n} = $LIB->_div($x->{_n}, $x->{_d}); # 22/7 => 3/1 w/ truncate $x->{_d} = $LIB->_one(); # d => 1 $x->{sign} = '+' if $x->{sign} eq '-' && $LIB -> _is_zero($x->{_n}); return $x; } sub bfac { my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_); # if $x is not an integer if (($x->{sign} ne '+') || (!$LIB->_is_one($x->{_d}))) { return $x->bnan(); } $x->{_n} = $LIB->_fac($x->{_n}); # since _d is 1, we don't need to reduce/norm the result $x->round(@r); } sub bpow { # power ($x ** $y) # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } # $x and/or $y is a NaN return $x->bnan() if $x->is_nan() || $y->is_nan(); # $x and/or $y is a +/-Inf if ($x->is_inf("-")) { return $x->bzero() if $y->is_negative(); return $x->bnan() if $y->is_zero(); return $x if $y->is_odd(); return $x->bneg(); } elsif ($x->is_inf("+")) { return $x->bzero() if $y->is_negative(); return $x->bnan() if $y->is_zero(); return $x; } elsif ($y->is_inf("-")) { return $x->bnan() if $x -> is_one("-"); return $x->binf("+") if $x > -1 && $x < 1; return $x->bone() if $x -> is_one("+"); return $x->bzero(); } elsif ($y->is_inf("+")) { return $x->bnan() if $x -> is_one("-"); return $x->bzero() if $x > -1 && $x < 1; return $x->bone() if $x -> is_one("+"); return $x->binf("+"); } if ($x->is_zero()) { return $x->binf() if $y->is_negative(); return $x->bone("+") if $y->is_zero(); return $x; } elsif ($x->is_one()) { return $x->round(@r) if $y->is_odd(); # x is -1, y is odd => -1 return $x->babs()->round(@r); # x is -1, y is even => 1 } elsif ($y->is_zero()) { return $x->bone(@r); # x^0 and x != 0 => 1 } elsif ($y->is_one()) { return $x->round(@r); # x^1 => x } # we don't support complex numbers, so return NaN return $x->bnan() if $x->is_negative() && !$y->is_int(); # (a/b)^-(c/d) = (b/a)^(c/d) ($x->{_n}, $x->{_d}) = ($x->{_d}, $x->{_n}) if $y->is_negative(); unless ($LIB->_is_one($y->{_n})) { $x->{_n} = $LIB->_pow($x->{_n}, $y->{_n}); $x->{_d} = $LIB->_pow($x->{_d}, $y->{_n}); $x->{sign} = '+' if $x->{sign} eq '-' && $LIB->_is_even($y->{_n}); } unless ($LIB->_is_one($y->{_d})) { return $x->bsqrt(@r) if $LIB->_is_two($y->{_d}); # 1/2 => sqrt return $x->broot($LIB->_str($y->{_d}), @r); # 1/N => root(N) } return $x->round(@r); } sub blog { # Return the logarithm of the operand. If a second operand is defined, that # value is used as the base, otherwise the base is assumed to be Euler's # constant. my ($class, $x, $base, @r); # Don't objectify the base, since an undefined base, as in $x->blog() or # $x->blog(undef) signals that the base is Euler's number. if (!ref($_[0]) && $_[0] =~ /^[A-Za-z]|::/) { # E.g., Math::BigFloat->blog(256, 2) ($class, $x, $base, @r) = defined $_[2] ? objectify(2, @_) : objectify(1, @_); } else { # E.g., Math::BigFloat::blog(256, 2) or $x->blog(2) ($class, $x, $base, @r) = defined $_[1] ? objectify(2, @_) : objectify(1, @_); } return $x if $x->modify('blog'); # Handle all exception cases and all trivial cases. I have used Wolfram Alpha # (http://www.wolframalpha.com) as the reference for these cases. return $x -> bnan() if $x -> is_nan(); if (defined $base) { $base = $class -> new($base) unless ref $base; if ($base -> is_nan() || $base -> is_one()) { return $x -> bnan(); } elsif ($base -> is_inf() || $base -> is_zero()) { return $x -> bnan() if $x -> is_inf() || $x -> is_zero(); return $x -> bzero(); } elsif ($base -> is_negative()) { # -inf < base < 0 return $x -> bzero() if $x -> is_one(); # x = 1 return $x -> bone() if $x == $base; # x = base return $x -> bnan(); # otherwise } return $x -> bone() if $x == $base; # 0 < base && 0 < x < inf } # We now know that the base is either undefined or positive and finite. if ($x -> is_inf()) { # x = +/-inf my $sign = defined $base && $base < 1 ? '-' : '+'; return $x -> binf($sign); } elsif ($x -> is_neg()) { # -inf < x < 0 return $x -> bnan(); } elsif ($x -> is_one()) { # x = 1 return $x -> bzero(); } elsif ($x -> is_zero()) { # x = 0 my $sign = defined $base && $base < 1 ? '+' : '-'; return $x -> binf($sign); } # At this point we are done handling all exception cases and trivial cases. $base = Math::BigFloat -> new($base) if defined $base; my $xn = Math::BigFloat -> new($LIB -> _str($x->{_n})); my $xd = Math::BigFloat -> new($LIB -> _str($x->{_d})); my $xtmp = Math::BigRat -> new($xn -> bdiv($xd) -> blog($base, @r) -> bsstr()); $x -> {sign} = $xtmp -> {sign}; $x -> {_n} = $xtmp -> {_n}; $x -> {_d} = $xtmp -> {_d}; return $x; } sub bexp { # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(1, @_); } return $x->binf(@r) if $x->{sign} eq '+inf'; return $x->bzero(@r) if $x->{sign} eq '-inf'; # we need to limit the accuracy to protect against overflow my $fallback = 0; my ($scale, @params); ($x, @params) = $x->_find_round_parameters(@r); # also takes care of the "error in _find_round_parameters?" case return $x if $x->{sign} eq 'NaN'; # no rounding at all, so must use fallback if (scalar @params == 0) { # simulate old behaviour $params[0] = $class->div_scale(); # and round to it as accuracy $params[1] = undef; # P = undef $scale = $params[0]+4; # at least four more for proper round $params[2] = $r[2]; # round mode by caller or undef $fallback = 1; # to clear a/p afterwards } else { # the 4 below is empirical, and there might be cases where it's not enough... $scale = abs($params[0] || $params[1]) + 4; # take whatever is defined } return $x->bone(@params) if $x->is_zero(); # See the comments in Math::BigFloat on how this algorithm works. # Basically we calculate A and B (where B is faculty(N)) so that A/B = e my $x_org = $x->copy(); if ($scale <= 75) { # set $x directly from a cached string form $x->{_n} = $LIB->_new("90933395208605785401971970164779391644753259799242"); $x->{_d} = $LIB->_new("33452526613163807108170062053440751665152000000000"); $x->{sign} = '+'; } else { # compute A and B so that e = A / B. # After some terms we end up with this, so we use it as a starting point: my $A = $LIB->_new("90933395208605785401971970164779391644753259799242"); my $F = $LIB->_new(42); my $step = 42; # Compute how many steps we need to take to get $A and $B sufficiently big my $steps = Math::BigFloat::_len_to_steps($scale - 4); # print STDERR "# Doing $steps steps for ", $scale-4, " digits\n"; while ($step++ <= $steps) { # calculate $a * $f + 1 $A = $LIB->_mul($A, $F); $A = $LIB->_inc($A); # increment f $F = $LIB->_inc($F); } # compute $B as factorial of $steps (this is faster than doing it manually) my $B = $LIB->_fac($LIB->_new($steps)); # print "A ", $LIB->_str($A), "\nB ", $LIB->_str($B), "\n"; $x->{_n} = $A; $x->{_d} = $B; $x->{sign} = '+'; } # $x contains now an estimate of e, with some surplus digits, so we can round if (!$x_org->is_one()) { # raise $x to the wanted power and round it in one step: $x->bpow($x_org, @params); } else { # else just round the already computed result delete $x->{_a}; delete $x->{_p}; # shortcut to not run through _find_round_parameters again if (defined $params[0]) { $x->bround($params[0], $params[2]); # then round accordingly } else { $x->bfround($params[1], $params[2]); # then round accordingly } } if ($fallback) { # clear a/p after round, since user did not request it delete $x->{_a}; delete $x->{_p}; } $x; } sub bnok { # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } my $xint = Math::BigInt -> new($x -> bint() -> bsstr()); my $yint = Math::BigInt -> new($y -> bint() -> bsstr()); $xint -> bnok($yint); $x -> {sign} = $xint -> {sign}; $x -> {_n} = $xint -> {_n}; $x -> {_d} = $xint -> {_d}; return $x; } sub broot { # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } # Convert $x into a Math::BigFloat. my $xd = Math::BigFloat -> new($LIB -> _str($x->{_d})); my $xflt = Math::BigFloat -> new($LIB -> _str($x->{_n})) -> bdiv($xd); $xflt -> {sign} = $x -> {sign}; # Convert $y into a Math::BigFloat. my $yd = Math::BigFloat -> new($LIB -> _str($y->{_d})); my $yflt = Math::BigFloat -> new($LIB -> _str($y->{_n})) -> bdiv($yd); $yflt -> {sign} = $y -> {sign}; # Compute the root and convert back to a Math::BigRat. $xflt -> broot($yflt, @r); my $xtmp = Math::BigRat -> new($xflt -> bsstr()); $x -> {sign} = $xtmp -> {sign}; $x -> {_n} = $xtmp -> {_n}; $x -> {_d} = $xtmp -> {_d}; return $x; } sub bmodpow { # set up parameters my ($class, $x, $y, $m, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, $m, @r) = objectify(3, @_); } # Convert $x, $y, and $m into Math::BigInt objects. my $xint = Math::BigInt -> new($x -> copy() -> bint()); my $yint = Math::BigInt -> new($y -> copy() -> bint()); my $mint = Math::BigInt -> new($m -> copy() -> bint()); $xint -> bmodpow($y, $m, @r); my $xtmp = Math::BigRat -> new($xint -> bsstr()); $x -> {sign} = $xtmp -> {sign}; $x -> {_n} = $xtmp -> {_n}; $x -> {_d} = $xtmp -> {_d}; return $x; } sub bmodinv { # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } # Convert $x and $y into Math::BigInt objects. my $xint = Math::BigInt -> new($x -> copy() -> bint()); my $yint = Math::BigInt -> new($y -> copy() -> bint()); $xint -> bmodinv($y, @r); my $xtmp = Math::BigRat -> new($xint -> bsstr()); $x -> {sign} = $xtmp -> {sign}; $x -> {_n} = $xtmp -> {_n}; $x -> {_d} = $xtmp -> {_d}; return $x; } sub bsqrt { my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_); return $x->bnan() if $x->{sign} !~ /^[+]/; # NaN, -inf or < 0 return $x if $x->{sign} eq '+inf'; # sqrt(inf) == inf return $x->round(@r) if $x->is_zero() || $x->is_one(); my $n = $x -> {_n}; my $d = $x -> {_d}; # Look for an exact solution. For the numerator and the denominator, take # the square root and square it and see if we got the original value. If we # did, for both the numerator and the denominator, we have an exact # solution. { my $nsqrt = $LIB -> _sqrt($LIB -> _copy($n)); my $n2 = $LIB -> _mul($LIB -> _copy($nsqrt), $nsqrt); if ($LIB -> _acmp($n, $n2) == 0) { my $dsqrt = $LIB -> _sqrt($LIB -> _copy($d)); my $d2 = $LIB -> _mul($LIB -> _copy($dsqrt), $dsqrt); if ($LIB -> _acmp($d, $d2) == 0) { $x -> {_n} = $nsqrt; $x -> {_d} = $dsqrt; return $x->round(@r); } } } local $Math::BigFloat::upgrade = undef; local $Math::BigFloat::downgrade = undef; local $Math::BigFloat::precision = undef; local $Math::BigFloat::accuracy = undef; local $Math::BigInt::upgrade = undef; local $Math::BigInt::precision = undef; local $Math::BigInt::accuracy = undef; my $xn = Math::BigFloat -> new($LIB -> _str($n)); my $xd = Math::BigFloat -> new($LIB -> _str($d)); my $xtmp = Math::BigRat -> new($xn -> bdiv($xd) -> bsqrt() -> bsstr()); $x -> {sign} = $xtmp -> {sign}; $x -> {_n} = $xtmp -> {_n}; $x -> {_d} = $xtmp -> {_d}; $x->round(@r); } sub blsft { my ($class, $x, $y, $b, @r) = objectify(2, @_); $b = 2 if !defined $b; $b = $class -> new($b) unless ref($b) && $b -> isa($class); return $x -> bnan() if $x -> is_nan() || $y -> is_nan() || $b -> is_nan(); # shift by a negative amount? return $x -> brsft($y -> copy() -> babs(), $b) if $y -> {sign} =~ /^-/; $x -> bmul($b -> bpow($y)); } sub brsft { my ($class, $x, $y, $b, @r) = objectify(2, @_); $b = 2 if !defined $b; $b = $class -> new($b) unless ref($b) && $b -> isa($class); return $x -> bnan() if $x -> is_nan() || $y -> is_nan() || $b -> is_nan(); # shift by a negative amount? return $x -> blsft($y -> copy() -> babs(), $b) if $y -> {sign} =~ /^-/; # the following call to bdiv() will return either quotient (scalar context) # or quotient and remainder (list context). $x -> bdiv($b -> bpow($y)); } sub band { my $x = shift; my $xref = ref($x); my $class = $xref || $x; croak 'band() is an instance method, not a class method' unless $xref; croak 'Not enough arguments for band()' if @_ < 1; my $y = shift; $y = $class -> new($y) unless ref($y); my @r = @_; my $xtmp = Math::BigInt -> new($x -> bint()); # to Math::BigInt $xtmp -> band($y); $xtmp = $class -> new($xtmp); # back to Math::BigRat $x -> {sign} = $xtmp -> {sign}; $x -> {_n} = $xtmp -> {_n}; $x -> {_d} = $xtmp -> {_d}; return $x -> round(@r); } sub bior { my $x = shift; my $xref = ref($x); my $class = $xref || $x; croak 'bior() is an instance method, not a class method' unless $xref; croak 'Not enough arguments for bior()' if @_ < 1; my $y = shift; $y = $class -> new($y) unless ref($y); my @r = @_; my $xtmp = Math::BigInt -> new($x -> bint()); # to Math::BigInt $xtmp -> bior($y); $xtmp = $class -> new($xtmp); # back to Math::BigRat $x -> {sign} = $xtmp -> {sign}; $x -> {_n} = $xtmp -> {_n}; $x -> {_d} = $xtmp -> {_d}; return $x -> round(@r); } sub bxor { my $x = shift; my $xref = ref($x); my $class = $xref || $x; croak 'bxor() is an instance method, not a class method' unless $xref; croak 'Not enough arguments for bxor()' if @_ < 1; my $y = shift; $y = $class -> new($y) unless ref($y); my @r = @_; my $xtmp = Math::BigInt -> new($x -> bint()); # to Math::BigInt $xtmp -> bxor($y); $xtmp = $class -> new($xtmp); # back to Math::BigRat $x -> {sign} = $xtmp -> {sign}; $x -> {_n} = $xtmp -> {_n}; $x -> {_d} = $xtmp -> {_d}; return $x -> round(@r); } sub bnot { my $x = shift; my $xref = ref($x); my $class = $xref || $x; croak 'bnot() is an instance method, not a class method' unless $xref; my @r = @_; my $xtmp = Math::BigInt -> new($x -> bint()); # to Math::BigInt $xtmp -> bnot(); $xtmp = $class -> new($xtmp); # back to Math::BigRat $x -> {sign} = $xtmp -> {sign}; $x -> {_n} = $xtmp -> {_n}; $x -> {_d} = $xtmp -> {_d}; return $x -> round(@r); } ############################################################################## # round sub round { $_[0]; } sub bround { $_[0]; } sub bfround { $_[0]; } ############################################################################## # comparing sub bcmp { # compare two signed numbers # set up parameters my ($class, $x, $y) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y) = objectify(2, @_); } if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/) { # $x is NaN and/or $y is NaN return undef if $x->{sign} eq $nan || $y->{sign} eq $nan; # $x and $y are both either +inf or -inf return 0 if $x->{sign} eq $y->{sign} && $x->{sign} =~ /^[+-]inf$/; # $x = +inf and $y < +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; } # $x >= 0 and $y < 0 return 1 if $x->{sign} eq '+' && $y->{sign} eq '-'; # $x < 0 and $y >= 0 return -1 if $x->{sign} eq '-' && $y->{sign} eq '+'; # At this point, we know that $x and $y have the same sign. # shortcut my $xz = $LIB->_is_zero($x->{_n}); my $yz = $LIB->_is_zero($y->{_n}); 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 my $t = $LIB->_mul($LIB->_copy($x->{_n}), $y->{_d}); my $u = $LIB->_mul($LIB->_copy($y->{_n}), $x->{_d}); my $cmp = $LIB->_acmp($t, $u); # signs are equal $cmp = -$cmp if $x->{sign} eq '-'; # both are '-' => reverse $cmp; } sub bacmp { # compare two numbers (as unsigned) # set up parameters my ($class, $x, $y) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y) = objectify(2, @_); } if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/)) { # handle +-inf and NaN return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan)); return 0 if $x->{sign} =~ /^[+-]inf$/ && $y->{sign} =~ /^[+-]inf$/; return 1 if $x->{sign} =~ /^[+-]inf$/ && $y->{sign} !~ /^[+-]inf$/; return -1; } my $t = $LIB->_mul($LIB->_copy($x->{_n}), $y->{_d}); my $u = $LIB->_mul($LIB->_copy($y->{_n}), $x->{_d}); $LIB->_acmp($t, $u); # ignore signs } sub beq { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; croak 'beq() is an instance method, not a class method' unless $selfref; croak 'Wrong number of arguments for beq()' unless @_ == 1; my $cmp = $self -> bcmp(shift); return defined($cmp) && ! $cmp; } sub bne { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; croak 'bne() is an instance method, not a class method' unless $selfref; croak 'Wrong number of arguments for bne()' unless @_ == 1; my $cmp = $self -> bcmp(shift); return defined($cmp) && ! $cmp ? '' : 1; } sub blt { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; croak 'blt() is an instance method, not a class method' unless $selfref; croak 'Wrong number of arguments for blt()' unless @_ == 1; my $cmp = $self -> bcmp(shift); return defined($cmp) && $cmp < 0; } sub ble { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; croak 'ble() is an instance method, not a class method' unless $selfref; croak 'Wrong number of arguments for ble()' unless @_ == 1; my $cmp = $self -> bcmp(shift); return defined($cmp) && $cmp <= 0; } sub bgt { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; croak 'bgt() is an instance method, not a class method' unless $selfref; croak 'Wrong number of arguments for bgt()' unless @_ == 1; my $cmp = $self -> bcmp(shift); return defined($cmp) && $cmp > 0; } sub bge { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; croak 'bge() is an instance method, not a class method' unless $selfref; croak 'Wrong number of arguments for bge()' unless @_ == 1; my $cmp = $self -> bcmp(shift); return defined($cmp) && $cmp >= 0; } ############################################################################## # output conversion sub numify { # convert 17/8 => float (aka 2.125) my ($self, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); # Non-finite number. return $x->bstr() if $x->{sign} !~ /^[+-]$/; # Finite number. my $abs = $LIB->_is_one($x->{_d}) ? $LIB->_num($x->{_n}) : Math::BigFloat -> new($LIB->_str($x->{_n})) -> bdiv($LIB->_str($x->{_d})) -> bstr(); return $x->{sign} eq '-' ? 0 - $abs : 0 + $abs; } sub as_int { my ($self, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); # NaN, inf etc return Math::BigInt->new($x->{sign}) if $x->{sign} !~ /^[+-]$/; my $u = Math::BigInt->bzero(); $u->{value} = $LIB->_div($LIB->_copy($x->{_n}), $x->{_d}); # 22/7 => 3 $u->bneg if $x->{sign} eq '-'; # no negative zero $u; } sub as_float { # return N/D as Math::BigFloat # set up parameters my ($class, $x, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it ($class, $x, @r) = objectify(1, @_) unless ref $_[0]; # NaN, inf etc return Math::BigFloat->new($x->{sign}) if $x->{sign} !~ /^[+-]$/; my $xd = Math::BigFloat -> new($LIB -> _str($x->{_d})); my $xflt = Math::BigFloat -> new($LIB -> _str($x->{_n})); $xflt -> {sign} = $x -> {sign}; $xflt -> bdiv($xd, @r); return $xflt; } sub as_bin { my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); return $x unless $x->is_int(); my $s = $x->{sign}; $s = '' if $s eq '+'; $s . $LIB->_as_bin($x->{_n}); } sub as_hex { my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); return $x unless $x->is_int(); my $s = $x->{sign}; $s = '' if $s eq '+'; $s . $LIB->_as_hex($x->{_n}); } sub as_oct { my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); return $x unless $x->is_int(); my $s = $x->{sign}; $s = '' if $s eq '+'; $s . $LIB->_as_oct($x->{_n}); } ############################################################################## sub from_hex { my $class = shift; $class->new(@_); } sub from_bin { my $class = shift; $class->new(@_); } sub from_oct { my $class = shift; my @parts; for my $c (@_) { push @parts, Math::BigInt->from_oct($c); } $class->new (@parts); } ############################################################################## # import sub import { my $class = shift; my $l = scalar @_; my $lib = ''; my @a; my $try = 'try'; for (my $i = 0; $i < $l ; $i++) { if ($_[$i] eq ':constant') { # this rest causes overlord er load to step in overload::constant float => sub { $class->new(shift); }; } # elsif ($_[$i] eq 'upgrade') # { # # this causes upgrading # $upgrade = $_[$i+1]; # or undef to disable # $i++; # } elsif ($_[$i] eq 'downgrade') { # this causes downgrading $downgrade = $_[$i+1]; # or undef to disable $i++; } elsif ($_[$i] =~ /^(lib|try|only)\z/) { $lib = $_[$i+1] || ''; # default Calc $try = $1; # lib, try or only $i++; } elsif ($_[$i] eq 'with') { # this argument is no longer used #$LIB = $_[$i+1] || 'Math::BigInt::Calc'; # default Math::BigInt::Calc $i++; } else { push @a, $_[$i]; } } require Math::BigInt; # let use Math::BigInt lib => 'GMP'; use Math::BigRat; still have GMP if ($lib ne '') { my @c = split /\s*,\s*/, $lib; foreach (@c) { $_ =~ tr/a-zA-Z0-9://cd; # limit to sane characters } $lib = join(",", @c); } my @import = ('objectify'); push @import, $try => $lib if $lib ne ''; # LIB already loaded, so feed it our lib arguments Math::BigInt->import(@import); $LIB = Math::BigFloat->config("lib"); # register us with LIB to get notified of future lib changes Math::BigInt::_register_callback($class, sub { $LIB = $_[0]; }); # any non :constant stuff is handled by Exporter (loaded by parent class) # even if @_ is empty, to give it a chance $class->SUPER::import(@a); # for subclasses $class->export_to_level(1, $class, @a); # need this, too } 1; __END__ =pod =head1 NAME Math::BigRat - Arbitrary big rational numbers =head1 SYNOPSIS use Math::BigRat; my $x = Math::BigRat->new('3/7'); $x += '5/9'; print $x->bstr(), "\n"; print $x ** 2, "\n"; my $y = Math::BigRat->new('inf'); print "$y ", ($y->is_inf ? 'is' : 'is not'), " infinity\n"; my $z = Math::BigRat->new(144); $z->bsqrt(); =head1 DESCRIPTION Math::BigRat complements Math::BigInt and Math::BigFloat by providing support for arbitrary big rational numbers. =head2 MATH LIBRARY You can change the underlying module that does the low-level math operations by using: use Math::BigRat try => 'GMP'; Note: This needs Math::BigInt::GMP installed. The following would first try to find Math::BigInt::Foo, then Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc: use Math::BigRat try => 'Foo,Math::BigInt::Bar'; If you want to get warned when the fallback occurs, replace "try" with "lib": use Math::BigRat lib => 'Foo,Math::BigInt::Bar'; If you want the code to die instead, replace "try" with "only": use Math::BigRat only => 'Foo,Math::BigInt::Bar'; =head1 METHODS Any methods not listed here are derived from Math::BigFloat (or Math::BigInt), so make sure you check these two modules for further information. =over =item new() $x = Math::BigRat->new('1/3'); Create a new Math::BigRat object. Input can come in various forms: $x = Math::BigRat->new(123); # scalars $x = Math::BigRat->new('inf'); # infinity $x = Math::BigRat->new('123.3'); # float $x = Math::BigRat->new('1/3'); # simple string $x = Math::BigRat->new('1 / 3'); # spaced $x = Math::BigRat->new('1 / 0.1'); # w/ floats $x = Math::BigRat->new(Math::BigInt->new(3)); # BigInt $x = Math::BigRat->new(Math::BigFloat->new('3.1')); # BigFloat $x = Math::BigRat->new(Math::BigInt::Lite->new('2')); # BigLite # You can also give D and N as different objects: $x = Math::BigRat->new( Math::BigInt->new(-123), Math::BigInt->new(7), ); # => -123/7 =item numerator() $n = $x->numerator(); Returns a copy of the numerator (the part above the line) as signed BigInt. =item denominator() $d = $x->denominator(); Returns a copy of the denominator (the part under the line) as positive BigInt. =item parts() ($n, $d) = $x->parts(); Return a list consisting of (signed) numerator and (unsigned) denominator as BigInts. =item numify() my $y = $x->numify(); Returns the object as a scalar. This will lose some data if the object cannot be represented by a normal Perl scalar (integer or float), so use L or L instead. This routine is automatically used whenever a scalar is required: my $x = Math::BigRat->new('3/1'); @array = (0, 1, 2, 3); $y = $array[$x]; # set $y to 3 =item as_int() =item as_number() $x = Math::BigRat->new('13/7'); print $x->as_int(), "\n"; # '1' Returns a copy of the object as BigInt, truncated to an integer. C is an alias for C. =item as_float() $x = Math::BigRat->new('13/7'); print $x->as_float(), "\n"; # '1' $x = Math::BigRat->new('2/3'); print $x->as_float(5), "\n"; # '0.66667' Returns a copy of the object as BigFloat, preserving the accuracy as wanted, or the default of 40 digits. This method was added in v0.22 of Math::BigRat (April 2008). =item as_hex() $x = Math::BigRat->new('13'); print $x->as_hex(), "\n"; # '0xd' Returns the BigRat as hexadecimal string. Works only for integers. =item as_bin() $x = Math::BigRat->new('13'); print $x->as_bin(), "\n"; # '0x1101' Returns the BigRat as binary string. Works only for integers. =item as_oct() $x = Math::BigRat->new('13'); print $x->as_oct(), "\n"; # '015' Returns the BigRat as octal string. Works only for integers. =item from_hex() my $h = Math::BigRat->from_hex('0x10'); Create a BigRat from a hexadecimal number in string form. =item from_oct() my $o = Math::BigRat->from_oct('020'); Create a BigRat from an octal number in string form. =item from_bin() my $b = Math::BigRat->from_bin('0b10000000'); Create a BigRat from an binary number in string form. =item bnan() $x = Math::BigRat->bnan(); Creates a new BigRat object representing NaN (Not A Number). If used on an object, it will set it to NaN: $x->bnan(); =item bzero() $x = Math::BigRat->bzero(); Creates a new BigRat object representing zero. If used on an object, it will set it to zero: $x->bzero(); =item binf() $x = Math::BigRat->binf($sign); Creates a new BigRat object representing infinity. The optional argument is either '-' or '+', indicating whether you want infinity or minus infinity. If used on an object, it will set it to infinity: $x->binf(); $x->binf('-'); =item bone() $x = Math::BigRat->bone($sign); Creates a new BigRat object representing one. The optional argument is either '-' or '+', indicating whether you want one or minus one. If used on an object, it will set it to one: $x->bone(); # +1 $x->bone('-'); # -1 =item length() $len = $x->length(); Return the length of $x in digits for integer values. =item digit() print Math::BigRat->new('123/1')->digit(1); # 1 print Math::BigRat->new('123/1')->digit(-1); # 3 Return the N'ths digit from X when X is an integer value. =item bnorm() $x->bnorm(); Reduce the number to the shortest form. This routine is called automatically whenever it is needed. =item bfac() $x->bfac(); Calculates the factorial of $x. For instance: print Math::BigRat->new('3/1')->bfac(), "\n"; # 1*2*3 print Math::BigRat->new('5/1')->bfac(), "\n"; # 1*2*3*4*5 Works currently only for integers. =item bround()/round()/bfround() Are not yet implemented. =item bmod() $x->bmod($y); Returns $x modulo $y. When $x is finite, and $y is finite and non-zero, the result is identical to the remainder after floored division (F-division). If, in addition, both $x and $y are integers, the result is identical to the result from Perl's % operator. =item bmodinv() $x->bmodinv($mod); # modular multiplicative inverse Returns the multiplicative inverse of C<$x> modulo C<$mod>. If $y = $x -> copy() -> bmodinv($mod) then C<$y> is the number closest to zero, and with the same sign as C<$mod>, satisfying ($x * $y) % $mod = 1 % $mod If C<$x> and C<$y> are non-zero, they must be relative primes, i.e., C. 'C' is returned when no modular multiplicative inverse exists. =item bmodpow() $num->bmodpow($exp,$mod); # modular exponentiation # ($num**$exp % $mod) Returns the value of C<$num> taken to the power C<$exp> in the modulus C<$mod> using binary exponentiation. C is far superior to writing $num ** $exp % $mod because it is much faster - it reduces internal variables into the modulus whenever possible, so it operates on smaller numbers. C also supports negative exponents. bmodpow($num, -1, $mod) is exactly equivalent to bmodinv($num, $mod) =item bneg() $x->bneg(); Used to negate the object in-place. =item is_one() print "$x is 1\n" if $x->is_one(); Return true if $x is exactly one, otherwise false. =item is_zero() print "$x is 0\n" if $x->is_zero(); Return true if $x is exactly zero, otherwise false. =item is_pos()/is_positive() print "$x is >= 0\n" if $x->is_positive(); Return true if $x is positive (greater than or equal to zero), otherwise false. Please note that '+inf' is also positive, while 'NaN' and '-inf' aren't. C is an alias for C. =item is_neg()/is_negative() print "$x is < 0\n" if $x->is_negative(); Return true if $x is negative (smaller than zero), otherwise false. Please note that '-inf' is also negative, while 'NaN' and '+inf' aren't. C is an alias for C. =item is_int() print "$x is an integer\n" if $x->is_int(); Return true if $x has a denominator of 1 (e.g. no fraction parts), otherwise false. Please note that '-inf', 'inf' and 'NaN' aren't integer. =item is_odd() print "$x is odd\n" if $x->is_odd(); Return true if $x is odd, otherwise false. =item is_even() print "$x is even\n" if $x->is_even(); Return true if $x is even, otherwise false. =item bceil() $x->bceil(); Set $x to the next bigger integer value (e.g. truncate the number to integer and then increment it by one). =item bfloor() $x->bfloor(); Truncate $x to an integer value. =item bint() $x->bint(); Round $x towards zero. =item bsqrt() $x->bsqrt(); Calculate the square root of $x. =item broot() $x->broot($n); Calculate the N'th root of $x. =item badd() $x->badd($y); Adds $y to $x and returns the result. =item bmul() $x->bmul($y); Multiplies $y to $x and returns the result. =item bsub() $x->bsub($y); Subtracts $y from $x and returns the result. =item bdiv() $q = $x->bdiv($y); ($q, $r) = $x->bdiv($y); In scalar context, divides $x by $y and returns the result. In list context, does floored division (F-division), returning an integer $q and a remainder $r so that $x = $q * $y + $r. The remainer (modulo) is equal to what is returned by C<$x->bmod($y)>. =item bdec() $x->bdec(); Decrements $x by 1 and returns the result. =item binc() $x->binc(); Increments $x by 1 and returns the result. =item copy() my $z = $x->copy(); Makes a deep copy of the object. Please see the documentation in L for further details. =item bstr()/bsstr() my $x = Math::BigRat->new('8/4'); print $x->bstr(), "\n"; # prints 1/2 print $x->bsstr(), "\n"; # prints 1/2 Return a string representing this object. =item bcmp() $x->bcmp($y); Compares $x with $y and takes the sign into account. Returns -1, 0, 1 or undef. =item bacmp() $x->bacmp($y); Compares $x with $y while ignoring their sign. Returns -1, 0, 1 or undef. =item beq() $x -> beq($y); Returns true if and only if $x is equal to $y, and false otherwise. =item bne() $x -> bne($y); Returns true if and only if $x is not equal to $y, and false otherwise. =item blt() $x -> blt($y); Returns true if and only if $x is equal to $y, and false otherwise. =item ble() $x -> ble($y); Returns true if and only if $x is less than or equal to $y, and false otherwise. =item bgt() $x -> bgt($y); Returns true if and only if $x is greater than $y, and false otherwise. =item bge() $x -> bge($y); Returns true if and only if $x is greater than or equal to $y, and false otherwise. =item blsft()/brsft() Used to shift numbers left/right. Please see the documentation in L for further details. =item band() $x->band($y); # bitwise and =item bior() $x->bior($y); # bitwise inclusive or =item bxor() $x->bxor($y); # bitwise exclusive or =item bnot() $x->bnot(); # bitwise not (two's complement) =item bpow() $x->bpow($y); Compute $x ** $y. Please see the documentation in L for further details. =item blog() $x->blog($base, $accuracy); # logarithm of x to the base $base If C<$base> is not defined, Euler's number (e) is used: print $x->blog(undef, 100); # log(x) to 100 digits =item bexp() $x->bexp($accuracy); # calculate e ** X Calculates two integers A and B so that A/B is equal to C, where C is Euler's number. This method was added in v0.20 of Math::BigRat (May 2007). See also C. =item bnok() $x->bnok($y); # x over y (binomial coefficient n over k) Calculates the binomial coefficient n over k, also called the "choose" function. The result is equivalent to: ( n ) n! | - | = ------- ( k ) k!(n-k)! This method was added in v0.20 of Math::BigRat (May 2007). =item config() Math::BigRat->config("trap_nan" => 1); # set $accu = Math::BigRat->config("accuracy"); # get Set or get configuration parameter values. Read-only parameters are marked as RO. Read-write parameters are marked as RW. The following parameters are supported. Parameter RO/RW Description Example ============================================================ lib RO Name of the math backend library Math::BigInt::Calc lib_version RO Version of the math backend library 0.30 class RO The class of config you just called Math::BigRat version RO version number of the class you used 0.10 upgrade RW To which class numbers are upgraded undef downgrade RW To which class numbers are downgraded undef precision RW Global precision undef accuracy RW Global accuracy undef round_mode RW Global round mode even div_scale RW Fallback accuracy for div, sqrt etc. 40 trap_nan RW Trap NaNs undef trap_inf RW Trap +inf/-inf undef =back =head1 BUGS Please report any bugs or feature requests to C, or through the web interface at L (requires login). We will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 SUPPORT You can find documentation for this module with the perldoc command. perldoc Math::BigRat You can also look for information at: =over 4 =item * RT: CPAN's request tracker L =item * AnnoCPAN: Annotated CPAN documentation L =item * CPAN Ratings L =item * Search CPAN L =item * CPAN Testers Matrix L =item * The Bignum mailing list =over 4 =item * Post to mailing list C =item * View mailing list L =item * Subscribe/Unsubscribe L =back =back =head1 LICENSE This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself. =head1 SEE ALSO L, L and L as well as the backends L, L, and L. =head1 AUTHORS =over 4 =item * Tels L 2001-2009. =item * Maintained by Peter John Acklam 2011- =back =cut BigFloat.pm000064400000545057152530054110006605 0ustar00package Math::BigFloat; # # Mike grinned. 'Two down, infinity to go' - Mike Nostrus in 'Before and After' # # 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 use 5.006001; use strict; use warnings; use Carp (); use Math::BigInt (); our $VERSION = '1.999811'; require Exporter; our @ISA = qw/Math::BigInt/; our @EXPORT_OK = qw/bpi/; # $_trap_inf/$_trap_nan are internal and should never be accessed from outside our ($AUTOLOAD, $accuracy, $precision, $div_scale, $round_mode, $rnd_mode, $upgrade, $downgrade, $_trap_nan, $_trap_inf); my $class = "Math::BigFloat"; use overload # overload key: with_assign '+' => sub { $_[0] -> copy() -> badd($_[1]); }, '-' => sub { my $c = $_[0] -> copy(); $_[2] ? $c -> bneg() -> badd($_[1]) : $c -> bsub($_[1]); }, '*' => sub { $_[0] -> copy() -> bmul($_[1]); }, '/' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bdiv($_[0]) : $_[0] -> copy() -> bdiv($_[1]); }, '%' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bmod($_[0]) : $_[0] -> copy() -> bmod($_[1]); }, '**' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bpow($_[0]) : $_[0] -> copy() -> bpow($_[1]); }, '<<' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> blsft($_[0]) : $_[0] -> copy() -> blsft($_[1]); }, '>>' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> brsft($_[0]) : $_[0] -> copy() -> brsft($_[1]); }, # 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]) : $_[0] -> copy() -> band($_[1]); }, '&=' => sub { $_[0] -> band($_[1]); }, '|' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bior($_[0]) : $_[0] -> copy() -> bior($_[1]); }, '|=' => sub { $_[0] -> bior($_[1]); }, '^' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bxor($_[0]) : $_[0] -> copy() -> bxor($_[1]); }, '^=' => 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]); }, 'cos' => sub { $_[0] -> copy() -> bcos(); }, 'sin' => sub { $_[0] -> copy() -> bsin(); }, 'exp' => sub { $_[0] -> copy() -> bexp($_[1]); }, 'abs' => sub { $_[0] -> copy() -> babs(); }, 'log' => sub { $_[0] -> copy() -> blog(); }, 'sqrt' => sub { $_[0] -> copy() -> bsqrt(); }, 'int' => sub { $_[0] -> copy() -> bint(); }, # overload key: conversion 'bool' => sub { $_[0] -> is_zero() ? '' : 1; }, '""' => sub { $_[0] -> bstr(); }, '0+' => sub { $_[0] -> numify(); }, '=' => sub { $_[0]->copy(); }, ; ############################################################################## # 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: # Math::BigInt->config('lib') my $MBI = 'Math::BigInt::Calc'; # 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 my $nan = 'NaN'; my $IMPORT = 0; # was import() called yet? used to make require work # some digits of accuracy for blog(undef, 10); which we use in blog() for speed my $LOG_10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726097'; my $LOG_10_A = length($LOG_10)-1; # ditto for log(2) my $LOG_2 = '0.6931471805599453094172321214581765680755001343602552541206800094933936220'; my $LOG_2_A = length($LOG_2)-1; my $HALF = '0.5'; # made into an object if nec. ############################################################################## # the old code had $rnd_mode, so we need to support it, too 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'; # 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 { # make fxxx and bxxx both work by selectively mapping fxxx() to MBF::bxxx() 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 @_ } ############################################################################## { # 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]||''}; } } 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 ############################################################################### sub new { # Create a new Math::BigFloat object from a string or another bigfloat object. # _e: exponent # _m: mantissa # sign => ("+", "-", "+inf", "-inf", or "NaN") my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; my ($wanted, @r) = @_; # avoid numify-calls by not using || on $wanted! unless (defined $wanted) { #Carp::carp("Use of uninitialized value in new"); return $self->bzero(@r); } # Using $wanted->isa("Math::BigFloat") here causes a 'Deep recursion on # subroutine "Math::BigFloat::as_number"' in some tests. Fixme! 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; } $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); } # 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; } # Shortcut for simple forms like '12' that have no trailing zeros. if ($wanted =~ /^([+-]?)0*([1-9][0-9]*[1-9])$/) { $self->{_e} = $MBI -> _zero(); $self->{_es} = '+'; $self->{sign} = $1 || '+'; $self->{_m} = $MBI -> _new($2); if (!$downgrade) { $self->round(@r) unless @r >= 2 && !defined $r[0] && !defined $r[1]; return $self; } } 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"); } return $downgrade->bnan() if $downgrade; $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' $self->{_m} = $MBI->_rsft($self->{_m}, $z, 10); ($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; } } # 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()); } $self->bnorm(); $self->round(@r) unless @r >= 2 && !defined $r[0] && !defined $r[1]; return $self; } sub from_hex { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; # Don't modify constant (read-only) objects. return if $selfref && $self->modify('from_hex'); my $str = shift; # If called as a class method, initialize a new object. $self = $class -> bzero() unless $selfref; if ($str =~ s/ ^ \s* # sign ( [+-]? ) # optional "hex marker" (?: 0? x )? # 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]+ )* ) # exponent (power of 2) using decimal digits (?: [Pp] ( [+-]? ) ( \d+ (?: _ \d+ )* ) )? \s* $ //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; # The significand must be multiplied by 2 raised to this exponent. my $two_expon = $class -> new($e_value); $two_expon -> bneg() if $e_sign eq '-'; # 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. 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"); } $self -> {sign} = $s_sign; $self -> {_m} = $MBI -> _from_hex('0x' . $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); } return $self; } return $self->bnan(); } sub from_oct { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; # Don't modify constant (read-only) objects. return if $selfref && $self->modify('from_oct'); my $str = shift; # If called as a class method, initialize a new object. $self = $class -> bzero() unless $selfref; if ($str =~ s/ ^ \s* # sign ( [+-]? ) # significand using the octal digits 0..7 ( [0-7]+ (?: _ [0-7]+ )* (?: \. (?: [0-7]+ (?: _ [0-7]+ )* )? )? | \. [0-7]+ (?: _ [0-7]+ )* ) # exponent (power of 2) using decimal digits (?: [Pp] ( [+-]? ) ( \d+ (?: _ \d+ )* ) )? \s* $ //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; # The significand must be multiplied by 2 raised to this exponent. my $two_expon = $class -> new($e_value); $two_expon -> bneg() if $e_sign eq '-'; # 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. 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"); } $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); } return $self; } return $self->bnan(); } sub from_bin { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; # Don't modify constant (read-only) objects. return if $selfref && $self->modify('from_bin'); my $str = shift; # If called as a class method, initialize a new object. $self = $class -> bzero() unless $selfref; if ($str =~ s/ ^ \s* # sign ( [+-]? ) # optional "bin marker" (?: 0? b )? # significand using the binary digits 0 and 1 ( [01]+ (?: _ [01]+ )* (?: \. (?: [01]+ (?: _ [01]+ )* )? )? | \. [01]+ (?: _ [01]+ )* ) # exponent (power of 2) using decimal digits (?: [Pp] ( [+-]? ) ( \d+ (?: _ \d+ )* ) )? \s* $ //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; # The significand must be multiplied by 2 raised to this exponent. my $two_expon = $class -> new($e_value); $two_expon -> bneg() if $e_sign eq '-'; # 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. my $idx = index($s_value, '.'); if ($idx >= 0) { substr($s_value, $idx, 1) = ''; $two_expon -= $class -> new(CORE::length($s_value)) -> bsub($idx); } $self -> {sign} = $s_sign; $self -> {_m} = $MBI -> _from_bin('0b' . $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); } return $self; } return $self->bnan(); } sub bzero { # create/assign '+0' 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 return if $selfref && $self->modify('bzero'); $self = bless {}, $class unless $selfref; $self -> {sign} = '+'; $self -> {_m} = $MBI -> _zero(); $self -> {_es} = '+'; $self -> {_e} = $MBI -> _zero(); 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}); } } return $self; } sub bone { # Create or assign '+1' (or -1 if given sign '-'). 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__; } my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; $self->import() if $IMPORT == 0; # make require work return if $selfref && $self->modify('bone'); my $sign = shift; $sign = defined $sign && $sign =~ /^\s*-/ ? "-" : "+"; $self = bless {}, $class unless $selfref; $self -> {sign} = $sign; $self -> {_m} = $MBI -> _one(); $self -> {_es} = '+'; $self -> {_e} = $MBI -> _zero(); 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})); } } return $self; } sub binf { # create/assign a '+inf' or '-inf' 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__; } my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; { no strict 'refs'; if (${"${class}::_trap_inf"}) { Carp::croak("Tried to create +-inf in $class->binf()"); } } $self->import() if $IMPORT == 0; # make require work return if $selfref && $self->modify('binf'); my $sign = shift; $sign = defined $sign && $sign =~ /^\s*-/ ? "-" : "+"; $self = bless {}, $class unless $selfref; $self -> {sign} = $sign . 'inf'; $self -> {_m} = $MBI -> _zero(); $self -> {_es} = '+'; $self -> {_e} = $MBI -> _zero(); return $self; } sub bnan { # create/assign a 'NaN' if (@_ == 0) { #Carp::carp("Using bnan() as a function is deprecated;", # " use bnan() as a method instead"); unshift @_, __PACKAGE__; } my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; { no strict 'refs'; if (${"${class}::_trap_nan"}) { Carp::croak("Tried to create NaN in $class->bnan()"); } } $self->import() if $IMPORT == 0; # make require work return if $selfref && $self->modify('bnan'); $self = bless {}, $class unless $selfref; $self -> {sign} = $nan; $self -> {_m} = $MBI -> _zero(); $self -> {_es} = '+'; $self -> {_e} = $MBI -> _zero(); return $self; } sub bpi { # 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(); my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; my @r; # rounding paramters # 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. if (@_ == 0 && (defined($self) && !ref($self) && $self =~ /^\s*[+-]?\d/i) || !defined($self)) { $r[0] = $self; $class = __PACKAGE__; $self = $class -> bzero(@r); # initialize } # ... or if bpi() is called as a method ... 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 } } ($self, @r) = $self -> _find_round_parameters(@r); # 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. my $n = defined $r[0] ? $r[0] : defined $r[1] ? 1 - $r[1] : $self -> div_scale(); my $rmode = defined $r[2] ? $r[2] : $self -> round_mode(); my $pi; if ($n <= 1000) { # 75 x 14 = 1050 digits my $all_digits = < new($digits . 'e-' . ($n - 1)); } else { # For large accuracy, the arctan formulas become very inefficient with # Math::BigFloat, so use Brent-Salamin (aka AGM or Gauss-Legendre). # Use a few more digits in the intermediate computations. my $nextra = 8; $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; } if (defined $r[0]) { $pi -> accuracy($r[0]); } elsif (defined $r[1]) { $pi -> precision($r[1]); } for my $key (qw/ sign _m _es _e _a _p /) { $self -> {$key} = $pi -> {$key}; } return $self; } sub copy { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; # If called as a class method, the object to copy is the next argument. $self = shift() unless $selfref; my $copy = bless {}, $class; $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}; return $copy; } sub as_number { # return copy as a bigint representation of this Math::BigFloat number my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_); return $x if $x->modify('as_number'); 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"); } 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 $z = $MBI->_rsft($z, $x->{_e}, 10); } elsif (! $MBI->_is_zero($x->{_e})) { # > 0 $z = $MBI->_lsft($z, $x->{_e}, 10); } $z = Math::BigInt->new($x->{sign} . $MBI->_str($z)); $z; } ############################################################################### # Boolean methods ############################################################################### sub is_zero { # return true if arg (BFLOAT or num_str) is zero my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); ($x->{sign} eq '+' && $MBI->_is_zero($x->{_m})) ? 1 : 0; } 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, @_); $sign = '+' if !defined $sign || $sign ne '-'; ($x->{sign} eq $sign && $MBI->_is_zero($x->{_e}) && $MBI->_is_one($x->{_m})) ? 1 : 0; } 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, @_); (($x->{sign} =~ /^[+-]$/) && # NaN & +-inf aren't ($MBI->_is_zero($x->{_e})) && ($MBI->_is_odd($x->{_m}))) ? 1 : 0; } 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, @_); (($x->{sign} =~ /^[+-]$/) && # NaN & +-inf aren't ($x->{_es} eq '+') && # 123.45 isn't ($MBI->_is_even($x->{_m}))) ? 1 : 0; # but 1200 is } sub is_int { # return true if arg (BFLOAT or num_str) is an integer my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); (($x->{sign} =~ /^[+-]$/) && # NaN and +-inf aren't ($x->{_es} eq '+')) ? 1 : 0; # 1e-1 => no integer } ############################################################################### # Comparison methods ############################################################################### sub bcmp { # Compares 2 values. Returns one of undef, <0, =0, >0. (suitable for sort) # set up parameters my ($class, $x, $y) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y) = objectify(2, @_); } return $upgrade->bcmp($x, $y) if defined $upgrade && ((!$x->isa($class)) || (!$y->isa($class))); # Handle all 'nan' cases. return undef if ($x->{sign} eq $nan) || ($y->{sign} eq $nan); # Handle all '+inf' and '-inf' cases. 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 # Handle all cases with opposite signs. 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 # Handle all remaining zero cases. 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 # Both arguments are now finite, non-zero numbers with the same sign. my $cmp; # 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. my $mxl = $MBI->_len($x->{_m}); my $myl = $MBI->_len($y->{_m}); # 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. if ($mxl == $myl) { # First handle the two cases where the exponents have different signs. if ($x->{_es} eq '+' && $y->{_es} eq '-') { $cmp = +1; } elsif ($x->{_es} eq '-' && $y->{_es} eq '+') { $cmp = -1; } # Then handle the case where the exponents have the same sign. else { $cmp = $MBI->_acmp($x->{_e}, $y->{_e}); $cmp = -$cmp if $x->{_es} eq '-'; } # 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; } # 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. my $ex; my $ey; if ($x->{_es} eq '+') { # 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}); } # 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 } } 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| } # If the exponent of x is < 0 and the exponent of y is < 0, add the # absolute values of both exponents to both exponents. else { $ex = $MBI->_copy($y->{_e}); # -ex + |ey| + |ex| = |ey| $ey = $MBI->_copy($x->{_e}); # -ey + |ex| + |ey| = |ex| } } # Now we can normalize the exponents by adding lengths of the mantissas. $ex = $MBI->_add($ex, $MBI->_new($mxl)); $ey = $MBI->_add($ey, $MBI->_new($myl)); # We're done if the exponents are different. $cmp = $MBI->_acmp($ex, $ey); $cmp = -$cmp if $x->{sign} eq '-'; # 124 > 123, but -124 < -123 return $cmp if $cmp; # Compare the mantissas, but first normalize them by padding the shorter # mantissa with zeros (shift left) until it has the same length as the longer # mantissa. my $mx = $x->{_m}; my $my = $y->{_m}; if ($mxl > $myl) { $my = $MBI->_lsft($MBI->_copy($my), $MBI->_new($mxl - $myl), 10); } elsif ($mxl < $myl) { $mx = $MBI->_lsft($MBI->_copy($mx), $MBI->_new($myl - $mxl), 10); } $cmp = $MBI->_acmp($mx, $my); $cmp = -$cmp if $x->{sign} eq '-'; # 124 > 123, but -124 < -123 return $cmp; } sub bacmp { # Compares 2 values, ignoring their signs. # Returns one of undef, <0, =0, >0. (suitable for sort) # set up parameters my ($class, $x, $y) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y) = objectify(2, @_); } return $upgrade->bacmp($x, $y) if defined $upgrade && ((!$x->isa($class)) || (!$y->isa($class))); # handle +-inf and NaN's if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/) { return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan)); return 0 if ($x->is_inf() && $y->is_inf()); return 1 if ($x->is_inf() && !$y->is_inf()); return -1; } # shortcut my $xz = $x->is_zero(); my $yz = $y->is_zero(); return 0 if $xz && $yz; # 0 <=> 0 return -1 if $xz && !$yz; # 0 <=> +y return 1 if $yz && !$xz; # +x <=> 0 # adjust so that exponents are equal my $lxm = $MBI->_len($x->{_m}); my $lym = $MBI->_len($y->{_m}); my ($xes, $yes) = (1, 1); $xes = -1 if $x->{_es} ne '+'; $yes = -1 if $y->{_es} ne '+'; # the numify somewhat limits our length, but makes it much faster my $lx = $lxm + $xes * $MBI->_num($x->{_e}); my $ly = $lym + $yes * $MBI->_num($y->{_e}); my $l = $lx - $ly; return $l <=> 0 if $l != 0; # lengths (corrected by exponent) are equal # so make mantissa equal-length by padding with zero (shift left) my $diff = $lxm - $lym; my $xm = $x->{_m}; # not yet copy it my $ym = $y->{_m}; if ($diff > 0) { $ym = $MBI->_copy($y->{_m}); $ym = $MBI->_lsft($ym, $MBI->_new($diff), 10); } elsif ($diff < 0) { $xm = $MBI->_copy($x->{_m}); $xm = $MBI->_lsft($xm, $MBI->_new(-$diff), 10); } $MBI->_acmp($xm, $ym); } ############################################################################### # Arithmetic methods ############################################################################### sub bneg { # (BINT or num_str) return BINT # negate number or make a negated number from string my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); return $x if $x->modify('bneg'); # for +0 do not negate (to have always normalized +0). Does nothing for 'NaN' $x->{sign} =~ tr/+-/-+/ unless ($x->{sign} eq '+' && $MBI->_is_zero($x->{_m})); $x; } sub bnorm { # adjust m and e so that m is smallest possible my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); return $x if $x->{sign} !~ /^[+-]$/; # inf, nan etc my $zeros = $MBI->_zeros($x->{_m}); # correct for trailing zeros if ($zeros != 0) { my $z = $MBI->_new($zeros); $x->{_m} = $MBI->_rsft($x->{_m}, $z, 10); if ($x->{_es} eq '-') { if ($MBI->_acmp($x->{_e}, $z) >= 0) { $x->{_e} = $MBI->_sub($x->{_e}, $z); $x->{_es} = '+' if $MBI->_is_zero($x->{_e}); } else { $x->{_e} = $MBI->_sub($MBI->_copy($z), $x->{_e}); $x->{_es} = '+'; } } else { $x->{_e} = $MBI->_add($x->{_e}, $z); } } else { # $x can only be 0Ey if there are no trailing zeros ('0' has 0 trailing # zeros). So, for something like 0Ey, set y to 1, and -0 => +0 $x->{sign} = '+', $x->{_es} = '+', $x->{_e} = $MBI->_one() if $MBI->_is_zero($x->{_m}); } $x; } sub binc { # increment arg by one my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_); return $x if $x->modify('binc'); if ($x->{_es} eq '-') { return $x->badd($class->bone(), @r); # digits after dot } if (!$MBI->_is_zero($x->{_e})) # _e == 0 for NaN, inf, -inf { # 1e2 => 100, so after the shift below _m has a '0' as last digit $x->{_m} = $MBI->_lsft($x->{_m}, $x->{_e}, 10); # 1e2 => 100 $x->{_e} = $MBI->_zero(); # normalize $x->{_es} = '+'; # we know that the last digit of $x will be '1' or '9', depending on the # sign } # now $x->{_e} == 0 if ($x->{sign} eq '+') { $x->{_m} = $MBI->_inc($x->{_m}); return $x->bnorm()->bround(@r); } elsif ($x->{sign} eq '-') { $x->{_m} = $MBI->_dec($x->{_m}); $x->{sign} = '+' if $MBI->_is_zero($x->{_m}); # -1 +1 => -0 => +0 return $x->bnorm()->bround(@r); } # inf, nan handling etc $x->badd($class->bone(), @r); # badd() does round } sub bdec { # decrement arg by one my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_); return $x if $x->modify('bdec'); if ($x->{_es} eq '-') { return $x->badd($class->bone('-'), @r); # digits after dot } if (!$MBI->_is_zero($x->{_e})) { $x->{_m} = $MBI->_lsft($x->{_m}, $x->{_e}, 10); # 1e2 => 100 $x->{_e} = $MBI->_zero(); # normalize $x->{_es} = '+'; } # now $x->{_e} == 0 my $zero = $x->is_zero(); # <= 0 if (($x->{sign} eq '-') || $zero) { $x->{_m} = $MBI->_inc($x->{_m}); $x->{sign} = '-' if $zero; # 0 => 1 => -1 $x->{sign} = '+' if $MBI->_is_zero($x->{_m}); # -1 +1 => -0 => +0 return $x->bnorm()->round(@r); } # > 0 elsif ($x->{sign} eq '+') { $x->{_m} = $MBI->_dec($x->{_m}); return $x->bnorm()->round(@r); } # inf, nan handling etc $x->badd($class->bone('-'), @r); # does round } sub badd { # add second arg (BFLOAT or string) to first (BFLOAT) (modifies first) # return result as BFLOAT # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } return $x if $x->modify('badd'); # inf and NaN handling if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/)) { # NaN first return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan)); # inf handling if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/)) { # +inf++inf or -inf+-inf => same, rest is NaN return $x if $x->{sign} eq $y->{sign}; return $x->bnan(); } # +-inf + something => +inf; something +-inf => +-inf $x->{sign} = $y->{sign}, return $x if $y->{sign} =~ /^[+-]inf$/; return $x; } return $upgrade->badd($x, $y, @r) if defined $upgrade && ((!$x->isa($class)) || (!$y->isa($class))); $r[3] = $y; # no push! # speed: no add for 0+y or x+0 return $x->bround(@r) if $y->is_zero(); # x+0 if ($x->is_zero()) # 0+y { # make copy, clobbering up x (modify in place!) $x->{_e} = $MBI->_copy($y->{_e}); $x->{_es} = $y->{_es}; $x->{_m} = $MBI->_copy($y->{_m}); $x->{sign} = $y->{sign} || $nan; return $x->round(@r); } # take lower of the two e's and adapt m1 to it to match m2 my $e = $y->{_e}; $e = $MBI->_zero() if !defined $e; # if no BFLOAT? $e = $MBI->_copy($e); # make copy (didn't do it yet) my $es; ($e, $es) = _e_sub($e, $x->{_e}, $y->{_es} || '+', $x->{_es}); my $add = $MBI->_copy($y->{_m}); if ($es eq '-') # < 0 { $x->{_m} = $MBI->_lsft($x->{_m}, $e, 10); ($x->{_e}, $x->{_es}) = _e_add($x->{_e}, $e, $x->{_es}, $es); } elsif (!$MBI->_is_zero($e)) # > 0 { $add = $MBI->_lsft($add, $e, 10); } # else: both e are the same, so just leave them if ($x->{sign} eq $y->{sign}) { # add $x->{_m} = $MBI->_add($x->{_m}, $add); } else { ($x->{_m}, $x->{sign}) = _e_add($x->{_m}, $add, $x->{sign}, $y->{sign}); } # delete trailing zeros, then round $x->bnorm()->round(@r); } sub bsub { # (BINT or num_str, BINT or num_str) return BINT # subtract second arg from first, modify first # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } return $x if $x -> modify('bsub'); return $upgrade -> new($x) -> bsub($upgrade -> new($y), @r) if defined $upgrade && (!$x -> isa($class) || !$y -> isa($class)); return $x -> round(@r) if $y -> is_zero(); # To correctly handle the lone special case $x -> bsub($x), we note the # sign of $x, then flip the sign from $y, and if the sign of $x did change, # too, then we caught the special case: my $xsign = $x -> {sign}; $y -> {sign} =~ tr/+-/-+/; # does nothing for NaN if ($xsign ne $x -> {sign}) { # special case of $x -> bsub($x) results in 0 return $x -> bzero(@r) if $xsign =~ /^[+-]$/; return $x -> bnan(); # NaN, -inf, +inf } $x -> badd($y, @r); # badd does not leave internal zeros $y -> {sign} =~ tr/+-/-+/; # refix $y (does nothing for NaN) $x; # already rounded by badd() or no rounding } sub bmul { # multiply two numbers # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } return $x if $x->modify('bmul'); return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan)); # inf handling if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/)) { return $x->bnan() if $x->is_zero() || $y->is_zero(); # result will always be +-inf: # +inf * +/+inf => +inf, -inf * -/-inf => +inf # +inf * -/-inf => -inf, -inf * +/+inf => -inf return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/); return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/); return $x->binf('-'); } return $upgrade->bmul($x, $y, @r) if defined $upgrade && ((!$x->isa($class)) || (!$y->isa($class))); # aEb * cEd = (a*c)E(b+d) $x->{_m} = $MBI->_mul($x->{_m}, $y->{_m}); ($x->{_e}, $x->{_es}) = _e_add($x->{_e}, $y->{_e}, $x->{_es}, $y->{_es}); $r[3] = $y; # no push! # adjust sign: $x->{sign} = $x->{sign} ne $y->{sign} ? '-' : '+'; $x->bnorm->round(@r); } sub bmuladd { # multiply two numbers and add the third to the result # set up parameters my ($class, $x, $y, $z, @r) = objectify(3, @_); return $x if $x->modify('bmuladd'); return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan) || ($z->{sign} eq $nan)); # inf handling if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/)) { return $x->bnan() if $x->is_zero() || $y->is_zero(); # result will always be +-inf: # +inf * +/+inf => +inf, -inf * -/-inf => +inf # +inf * -/-inf => -inf, -inf * +/+inf => -inf return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/); return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/); return $x->binf('-'); } return $upgrade->bmul($x, $y, @r) if defined $upgrade && ((!$x->isa($class)) || (!$y->isa($class))); # aEb * cEd = (a*c)E(b+d) $x->{_m} = $MBI->_mul($x->{_m}, $y->{_m}); ($x->{_e}, $x->{_es}) = _e_add($x->{_e}, $y->{_e}, $x->{_es}, $y->{_es}); $r[3] = $y; # no push! # adjust sign: $x->{sign} = $x->{sign} ne $y->{sign} ? '-' : '+'; # z=inf handling (z=NaN handled above) $x->{sign} = $z->{sign}, return $x if $z->{sign} =~ /^[+-]inf$/; # take lower of the two e's and adapt m1 to it to match m2 my $e = $z->{_e}; $e = $MBI->_zero() if !defined $e; # if no BFLOAT? $e = $MBI->_copy($e); # make copy (didn't do it yet) my $es; ($e, $es) = _e_sub($e, $x->{_e}, $z->{_es} || '+', $x->{_es}); my $add = $MBI->_copy($z->{_m}); if ($es eq '-') # < 0 { $x->{_m} = $MBI->_lsft($x->{_m}, $e, 10); ($x->{_e}, $x->{_es}) = _e_add($x->{_e}, $e, $x->{_es}, $es); } elsif (!$MBI->_is_zero($e)) # > 0 { $add = $MBI->_lsft($add, $e, 10); } # else: both e are the same, so just leave them if ($x->{sign} eq $z->{sign}) { # add $x->{_m} = $MBI->_add($x->{_m}, $add); } else { ($x->{_m}, $x->{sign}) = _e_add($x->{_m}, $add, $x->{sign}, $z->{sign}); } # delete trailing zeros, then round $x->bnorm()->round(@r); } sub bdiv { # (dividend: BFLOAT or num_str, divisor: BFLOAT or num_str) return # (BFLOAT, BFLOAT) (quo, rem) or BFLOAT (only quo) # set up parameters my ($class, $x, $y, $a, $p, $r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, $a, $p, $r) = objectify(2, @_); } return $x if $x->modify('bdiv'); my $wantarray = wantarray; # call only once # At least one argument is NaN. This is handled the same way as in # Math::BigInt -> bdiv(). if ($x -> is_nan() || $y -> is_nan()) { return $wantarray ? ($x -> bnan(), $class -> bnan()) : $x -> bnan(); } # Divide by zero and modulo zero. This is handled the same way as in # Math::BigInt -> bdiv(). See the comment in the code for Math::BigInt -> # bdiv() for further details. if ($y -> is_zero()) { my ($quo, $rem); if ($wantarray) { $rem = $x -> copy(); } if ($x -> is_zero()) { $quo = $x -> bnan(); } else { $quo = $x -> binf($x -> {sign}); } return $wantarray ? ($quo, $rem) : $quo; } # Numerator (dividend) is +/-inf. This is handled the same way as in # Math::BigInt -> bdiv(). See the comment in the code for Math::BigInt -> # bdiv() for further details. if ($x -> is_inf()) { my ($quo, $rem); $rem = $class -> bnan() if $wantarray; if ($y -> is_inf()) { $quo = $x -> bnan(); } else { my $sign = $x -> bcmp(0) == $y -> bcmp(0) ? '+' : '-'; $quo = $x -> binf($sign); } return $wantarray ? ($quo, $rem) : $quo; } # Denominator (divisor) is +/-inf. This is handled the same way as in # Math::BigInt -> bdiv(), with one exception: In scalar context, # Math::BigFloat does true division (although rounded), not floored division # (F-division), so a finite number divided by +/-inf is always zero. See the # comment in the code for Math::BigInt -> bdiv() for further details. if ($y -> is_inf()) { my ($quo, $rem); if ($wantarray) { if ($x -> is_zero() || $x -> bcmp(0) == $y -> bcmp(0)) { $rem = $x -> copy(); $quo = $x -> bzero(); } else { $rem = $class -> binf($y -> {sign}); $quo = $x -> bone('-'); } return ($quo, $rem); } else { if ($y -> is_inf()) { if ($x -> is_nan() || $x -> is_inf()) { return $x -> bnan(); } else { return $x -> bzero(); } } } } # At this point, both the numerator and denominator are finite numbers, and # the denominator (divisor) is non-zero. # x == 0? return wantarray ? ($x, $class->bzero()) : $x if $x->is_zero(); # upgrade ? return $upgrade->bdiv($upgrade->new($x), $y, $a, $p, $r) if defined $upgrade; # we need to limit the accuracy to protect against overflow my $fallback = 0; my (@params, $scale); ($x, @params) = $x->_find_round_parameters($a, $p, $r, $y); return $x if $x->is_nan(); # error in _find_round_parameters? # no rounding at all, so must use fallback if (scalar @params == 0) { # simulate old behaviour $params[0] = $class->div_scale(); # and round to it as accuracy $scale = $params[0]+4; # at least four more for proper round $params[2] = $r; # round mode by caller or undef $fallback = 1; # to clear a/p afterwards } else { # the 4 below is empirical, and there might be cases where it is not # enough... $scale = abs($params[0] || $params[1]) + 4; # take whatever is defined } my $rem; $rem = $class -> bzero() if wantarray; $y = $class->new($y) unless $y->isa('Math::BigFloat'); my $lx = $MBI -> _len($x->{_m}); my $ly = $MBI -> _len($y->{_m}); $scale = $lx if $lx > $scale; $scale = $ly if $ly > $scale; my $diff = $ly - $lx; $scale += $diff if $diff > 0; # if lx << ly, but not if ly << lx! # check that $y is not 1 nor -1 and cache the result: my $y_not_one = !($MBI->_is_zero($y->{_e}) && $MBI->_is_one($y->{_m})); # flipping the sign of $y will also flip the sign of $x for the special # case of $x->bsub($x); so we can catch it below: my $xsign = $x->{sign}; $y->{sign} =~ tr/+-/-+/; if ($xsign ne $x->{sign}) { # special case of $x /= $x results in 1 $x->bone(); # "fixes" also sign of $y, since $x is $y } else { # correct $y's sign again $y->{sign} =~ tr/+-/-+/; # continue with normal div code: # make copy of $x in case of list context for later remainder calculation if (wantarray && $y_not_one) { $rem = $x->copy(); } $x->{sign} = $x->{sign} ne $y->sign() ? '-' : '+'; # check for / +-1 (+/- 1E0) if ($y_not_one) { # promote BigInts and it's subclasses (except when already a Math::BigFloat) $y = $class->new($y) unless $y->isa('Math::BigFloat'); # calculate the result to $scale digits and then round it # a * 10 ** b / c * 10 ** d => a/c * 10 ** (b-d) $x->{_m} = $MBI->_lsft($x->{_m}, $MBI->_new($scale), 10); $x->{_m} = $MBI->_div($x->{_m}, $y->{_m}); # a/c # correct exponent of $x ($x->{_e}, $x->{_es}) = _e_sub($x->{_e}, $y->{_e}, $x->{_es}, $y->{_es}); # correct for 10**scale ($x->{_e}, $x->{_es}) = _e_sub($x->{_e}, $MBI->_new($scale), $x->{_es}, '+'); $x->bnorm(); # remove trailing 0's } } # end else $x != $y # shortcut to not run through _find_round_parameters again if (defined $params[0]) { delete $x->{_a}; # clear before round $x->bround($params[0], $params[2]); # then round accordingly } else { delete $x->{_p}; # clear before round $x->bfround($params[1], $params[2]); # then round accordingly } if ($fallback) { # clear a/p after round, since user did not request it delete $x->{_a}; delete $x->{_p}; } if (wantarray) { if ($y_not_one) { $x -> bfloor(); $rem->bmod($y, @params); # copy already done } if ($fallback) { # clear a/p after round, since user did not request it delete $rem->{_a}; delete $rem->{_p}; } return ($x, $rem); } $x; } sub bmod { # (dividend: BFLOAT or num_str, divisor: BFLOAT or num_str) return remainder # set up parameters my ($class, $x, $y, $a, $p, $r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, $a, $p, $r) = objectify(2, @_); } return $x if $x->modify('bmod'); # At least one argument is NaN. This is handled the same way as in # Math::BigInt -> bmod(). if ($x -> is_nan() || $y -> is_nan()) { return $x -> bnan(); } # Modulo zero. This is handled the same way as in Math::BigInt -> bmod(). if ($y -> is_zero()) { return $x; } # Numerator (dividend) is +/-inf. This is handled the same way as in # Math::BigInt -> bmod(). if ($x -> is_inf()) { return $x -> bnan(); } # Denominator (divisor) is +/-inf. This is handled the same way as in # Math::BigInt -> bmod(). if ($y -> is_inf()) { if ($x -> is_zero() || $x -> bcmp(0) == $y -> bcmp(0)) { return $x; } else { return $x -> binf($y -> sign()); } } return $x->bzero() if $x->is_zero() || ($x->is_int() && # check that $y == +1 or $y == -1: ($MBI->_is_zero($y->{_e}) && $MBI->_is_one($y->{_m}))); my $cmp = $x->bacmp($y); # equal or $x < $y? if ($cmp == 0) { # $x == $y => result 0 return $x -> bzero($a, $p); } # only $y of the operands negative? my $neg = $x->{sign} ne $y->{sign} ? 1 : 0; $x->{sign} = $y->{sign}; # calc sign first if ($cmp < 0 && $neg == 0) { # $x < $y => result $x return $x -> round($a, $p, $r); } my $ym = $MBI->_copy($y->{_m}); # 2e1 => 20 $ym = $MBI->_lsft($ym, $y->{_e}, 10) if $y->{_es} eq '+' && !$MBI->_is_zero($y->{_e}); # if $y has digits after dot my $shifty = 0; # correct _e of $x by this if ($y->{_es} eq '-') # has digits after dot { # 123 % 2.5 => 1230 % 25 => 5 => 0.5 $shifty = $MBI->_num($y->{_e}); # no more digits after dot $x->{_m} = $MBI->_lsft($x->{_m}, $y->{_e}, 10); # 123 => 1230, $y->{_m} is already 25 } # $ym is now mantissa of $y based on exponent 0 my $shiftx = 0; # correct _e of $x by this if ($x->{_es} eq '-') # has digits after dot { # 123.4 % 20 => 1234 % 200 $shiftx = $MBI->_num($x->{_e}); # no more digits after dot $ym = $MBI->_lsft($ym, $x->{_e}, 10); # 123 => 1230 } # 123e1 % 20 => 1230 % 20 if ($x->{_es} eq '+' && !$MBI->_is_zero($x->{_e})) { $x->{_m} = $MBI->_lsft($x->{_m}, $x->{_e}, 10); # es => '+' here } $x->{_e} = $MBI->_new($shiftx); $x->{_es} = '+'; $x->{_es} = '-' if $shiftx != 0 || $shifty != 0; $x->{_e} = $MBI->_add($x->{_e}, $MBI->_new($shifty)) if $shifty != 0; # now mantissas are equalized, exponent of $x is adjusted, so calc result $x->{_m} = $MBI->_mod($x->{_m}, $ym); $x->{sign} = '+' if $MBI->_is_zero($x->{_m}); # fix sign for -0 $x->bnorm(); if ($neg != 0 && ! $x -> is_zero()) # one of them negative => correct in place { my $r = $y - $x; $x->{_m} = $r->{_m}; $x->{_e} = $r->{_e}; $x->{_es} = $r->{_es}; $x->{sign} = '+' if $MBI->_is_zero($x->{_m}); # fix sign for -0 $x->bnorm(); } $x->round($a, $p, $r, $y); # round and return } sub bmodpow { # takes a very large number to a very large exponent in a given very # large modulus, quickly, thanks to binary exponentiation. Supports # negative exponents. my ($class, $num, $exp, $mod, @r) = objectify(3, @_); return $num if $num->modify('bmodpow'); # check modulus for valid values return $num->bnan() if ($mod->{sign} ne '+' # NaN, -, -inf, +inf || $mod->is_zero()); # check exponent for valid values if ($exp->{sign} =~ /\w/) { # i.e., if it's NaN, +inf, or -inf... return $num->bnan(); } $num->bmodinv ($mod) if ($exp->{sign} eq '-'); # check num for valid values (also NaN if there was no inverse but $exp < 0) return $num->bnan() if $num->{sign} !~ /^[+-]$/; # $mod is positive, sign on $exp is ignored, result also positive # XXX TODO: speed it up when all three numbers are integers $num->bpow($exp)->bmod($mod); } sub bpow { # (BFLOAT or num_str, BFLOAT or num_str) return BFLOAT # compute power of two numbers, second arg is used as integer # modifies first argument # set up parameters my ($class, $x, $y, $a, $p, $r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, $a, $p, $r) = objectify(2, @_); } return $x if $x->modify('bpow'); return $x->bnan() if $x->{sign} eq $nan || $y->{sign} eq $nan; return $x if $x->{sign} =~ /^[+-]inf$/; # cache the result of is_zero my $y_is_zero = $y->is_zero(); return $x->bone() if $y_is_zero; return $x if $x->is_one() || $y->is_one(); my $x_is_zero = $x->is_zero(); return $x->_pow($y, $a, $p, $r) if !$x_is_zero && !$y->is_int(); # non-integer power my $y1 = $y->as_number()->{value}; # make MBI part # if ($x == -1) if ($x->{sign} eq '-' && $MBI->_is_one($x->{_m}) && $MBI->_is_zero($x->{_e})) { # if $x == -1 and odd/even y => +1/-1 because +-1 ^ (+-1) => +-1 return $MBI->_is_odd($y1) ? $x : $x->babs(1); } if ($x_is_zero) { return $x if $y->{sign} eq '+'; # 0**y => 0 (if not y <= 0) # 0 ** -y => 1 / (0 ** y) => 1 / 0! (1 / 0 => +inf) return $x->binf(); } my $new_sign = '+'; $new_sign = $MBI->_is_odd($y1) ? '-' : '+' if $x->{sign} ne '+'; # calculate $x->{_m} ** $y and $x->{_e} * $y separately (faster) $x->{_m} = $MBI->_pow($x->{_m}, $y1); $x->{_e} = $MBI->_mul ($x->{_e}, $y1); $x->{sign} = $new_sign; $x->bnorm(); if ($y->{sign} eq '-') { # modify $x in place! my $z = $x->copy(); $x->bone(); return scalar $x->bdiv($z, $a, $p, $r); # round in one go (might ignore y's A!) } $x->round($a, $p, $r, $y); } sub blog { # Return the logarithm of the operand. If a second operand is defined, that # value is used as the base, otherwise the base is assumed to be Euler's # constant. my ($class, $x, $base, $a, $p, $r); # Don't objectify the base, since an undefined base, as in $x->blog() or # $x->blog(undef) signals that the base is Euler's number. if (!ref($_[0]) && $_[0] =~ /^[A-Za-z]|::/) { # E.g., Math::BigFloat->blog(256, 2) ($class, $x, $base, $a, $p, $r) = defined $_[2] ? objectify(2, @_) : objectify(1, @_); } else { # E.g., Math::BigFloat::blog(256, 2) or $x->blog(2) ($class, $x, $base, $a, $p, $r) = defined $_[1] ? objectify(2, @_) : objectify(1, @_); } return $x if $x->modify('blog'); return $x -> bnan() if $x -> is_nan(); # we need to limit the accuracy to protect against overflow my $fallback = 0; my ($scale, @params); ($x, @params) = $x->_find_round_parameters($a, $p, $r); # no rounding at all, so must use fallback if (scalar @params == 0) { # simulate old behaviour $params[0] = $class->div_scale(); # and round to it as accuracy $params[1] = undef; # P = undef $scale = $params[0]+4; # at least four more for proper round $params[2] = $r; # round mode by caller or undef $fallback = 1; # to clear a/p afterwards } else { # the 4 below is empirical, and there might be cases where it is not # enough... $scale = abs($params[0] || $params[1]) + 4; # take whatever is defined } my $done = 0; if (defined $base) { $base = $class -> new($base) unless ref $base; if ($base -> is_nan() || $base -> is_one()) { $x -> bnan(); $done = 1; } elsif ($base -> is_inf() || $base -> is_zero()) { if ($x -> is_inf() || $x -> is_zero()) { $x -> bnan(); } else { $x -> bzero(@params); } $done = 1; } elsif ($base -> is_negative()) { # -inf < base < 0 if ($x -> is_one()) { # x = 1 $x -> bzero(@params); } elsif ($x == $base) { $x -> bone('+', @params); # x = base } else { $x -> bnan(); # otherwise } $done = 1; } elsif ($x == $base) { $x -> bone('+', @params); # 0 < base && 0 < x < inf $done = 1; } } # We now know that the base is either undefined or positive and finite. unless ($done) { if ($x -> is_inf()) { # x = +/-inf my $sign = defined $base && $base < 1 ? '-' : '+'; $x -> binf($sign); $done = 1; } elsif ($x -> is_neg()) { # -inf < x < 0 $x -> bnan(); $done = 1; } elsif ($x -> is_one()) { # x = 1 $x -> bzero(@params); $done = 1; } elsif ($x -> is_zero()) { # x = 0 my $sign = defined $base && $base < 1 ? '+' : '-'; $x -> binf($sign); $done = 1; } } if ($done) { if ($fallback) { # clear a/p after round, since user did not request it delete $x->{_a}; delete $x->{_p}; } return $x; } # when user set globals, they would interfere with our calculation, so # disable them and later re-enable them no strict 'refs'; my $abr = "$class\::accuracy"; my $ab = $$abr; $$abr = undef; my $pbr = "$class\::precision"; my $pb = $$pbr; $$pbr = undef; # we also need to disable any set A or P on $x (_find_round_parameters took # them already into account), since these would interfere, too delete $x->{_a}; delete $x->{_p}; # need to disable $upgrade in BigInt, to avoid deep recursion local $Math::BigInt::upgrade = undef; local $Math::BigFloat::downgrade = undef; # upgrade $x if $x is not a Math::BigFloat (handle BigInt input) # XXX TODO: rebless! if (!$x->isa('Math::BigFloat')) { $x = Math::BigFloat->new($x); $class = ref($x); } $done = 0; # If the base is defined and an integer, try to calculate integer result # first. This is very fast, and in case the real result was found, we can # stop right here. if (defined $base && $base->is_int() && $x->is_int()) { my $i = $MBI->_copy($x->{_m}); $i = $MBI->_lsft($i, $x->{_e}, 10) unless $MBI->_is_zero($x->{_e}); my $int = Math::BigInt->bzero(); $int->{value} = $i; $int->blog($base->as_number()); # if ($exact) if ($base->as_number()->bpow($int) == $x) { # found result, return it $x->{_m} = $int->{value}; $x->{_e} = $MBI->_zero(); $x->{_es} = '+'; $x->bnorm(); $done = 1; } } if ($done == 0) { # base is undef, so base should be e (Euler's number), so first calculate the # log to base e (using reduction by 10 (and probably 2)): $class->_log_10($x, $scale); # and if a different base was requested, convert it if (defined $base) { $base = Math::BigFloat->new($base) unless $base->isa('Math::BigFloat'); # not ln, but some other base (don't modify $base) $x->bdiv($base->copy()->blog(undef, $scale), $scale); } } # shortcut to not run through _find_round_parameters again if (defined $params[0]) { $x->bround($params[0], $params[2]); # then round accordingly } else { $x->bfround($params[1], $params[2]); # then round accordingly } if ($fallback) { # clear a/p after round, since user did not request it delete $x->{_a}; delete $x->{_p}; } # restore globals $$abr = $ab; $$pbr = $pb; $x; } sub bexp { # Calculate e ** X (Euler's number to the power of X) my ($class, $x, $a, $p, $r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_); return $x if $x->modify('bexp'); return $x->binf() if $x->{sign} eq '+inf'; return $x->bzero() if $x->{sign} eq '-inf'; # we need to limit the accuracy to protect against overflow my $fallback = 0; my ($scale, @params); ($x, @params) = $x->_find_round_parameters($a, $p, $r); # also takes care of the "error in _find_round_parameters?" case return $x if $x->{sign} eq 'NaN'; # no rounding at all, so must use fallback if (scalar @params == 0) { # simulate old behaviour $params[0] = $class->div_scale(); # and round to it as accuracy $params[1] = undef; # P = undef $scale = $params[0]+4; # at least four more for proper round $params[2] = $r; # round mode by caller or undef $fallback = 1; # to clear a/p afterwards } else { # the 4 below is empirical, and there might be cases where it's not enough... $scale = abs($params[0] || $params[1]) + 4; # take whatever is defined } return $x->bone(@params) if $x->is_zero(); if (!$x->isa('Math::BigFloat')) { $x = Math::BigFloat->new($x); $class = ref($x); } # when user set globals, they would interfere with our calculation, so # disable them and later re-enable them no strict 'refs'; my $abr = "$class\::accuracy"; my $ab = $$abr; $$abr = undef; my $pbr = "$class\::precision"; my $pb = $$pbr; $$pbr = undef; # we also need to disable any set A or P on $x (_find_round_parameters took # them already into account), since these would interfere, too delete $x->{_a}; delete $x->{_p}; # need to disable $upgrade in BigInt, to avoid deep recursion local $Math::BigInt::upgrade = undef; local $Math::BigFloat::downgrade = undef; my $x_org = $x->copy(); # We use the following Taylor series: # x x^2 x^3 x^4 # e = 1 + --- + --- + --- + --- ... # 1! 2! 3! 4! # The difference for each term is X and N, which would result in: # 2 copy, 2 mul, 2 add, 1 inc, 1 div operations per term # But it is faster to compute exp(1) and then raising it to the # given power, esp. if $x is really big and an integer because: # * The numerator is always 1, making the computation faster # * the series converges faster in the case of x == 1 # * We can also easily check when we have reached our limit: when the # term to be added is smaller than "1E$scale", we can stop - f.i. # scale == 5, and we have 1/40320, then we stop since 1/40320 < 1E-5. # * we can compute the *exact* result by simulating bigrat math: # 1 1 gcd(3, 4) = 1 1*24 + 1*6 5 # - + - = ---------- = -- # 6 24 6*24 24 # We do not compute the gcd() here, but simple do: # 1 1 1*24 + 1*6 30 # - + - = --------- = -- # 6 24 6*24 144 # In general: # a c a*d + c*b and note that c is always 1 and d = (b*f) # - + - = --------- # b d b*d # This leads to: which can be reduced by b to: # a 1 a*b*f + b a*f + 1 # - + - = --------- = ------- # b b*f b*b*f b*f # The first terms in the series are: # 1 1 1 1 1 1 1 1 13700 # -- + -- + -- + -- + -- + --- + --- + ---- = ----- # 1 1 2 6 24 120 720 5040 5040 # Note that we cannot simple reduce 13700/5040 to 685/252, but must keep A and B! if ($scale <= 75) { # set $x directly from a cached string form $x->{_m} = $MBI->_new( "27182818284590452353602874713526624977572470936999595749669676277240766303535476"); $x->{sign} = '+'; $x->{_es} = '-'; $x->{_e} = $MBI->_new(79); } else { # compute A and B so that e = A / B. # After some terms we end up with this, so we use it as a starting point: my $A = $MBI->_new("90933395208605785401971970164779391644753259799242"); my $F = $MBI->_new(42); my $step = 42; # Compute how many steps we need to take to get $A and $B sufficiently big my $steps = _len_to_steps($scale - 4); # print STDERR "# Doing $steps steps for ", $scale-4, " digits\n"; while ($step++ <= $steps) { # calculate $a * $f + 1 $A = $MBI->_mul($A, $F); $A = $MBI->_inc($A); # increment f $F = $MBI->_inc($F); } # compute $B as factorial of $steps (this is faster than doing it manually) my $B = $MBI->_fac($MBI->_new($steps)); # print "A ", $MBI->_str($A), "\nB ", $MBI->_str($B), "\n"; # compute A/B with $scale digits in the result (truncate, not round) $A = $MBI->_lsft($A, $MBI->_new($scale), 10); $A = $MBI->_div($A, $B); $x->{_m} = $A; $x->{sign} = '+'; $x->{_es} = '-'; $x->{_e} = $MBI->_new($scale); } # $x contains now an estimate of e, with some surplus digits, so we can round if (!$x_org->is_one()) { # Reduce size of fractional part, followup with integer power of two. my $lshift = 0; while ($lshift < 30 && $x_org->bacmp(2 << $lshift) > 0) { $lshift++; } # Raise $x to the wanted power and round it. if ($lshift == 0) { $x->bpow($x_org, @params); } else { my($mul, $rescale) = (1 << $lshift, $scale+1+$lshift); $x->bpow(scalar $x_org->bdiv($mul, $rescale), $rescale)->bpow($mul, @params); } } else { # else just round the already computed result delete $x->{_a}; delete $x->{_p}; # shortcut to not run through _find_round_parameters again if (defined $params[0]) { $x->bround($params[0], $params[2]); # then round accordingly } else { $x->bfround($params[1], $params[2]); # then round accordingly } } if ($fallback) { # clear a/p after round, since user did not request it delete $x->{_a}; delete $x->{_p}; } # restore globals $$abr = $ab; $$pbr = $pb; $x; # return modified $x } sub bnok { # Calculate n over k (binomial coefficient or "choose" function) as integer. # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } return $x if $x->modify('bnok'); return $x->bnan() if $x->is_nan() || $y->is_nan(); return $x->binf() if $x->is_inf(); my $u = $x->as_int(); $u->bnok($y->as_int()); $x->{_m} = $u->{value}; $x->{_e} = $MBI->_zero(); $x->{_es} = '+'; $x->{sign} = '+'; $x->bnorm(@r); } sub bsin { # Calculate a sinus of x. my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_); # taylor: x^3 x^5 x^7 x^9 # sin = x - --- + --- - --- + --- ... # 3! 5! 7! 9! # we need to limit the accuracy to protect against overflow my $fallback = 0; my ($scale, @params); ($x, @params) = $x->_find_round_parameters(@r); # constant object or error in _find_round_parameters? return $x if $x->modify('bsin') || $x->is_nan(); return $x->bzero(@r) if $x->is_zero(); # no rounding at all, so must use fallback if (scalar @params == 0) { # simulate old behaviour $params[0] = $class->div_scale(); # and round to it as accuracy $params[1] = undef; # disable P $scale = $params[0]+4; # at least four more for proper round $params[2] = $r[2]; # round mode by caller or undef $fallback = 1; # to clear a/p afterwards } else { # the 4 below is empirical, and there might be cases where it is not # enough... $scale = abs($params[0] || $params[1]) + 4; # take whatever is defined } # when user set globals, they would interfere with our calculation, so # disable them and later re-enable them no strict 'refs'; my $abr = "$class\::accuracy"; my $ab = $$abr; $$abr = undef; my $pbr = "$class\::precision"; my $pb = $$pbr; $$pbr = undef; # we also need to disable any set A or P on $x (_find_round_parameters took # them already into account), since these would interfere, too delete $x->{_a}; delete $x->{_p}; # need to disable $upgrade in BigInt, to avoid deep recursion local $Math::BigInt::upgrade = undef; my $last = 0; my $over = $x * $x; # X ^ 2 my $x2 = $over->copy(); # X ^ 2; difference between terms $over->bmul($x); # X ^ 3 as starting value my $sign = 1; # start with -= my $below = $class->new(6); my $factorial = $class->new(4); delete $x->{_a}; delete $x->{_p}; my $limit = $class->new("1E-". ($scale-1)); #my $steps = 0; while (3 < 5) { # we calculate the next term, and add it to the last # when the next term is below our limit, it won't affect the outcome # anymore, so we stop: my $next = $over->copy()->bdiv($below, $scale); last if $next->bacmp($limit) <= 0; if ($sign == 0) { $x->badd($next); } else { $x->bsub($next); } $sign = 1-$sign; # alternate # calculate things for the next term $over->bmul($x2); # $x*$x $below->bmul($factorial); $factorial->binc(); # n*(n+1) $below->bmul($factorial); $factorial->binc(); # n*(n+1) } # shortcut to not run through _find_round_parameters again if (defined $params[0]) { $x->bround($params[0], $params[2]); # then round accordingly } else { $x->bfround($params[1], $params[2]); # then round accordingly } if ($fallback) { # clear a/p after round, since user did not request it delete $x->{_a}; delete $x->{_p}; } # restore globals $$abr = $ab; $$pbr = $pb; $x; } sub bcos { # Calculate a cosinus of x. my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_); # Taylor: x^2 x^4 x^6 x^8 # cos = 1 - --- + --- - --- + --- ... # 2! 4! 6! 8! # we need to limit the accuracy to protect against overflow my $fallback = 0; my ($scale, @params); ($x, @params) = $x->_find_round_parameters(@r); # constant object or error in _find_round_parameters? return $x if $x->modify('bcos') || $x->is_nan(); return $x->bone(@r) if $x->is_zero(); # no rounding at all, so must use fallback if (scalar @params == 0) { # simulate old behaviour $params[0] = $class->div_scale(); # and round to it as accuracy $params[1] = undef; # disable P $scale = $params[0]+4; # at least four more for proper round $params[2] = $r[2]; # round mode by caller or undef $fallback = 1; # to clear a/p afterwards } else { # the 4 below is empirical, and there might be cases where it is not # enough... $scale = abs($params[0] || $params[1]) + 4; # take whatever is defined } # when user set globals, they would interfere with our calculation, so # disable them and later re-enable them no strict 'refs'; my $abr = "$class\::accuracy"; my $ab = $$abr; $$abr = undef; my $pbr = "$class\::precision"; my $pb = $$pbr; $$pbr = undef; # we also need to disable any set A or P on $x (_find_round_parameters took # them already into account), since these would interfere, too delete $x->{_a}; delete $x->{_p}; # need to disable $upgrade in BigInt, to avoid deep recursion local $Math::BigInt::upgrade = undef; my $last = 0; my $over = $x * $x; # X ^ 2 my $x2 = $over->copy(); # X ^ 2; difference between terms my $sign = 1; # start with -= my $below = $class->new(2); my $factorial = $class->new(3); $x->bone(); delete $x->{_a}; delete $x->{_p}; my $limit = $class->new("1E-". ($scale-1)); #my $steps = 0; while (3 < 5) { # we calculate the next term, and add it to the last # when the next term is below our limit, it won't affect the outcome # anymore, so we stop: my $next = $over->copy()->bdiv($below, $scale); last if $next->bacmp($limit) <= 0; if ($sign == 0) { $x->badd($next); } else { $x->bsub($next); } $sign = 1-$sign; # alternate # calculate things for the next term $over->bmul($x2); # $x*$x $below->bmul($factorial); $factorial->binc(); # n*(n+1) $below->bmul($factorial); $factorial->binc(); # n*(n+1) } # shortcut to not run through _find_round_parameters again if (defined $params[0]) { $x->bround($params[0], $params[2]); # then round accordingly } else { $x->bfround($params[1], $params[2]); # then round accordingly } if ($fallback) { # clear a/p after round, since user did not request it delete $x->{_a}; delete $x->{_p}; } # restore globals $$abr = $ab; $$pbr = $pb; $x; } sub batan { # Calculate a arcus tangens of x. my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; my (@r) = @_; # taylor: x^3 x^5 x^7 x^9 # atan = x - --- + --- - --- + --- ... # 3 5 7 9 # We need to limit the accuracy to protect against overflow. my $fallback = 0; my ($scale, @params); ($self, @params) = $self->_find_round_parameters(@r); # Constant object or error in _find_round_parameters? return $self if $self->modify('batan') || $self->is_nan(); if ($self->{sign} =~ /^[+-]inf\z/) { # +inf result is PI/2 # -inf result is -PI/2 # calculate PI/2 my $pi = $class->bpi(@r); # modify $self in place $self->{_m} = $pi->{_m}; $self->{_e} = $pi->{_e}; $self->{_es} = $pi->{_es}; # -y => -PI/2, +y => PI/2 $self->{sign} = substr($self->{sign}, 0, 1); # "+inf" => "+" $self -> {_m} = $MBI->_div($self->{_m}, $MBI->_new(2)); return $self; } return $self->bzero(@r) if $self->is_zero(); # no rounding at all, so must use fallback if (scalar @params == 0) { # simulate old behaviour $params[0] = $class->div_scale(); # and round to it as accuracy $params[1] = undef; # disable P $scale = $params[0]+4; # at least four more for proper round $params[2] = $r[2]; # round mode by caller or undef $fallback = 1; # to clear a/p afterwards } else { # the 4 below is empirical, and there might be cases where it is not # enough... $scale = abs($params[0] || $params[1]) + 4; # take whatever is defined } # 1 or -1 => PI/4 # inlined is_one() && is_one('-') if ($MBI->_is_one($self->{_m}) && $MBI->_is_zero($self->{_e})) { my $pi = $class->bpi($scale - 3); # modify $self in place $self->{_m} = $pi->{_m}; $self->{_e} = $pi->{_e}; $self->{_es} = $pi->{_es}; # leave the sign of $self alone (+1 => +PI/4, -1 => -PI/4) $self->{_m} = $MBI->_div($self->{_m}, $MBI->_new(4)); return $self; } # This series is only valid if -1 < x < 1, so for other x we need to # calculate PI/2 - atan(1/x): my $one = $MBI->_new(1); my $pi = undef; if ($self->bacmp($self->copy()->bone) >= 0) { # calculate PI/2 $pi = $class->bpi($scale - 3); $pi->{_m} = $MBI->_div($pi->{_m}, $MBI->_new(2)); # calculate 1/$self: my $self_copy = $self->copy(); # modify $self in place $self->bone(); $self->bdiv($self_copy, $scale); } my $fmul = 1; foreach my $k (0 .. int($scale / 20)) { $fmul *= 2; $self->bdiv($self->copy()->bmul($self)->binc->bsqrt($scale + 4)->binc, $scale + 4); } # When user set globals, they would interfere with our calculation, so # disable them and later re-enable them. no strict 'refs'; my $abr = "$class\::accuracy"; my $ab = $$abr; $$abr = undef; my $pbr = "$class\::precision"; my $pb = $$pbr; $$pbr = undef; # We also need to disable any set A or P on $self (_find_round_parameters # took them already into account), since these would interfere, too delete $self->{_a}; delete $self->{_p}; # Need to disable $upgrade in BigInt, to avoid deep recursion. local $Math::BigInt::upgrade = undef; my $last = 0; my $over = $self * $self; # X ^ 2 my $self2 = $over->copy(); # X ^ 2; difference between terms $over->bmul($self); # X ^ 3 as starting value my $sign = 1; # start with -= my $below = $class->new(3); my $two = $class->new(2); delete $self->{_a}; delete $self->{_p}; my $limit = $class->new("1E-". ($scale-1)); #my $steps = 0; while (1) { # We calculate the next term, and add it to the last. When the next # term is below our limit, it won't affect the outcome anymore, so we # stop: my $next = $over->copy()->bdiv($below, $scale); last if $next->bacmp($limit) <= 0; if ($sign == 0) { $self->badd($next); } else { $self->bsub($next); } $sign = 1-$sign; # alternatex # calculate things for the next term $over->bmul($self2); # $self*$self $below->badd($two); # n += 2 } $self->bmul($fmul); if (defined $pi) { my $self_copy = $self->copy(); # modify $self in place $self->{_m} = $pi->{_m}; $self->{_e} = $pi->{_e}; $self->{_es} = $pi->{_es}; # PI/2 - $self $self->bsub($self_copy); } # Shortcut to not run through _find_round_parameters again. if (defined $params[0]) { $self->bround($params[0], $params[2]); # then round accordingly } else { $self->bfround($params[1], $params[2]); # then round accordingly } if ($fallback) { # Clear a/p after round, since user did not request it. delete $self->{_a}; delete $self->{_p}; } # restore globals $$abr = $ab; $$pbr = $pb; $self; } sub batan2 { # $y -> batan2($x) returns the arcus tangens of $y / $x. # Set up parameters. my ($class, $y, $x, @r) = (ref($_[0]), @_); # Objectify is costly, so avoid it if we can. if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $y, $x, @r) = objectify(2, @_); } # Quick exit if $y is read-only. return $y if $y -> modify('batan2'); # Handle all NaN cases. return $y -> bnan() if $x->{sign} eq $nan || $y->{sign} eq $nan; # We need to limit the accuracy to protect against overflow. my $fallback = 0; my ($scale, @params); ($y, @params) = $y -> _find_round_parameters(@r); # Error in _find_round_parameters? return $y if $y->is_nan(); # No rounding at all, so must use fallback. if (scalar @params == 0) { # Simulate old behaviour $params[0] = $class -> div_scale(); # and round to it as accuracy $params[1] = undef; # disable P $scale = $params[0] + 4; # at least four more for proper round $params[2] = $r[2]; # round mode by caller or undef $fallback = 1; # to clear a/p afterwards } else { # The 4 below is empirical, and there might be cases where it is not # enough ... $scale = abs($params[0] || $params[1]) + 4; # take whatever is defined } if ($x -> is_inf("+")) { # x = inf if ($y -> is_inf("+")) { # y = inf $y -> bpi($scale) -> bmul("0.25"); # pi/4 } elsif ($y -> is_inf("-")) { # y = -inf $y -> bpi($scale) -> bmul("-0.25"); # -pi/4 } else { # -inf < y < inf return $y -> bzero(@r); # 0 } } elsif ($x -> is_inf("-")) { # x = -inf if ($y -> is_inf("+")) { # y = inf $y -> bpi($scale) -> bmul("0.75"); # 3/4 pi } elsif ($y -> is_inf("-")) { # y = -inf $y -> bpi($scale) -> bmul("-0.75"); # -3/4 pi } elsif ($y >= 0) { # y >= 0 $y -> bpi($scale); # pi } else { # y < 0 $y -> bpi($scale) -> bneg(); # -pi } } elsif ($x > 0) { # 0 < x < inf if ($y -> is_inf("+")) { # y = inf $y -> bpi($scale) -> bmul("0.5"); # pi/2 } elsif ($y -> is_inf("-")) { # y = -inf $y -> bpi($scale) -> bmul("-0.5"); # -pi/2 } else { # -inf < y < inf $y -> bdiv($x, $scale) -> batan($scale); # atan(y/x) } } elsif ($x < 0) { # -inf < x < 0 my $pi = $class -> bpi($scale); if ($y >= 0) { # y >= 0 $y -> bdiv($x, $scale) -> batan() # atan(y/x) + pi -> badd($pi); } else { # y < 0 $y -> bdiv($x, $scale) -> batan() # atan(y/x) - pi -> bsub($pi); } } else { # x = 0 if ($y > 0) { # y > 0 $y -> bpi($scale) -> bmul("0.5"); # pi/2 } elsif ($y < 0) { # y < 0 $y -> bpi($scale) -> bmul("-0.5"); # -pi/2 } else { # y = 0 return $y -> bzero(@r); # 0 } } $y -> round(@r); if ($fallback) { delete $y->{_a}; delete $y->{_p}; } return $y; } ############################################################################## sub bsqrt { # calculate square root my ($class, $x, $a, $p, $r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_); return $x if $x->modify('bsqrt'); return $x->bnan() if $x->{sign} !~ /^[+]/; # NaN, -inf or < 0 return $x if $x->{sign} eq '+inf'; # sqrt(inf) == inf return $x->round($a, $p, $r) if $x->is_zero() || $x->is_one(); # we need to limit the accuracy to protect against overflow my $fallback = 0; my (@params, $scale); ($x, @params) = $x->_find_round_parameters($a, $p, $r); return $x if $x->is_nan(); # error in _find_round_parameters? # no rounding at all, so must use fallback if (scalar @params == 0) { # simulate old behaviour $params[0] = $class->div_scale(); # and round to it as accuracy $scale = $params[0]+4; # at least four more for proper round $params[2] = $r; # round mode by caller or undef $fallback = 1; # to clear a/p afterwards } else { # the 4 below is empirical, and there might be cases where it is not # enough... $scale = abs($params[0] || $params[1]) + 4; # take whatever is defined } # when user set globals, they would interfere with our calculation, so # disable them and later re-enable them no strict 'refs'; my $abr = "$class\::accuracy"; my $ab = $$abr; $$abr = undef; my $pbr = "$class\::precision"; my $pb = $$pbr; $$pbr = undef; # we also need to disable any set A or P on $x (_find_round_parameters took # them already into account), since these would interfere, too delete $x->{_a}; delete $x->{_p}; # need to disable $upgrade in BigInt, to avoid deep recursion local $Math::BigInt::upgrade = undef; # should be really parent class vs MBI my $i = $MBI->_copy($x->{_m}); $i = $MBI->_lsft($i, $x->{_e}, 10) unless $MBI->_is_zero($x->{_e}); my $xas = Math::BigInt->bzero(); $xas->{value} = $i; my $gs = $xas->copy()->bsqrt(); # some guess if (($x->{_es} ne '-') # guess can't be accurate if there are # digits after the dot && ($xas->bacmp($gs * $gs) == 0)) # guess hit the nail on the head? { # exact result, copy result over to keep $x $x->{_m} = $gs->{value}; $x->{_e} = $MBI->_zero(); $x->{_es} = '+'; $x->bnorm(); # shortcut to not run through _find_round_parameters again if (defined $params[0]) { $x->bround($params[0], $params[2]); # then round accordingly } else { $x->bfround($params[1], $params[2]); # then round accordingly } if ($fallback) { # clear a/p after round, since user did not request it delete $x->{_a}; delete $x->{_p}; } # re-enable A and P, upgrade is taken care of by "local" ${"$class\::accuracy"} = $ab; ${"$class\::precision"} = $pb; return $x; } # sqrt(2) = 1.4 because sqrt(2*100) = 1.4*10; so we can increase the accuracy # of the result by multiplying the input by 100 and then divide the integer # result of sqrt(input) by 10. Rounding afterwards returns the real result. # The following steps will transform 123.456 (in $x) into 123456 (in $y1) my $y1 = $MBI->_copy($x->{_m}); my $length = $MBI->_len($y1); # Now calculate how many digits the result of sqrt(y1) would have my $digits = int($length / 2); # But we need at least $scale digits, so calculate how many are missing my $shift = $scale - $digits; # This happens if the input had enough digits # (we take care of integer guesses above) $shift = 0 if $shift < 0; # Multiply in steps of 100, by shifting left two times the "missing" digits my $s2 = $shift * 2; # We now make sure that $y1 has the same odd or even number of digits than # $x had. So when _e of $x is odd, we must shift $y1 by one digit left, # because we always must multiply by steps of 100 (sqrt(100) is 10) and not # steps of 10. The length of $x does not count, since an even or odd number # of digits before the dot is not changed by adding an even number of digits # after the dot (the result is still odd or even digits long). $s2++ if $MBI->_is_odd($x->{_e}); $y1 = $MBI->_lsft($y1, $MBI->_new($s2), 10); # now take the square root and truncate to integer $y1 = $MBI->_sqrt($y1); # By "shifting" $y1 right (by creating a negative _e) we calculate the final # result, which is than later rounded to the desired scale. # calculate how many zeros $x had after the '.' (or before it, depending # on sign of $dat, the result should have half as many: my $dat = $MBI->_num($x->{_e}); $dat = -$dat if $x->{_es} eq '-'; $dat += $length; if ($dat > 0) { # no zeros after the dot (e.g. 1.23, 0.49 etc) # preserve half as many digits before the dot than the input had # (but round this "up") $dat = int(($dat+1)/2); } else { $dat = int(($dat)/2); } $dat -= $MBI->_len($y1); if ($dat < 0) { $dat = abs($dat); $x->{_e} = $MBI->_new($dat); $x->{_es} = '-'; } else { $x->{_e} = $MBI->_new($dat); $x->{_es} = '+'; } $x->{_m} = $y1; $x->bnorm(); # shortcut to not run through _find_round_parameters again if (defined $params[0]) { $x->bround($params[0], $params[2]); # then round accordingly } else { $x->bfround($params[1], $params[2]); # then round accordingly } if ($fallback) { # clear a/p after round, since user did not request it delete $x->{_a}; delete $x->{_p}; } # restore globals $$abr = $ab; $$pbr = $pb; $x; } sub broot { # calculate $y'th root of $x # set up parameters my ($class, $x, $y, $a, $p, $r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, $a, $p, $r) = objectify(2, @_); } return $x if $x->modify('broot'); # NaN handling: $x ** 1/0, x or y NaN, or y inf/-inf or y == 0 return $x->bnan() if $x->{sign} !~ /^\+/ || $y->is_zero() || $y->{sign} !~ /^\+$/; return $x if $x->is_zero() || $x->is_one() || $x->is_inf() || $y->is_one(); # we need to limit the accuracy to protect against overflow my $fallback = 0; my (@params, $scale); ($x, @params) = $x->_find_round_parameters($a, $p, $r); return $x if $x->is_nan(); # error in _find_round_parameters? # no rounding at all, so must use fallback if (scalar @params == 0) { # simulate old behaviour $params[0] = $class->div_scale(); # and round to it as accuracy $scale = $params[0]+4; # at least four more for proper round $params[2] = $r; # round mode by caller or undef $fallback = 1; # to clear a/p afterwards } else { # the 4 below is empirical, and there might be cases where it is not # enough... $scale = abs($params[0] || $params[1]) + 4; # take whatever is defined } # when user set globals, they would interfere with our calculation, so # disable them and later re-enable them no strict 'refs'; my $abr = "$class\::accuracy"; my $ab = $$abr; $$abr = undef; my $pbr = "$class\::precision"; my $pb = $$pbr; $$pbr = undef; # we also need to disable any set A or P on $x (_find_round_parameters took # them already into account), since these would interfere, too delete $x->{_a}; delete $x->{_p}; # need to disable $upgrade in BigInt, to avoid deep recursion local $Math::BigInt::upgrade = undef; # should be really parent class vs MBI # remember sign and make $x positive, since -4 ** (1/2) => -2 my $sign = 0; $sign = 1 if $x->{sign} eq '-'; $x->{sign} = '+'; my $is_two = 0; if ($y->isa('Math::BigFloat')) { $is_two = ($y->{sign} eq '+' && $MBI->_is_two($y->{_m}) && $MBI->_is_zero($y->{_e})); } else { $is_two = ($y == 2); } # normal square root if $y == 2: if ($is_two) { $x->bsqrt($scale+4); } elsif ($y->is_one('-')) { # $x ** -1 => 1/$x my $u = $class->bone()->bdiv($x, $scale); # copy private parts over $x->{_m} = $u->{_m}; $x->{_e} = $u->{_e}; $x->{_es} = $u->{_es}; } else { # calculate the broot() as integer result first, and if it fits, return # it rightaway (but only if $x and $y are integer): my $done = 0; # not yet if ($y->is_int() && $x->is_int()) { my $i = $MBI->_copy($x->{_m}); $i = $MBI->_lsft($i, $x->{_e}, 10) unless $MBI->_is_zero($x->{_e}); my $int = Math::BigInt->bzero(); $int->{value} = $i; $int->broot($y->as_number()); # if ($exact) if ($int->copy()->bpow($y) == $x) { # found result, return it $x->{_m} = $int->{value}; $x->{_e} = $MBI->_zero(); $x->{_es} = '+'; $x->bnorm(); $done = 1; } } if ($done == 0) { my $u = $class->bone()->bdiv($y, $scale+4); delete $u->{_a}; delete $u->{_p}; # otherwise it conflicts $x->bpow($u, $scale+4); # el cheapo } } $x->bneg() if $sign == 1; # shortcut to not run through _find_round_parameters again if (defined $params[0]) { $x->bround($params[0], $params[2]); # then round accordingly } else { $x->bfround($params[1], $params[2]); # then round accordingly } if ($fallback) { # clear a/p after round, since user did not request it delete $x->{_a}; delete $x->{_p}; } # restore globals $$abr = $ab; $$pbr = $pb; $x; } sub bfac { # (BFLOAT or num_str, BFLOAT or num_str) return BFLOAT # compute factorial number, modifies first argument # set up parameters my ($class, $x, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it ($class, $x, @r) = objectify(1, @_) if !ref($x); # inf => inf return $x if $x->modify('bfac') || $x->{sign} eq '+inf'; return $x->bnan() if (($x->{sign} ne '+') || # inf, NaN, <0 etc => NaN ($x->{_es} ne '+')); # digits after dot? if (! $MBI->_is_zero($x->{_e})) { $x->{_m} = $MBI->_lsft($x->{_m}, $x->{_e}, 10); # change 12e1 to 120e0 $x->{_e} = $MBI->_zero(); # normalize $x->{_es} = '+'; } $x->{_m} = $MBI->_fac($x->{_m}); # calculate factorial $x->bnorm()->round(@r); # norm again and round result } sub bdfac { # compute double factorial # set up parameters my ($class, $x, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it ($class, $x, @r) = objectify(1, @_) if !ref($x); # inf => inf return $x if $x->modify('bfac') || $x->{sign} eq '+inf'; return $x->bnan() if (($x->{sign} ne '+') || # inf, NaN, <0 etc => NaN ($x->{_es} ne '+')); # digits after dot? Carp::croak("bdfac() requires a newer version of the $MBI library.") unless $MBI->can('_dfac'); if (! $MBI->_is_zero($x->{_e})) { $x->{_m} = $MBI->_lsft($x->{_m}, $x->{_e}, 10); # change 12e1 to 120e0 $x->{_e} = $MBI->_zero(); # normalize $x->{_es} = '+'; } $x->{_m} = $MBI->_dfac($x->{_m}); # calculate factorial $x->bnorm()->round(@r); # norm again and round result } sub blsft { # shift left by $y (multiply by $b ** $y) # set up parameters my ($class, $x, $y, $b, $a, $p, $r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, $b, $a, $p, $r) = objectify(2, @_); } return $x if $x -> modify('blsft'); return $x if $x -> {sign} !~ /^[+-]$/; # nan, +inf, -inf $b = 2 if !defined $b; $b = $class -> new($b) unless ref($b) && $b -> isa($class); return $x -> bnan() if $x -> is_nan() || $y -> is_nan() || $b -> is_nan(); # shift by a negative amount? return $x -> brsft($y -> copy() -> babs(), $b) if $y -> {sign} =~ /^-/; $x -> bmul($b -> bpow($y), $a, $p, $r, $y); } sub brsft { # shift right by $y (divide $b ** $y) # set up parameters my ($class, $x, $y, $b, $a, $p, $r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, $b, $a, $p, $r) = objectify(2, @_); } return $x if $x -> modify('brsft'); return $x if $x -> {sign} !~ /^[+-]$/; # nan, +inf, -inf $b = 2 if !defined $b; $b = $class -> new($b) unless ref($b) && $b -> isa($class); return $x -> bnan() if $x -> is_nan() || $y -> is_nan() || $b -> is_nan(); # shift by a negative amount? return $x -> blsft($y -> copy() -> babs(), $b) if $y -> {sign} =~ /^-/; # the following call to bdiv() will return either quotient (scalar context) # or quotient and remainder (list context). $x -> bdiv($b -> bpow($y), $a, $p, $r, $y); } ############################################################################### # Bitwise methods ############################################################################### sub band { my $x = shift; my $xref = ref($x); my $class = $xref || $x; Carp::croak 'band() is an instance method, not a class method' unless $xref; Carp::croak 'Not enough arguments for band()' if @_ < 1; return if $x -> modify('band'); my $y = shift; $y = $class -> new($y) unless ref($y); my @r = @_; my $xtmp = Math::BigInt -> new($x -> bint()); # to Math::BigInt $xtmp -> band($y); $xtmp = $class -> new($xtmp); # back to Math::BigFloat $x -> {sign} = $xtmp -> {sign}; $x -> {_m} = $xtmp -> {_m}; $x -> {_es} = $xtmp -> {_es}; $x -> {_e} = $xtmp -> {_e}; return $x -> round(@r); } sub bior { my $x = shift; my $xref = ref($x); my $class = $xref || $x; Carp::croak 'bior() is an instance method, not a class method' unless $xref; Carp::croak 'Not enough arguments for bior()' if @_ < 1; return if $x -> modify('bior'); my $y = shift; $y = $class -> new($y) unless ref($y); my @r = @_; my $xtmp = Math::BigInt -> new($x -> bint()); # to Math::BigInt $xtmp -> bior($y); $xtmp = $class -> new($xtmp); # back to Math::BigFloat $x -> {sign} = $xtmp -> {sign}; $x -> {_m} = $xtmp -> {_m}; $x -> {_es} = $xtmp -> {_es}; $x -> {_e} = $xtmp -> {_e}; return $x -> round(@r); } sub bxor { my $x = shift; my $xref = ref($x); my $class = $xref || $x; Carp::croak 'bxor() is an instance method, not a class method' unless $xref; Carp::croak 'Not enough arguments for bxor()' if @_ < 1; return if $x -> modify('bxor'); my $y = shift; $y = $class -> new($y) unless ref($y); my @r = @_; my $xtmp = Math::BigInt -> new($x -> bint()); # to Math::BigInt $xtmp -> bxor($y); $xtmp = $class -> new($xtmp); # back to Math::BigFloat $x -> {sign} = $xtmp -> {sign}; $x -> {_m} = $xtmp -> {_m}; $x -> {_es} = $xtmp -> {_es}; $x -> {_e} = $xtmp -> {_e}; return $x -> round(@r); } sub bnot { my $x = shift; my $xref = ref($x); my $class = $xref || $x; Carp::croak 'bnot() is an instance method, not a class method' unless $xref; return if $x -> modify('bnot'); my @r = @_; my $xtmp = Math::BigInt -> new($x -> bint()); # to Math::BigInt $xtmp -> bnot(); $xtmp = $class -> new($xtmp); # back to Math::BigFloat $x -> {sign} = $xtmp -> {sign}; $x -> {_m} = $xtmp -> {_m}; $x -> {_es} = $xtmp -> {_es}; $x -> {_e} = $xtmp -> {_e}; return $x -> round(@r); } ############################################################################### # Rounding methods ############################################################################### sub bround { # accuracy: preserve $N digits, and overwrite the rest with 0's my $x = shift; my $class = ref($x) || $x; $x = $class->new(shift) if !ref($x); if (($_[0] || 0) < 0) { Carp::croak('bround() needs positive accuracy'); } my ($scale, $mode) = $x->_scale_a(@_); return $x if !defined $scale || $x->modify('bround'); # no-op # scale is now either $x->{_a}, $accuracy, or the user parameter # test whether $x already has lower accuracy, do nothing in this case # but do round if the accuracy is the same, since a math operation might # want to round a number with A=5 to 5 digits afterwards again return $x if defined $x->{_a} && $x->{_a} < $scale; # scale < 0 makes no sense # scale == 0 => keep all digits # never round a +-inf, NaN return $x if ($scale <= 0) || $x->{sign} !~ /^[+-]$/; # 1: never round a 0 # 2: if we should keep more digits than the mantissa has, do nothing if ($x->is_zero() || $MBI->_len($x->{_m}) <= $scale) { $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; return $x; } # pass sign to bround for '+inf' and '-inf' rounding modes my $m = bless { sign => $x->{sign}, value => $x->{_m} }, 'Math::BigInt'; $m->bround($scale, $mode); # round mantissa $x->{_m} = $m->{value}; # get our mantissa back $x->{_a} = $scale; # remember rounding delete $x->{_p}; # and clear P $x->bnorm(); # del trailing zeros gen. by bround() } sub bfround { # precision: round to the $Nth digit left (+$n) or right (-$n) from the '.' # $n == 0 means round to integer # expects and returns normalized numbers! my $x = shift; my $class = ref($x) || $x; $x = $class->new(shift) if !ref($x); my ($scale, $mode) = $x->_scale_p(@_); return $x if !defined $scale || $x->modify('bfround'); # no-op # never round a 0, +-inf, NaN if ($x->is_zero()) { $x->{_p} = $scale if !defined $x->{_p} || $x->{_p} < $scale; # -3 < -2 return $x; } return $x if $x->{sign} !~ /^[+-]$/; # don't round if x already has lower precision return $x if (defined $x->{_p} && $x->{_p} < 0 && $scale < $x->{_p}); $x->{_p} = $scale; # remember round in any case delete $x->{_a}; # and clear A if ($scale < 0) { # round right from the '.' return $x if $x->{_es} eq '+'; # e >= 0 => nothing to round $scale = -$scale; # positive for simplicity my $len = $MBI->_len($x->{_m}); # length of mantissa # the following poses a restriction on _e, but if _e is bigger than a # scalar, you got other problems (memory etc) anyway my $dad = -(0+ ($x->{_es}.$MBI->_num($x->{_e}))); # digits after dot my $zad = 0; # zeros after dot $zad = $dad - $len if (-$dad < -$len); # for 0.00..00xxx style # print "scale $scale dad $dad zad $zad len $len\n"; # number bsstr len zad dad # 0.123 123e-3 3 0 3 # 0.0123 123e-4 3 1 4 # 0.001 1e-3 1 2 3 # 1.23 123e-2 3 0 2 # 1.2345 12345e-4 5 0 4 # do not round after/right of the $dad return $x if $scale > $dad; # 0.123, scale >= 3 => exit # round to zero if rounding inside the $zad, but not for last zero like: # 0.0065, scale -2, round last '0' with following '65' (scale == zad case) return $x->bzero() if $scale < $zad; if ($scale == $zad) # for 0.006, scale -3 and trunc { $scale = -$len; } else { # adjust round-point to be inside mantissa if ($zad != 0) { $scale = $scale-$zad; } else { my $dbd = $len - $dad; $dbd = 0 if $dbd < 0; # digits before dot $scale = $dbd+$scale; } } } else { # round left from the '.' # 123 => 100 means length(123) = 3 - $scale (2) => 1 my $dbt = $MBI->_len($x->{_m}); # digits before dot my $dbd = $dbt + ($x->{_es} . $MBI->_num($x->{_e})); # should be the same, so treat it as this $scale = 1 if $scale == 0; # shortcut if already integer return $x if $scale == 1 && $dbt <= $dbd; # maximum digits before dot ++$dbd; if ($scale > $dbd) { # not enough digits before dot, so round to zero return $x->bzero; } elsif ($scale == $dbd) { # maximum $scale = -$dbt; } else { $scale = $dbd - $scale; } } # pass sign to bround for rounding modes '+inf' and '-inf' my $m = bless { sign => $x->{sign}, value => $x->{_m} }, 'Math::BigInt'; $m->bround($scale, $mode); $x->{_m} = $m->{value}; # get our mantissa back $x->bnorm(); } sub bfloor { # round towards minus infinity my ($class, $x, $a, $p, $r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_); return $x if $x->modify('bfloor'); return $x if $x->{sign} !~ /^[+-]$/; # nan, +inf, -inf # if $x has digits after dot if ($x->{_es} eq '-') { $x->{_m} = $MBI->_rsft($x->{_m}, $x->{_e}, 10); # cut off digits after dot $x->{_e} = $MBI->_zero(); # trunc/norm $x->{_es} = '+'; # abs e $x->{_m} = $MBI->_inc($x->{_m}) if $x->{sign} eq '-'; # increment if negative } $x->round($a, $p, $r); } sub bceil { # round towards plus infinity my ($class, $x, $a, $p, $r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_); return $x if $x->modify('bceil'); return $x if $x->{sign} !~ /^[+-]$/; # nan, +inf, -inf # if $x has digits after dot if ($x->{_es} eq '-') { $x->{_m} = $MBI->_rsft($x->{_m}, $x->{_e}, 10); # cut off digits after dot $x->{_e} = $MBI->_zero(); # trunc/norm $x->{_es} = '+'; # abs e if ($x->{sign} eq '+') { $x->{_m} = $MBI->_inc($x->{_m}); # increment if positive } else { $x->{sign} = '+' if $MBI->_is_zero($x->{_m}); # avoid -0 } } $x->round($a, $p, $r); } sub bint { # round towards zero my ($class, $x, $a, $p, $r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_); return $x if $x->modify('bint'); return $x if $x->{sign} !~ /^[+-]$/; # nan, +inf, -inf # if $x has digits after the decimal point if ($x->{_es} eq '-') { $x->{_m} = $MBI->_rsft($x->{_m}, $x->{_e}, 10); # cut off digits after dot $x->{_e} = $MBI->_zero(); # truncate/normalize $x->{_es} = '+'; # abs e $x->{sign} = '+' if $MBI->_is_zero($x->{_m}); # avoid -0 } $x->round($a, $p, $r); } ############################################################################### # Other mathematical methods ############################################################################### sub bgcd { # (BINT or num_str, BINT or num_str) return BINT # does not modify arguments, but returns new object unshift @_, __PACKAGE__ unless ref($_[0]) || $_[0] =~ /^[a-z]\w*(?:::[a-z]\w*)*$/i; my ($class, @args) = objectify(0, @_); my $x = shift @args; $x = ref($x) && $x -> isa($class) ? $x -> copy() : $class -> new($x); return $class->bnan() unless $x -> is_int(); while (@args) { my $y = shift @args; $y = $class->new($y) unless ref($y) && $y -> isa($class); return $class->bnan() unless $y -> is_int(); # greatest common divisor while (! $y->is_zero()) { ($x, $y) = ($y->copy(), $x->copy()->bmod($y)); } last if $x -> is_one(); } return $x -> babs(); } sub blcm { # (BFLOAT or num_str, BFLOAT or num_str) return BFLOAT # does not modify arguments, but returns new object # Least Common Multiple unshift @_, __PACKAGE__ unless ref($_[0]) || $_[0] =~ /^[a-z]\w*(?:::[a-z]\w*)*$/i; my ($class, @args) = objectify(0, @_); my $x = shift @args; $x = ref($x) && $x -> isa($class) ? $x -> copy() : $class -> new($x); return $class->bnan() if $x->{sign} !~ /^[+-]$/; # x NaN? while (@args) { my $y = shift @args; $y = $class -> new($y) unless ref($y) && $y -> isa($class); return $x->bnan() unless $y -> is_int(); my $gcd = $x -> bgcd($y); $x -> bdiv($gcd) -> bmul($y); } return $x -> babs(); } ############################################################################### # Object property methods ############################################################################### sub length { my $x = shift; my $class = ref($x) || $x; $x = $class->new(shift) unless ref($x); return 1 if $MBI->_is_zero($x->{_m}); my $len = $MBI->_len($x->{_m}); $len += $MBI->_num($x->{_e}) if $x->{_es} eq '+'; if (wantarray()) { my $t = 0; $t = $MBI->_num($x->{_e}) if $x->{_es} eq '-'; return ($len, $t); } $len; } sub mantissa { # return a copy of the mantissa my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_); if ($x->{sign} !~ /^[+-]$/) { my $s = $x->{sign}; $s =~ s/^[+]//; return Math::BigInt->new($s, undef, undef); # -inf, +inf => +inf } my $m = Math::BigInt->new($MBI->_str($x->{_m}), undef, undef); $m->bneg() if $x->{sign} eq '-'; $m; } sub exponent { # return a copy of the exponent my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_); if ($x->{sign} !~ /^[+-]$/) { my $s = $x->{sign}; $s =~ s/^[+-]//; return Math::BigInt->new($s, undef, undef); # -inf, +inf => +inf } Math::BigInt->new($x->{_es} . $MBI->_str($x->{_e}), undef, undef); } sub parts { # return a copy of both the exponent and the mantissa my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_); if ($x->{sign} !~ /^[+-]$/) { my $s = $x->{sign}; $s =~ s/^[+]//; my $se = $s; $se =~ s/^[-]//; return ($class->new($s), $class->new($se)); # +inf => inf and -inf, +inf => inf } my $m = Math::BigInt->bzero(); $m->{value} = $MBI->_copy($x->{_m}); $m->bneg() if $x->{sign} eq '-'; ($m, Math::BigInt->new($x->{_es} . $MBI->_num($x->{_e}))); } sub sparts { my $self = shift; my $class = ref $self; Carp::croak("sparts() is an instance method, not a class method") unless $class; # Not-a-number. if ($self -> is_nan()) { my $mant = $self -> copy(); # mantissa return $mant unless wantarray; # scalar context my $expo = $class -> bnan(); # exponent return ($mant, $expo); # list context } # Infinity. if ($self -> is_inf()) { my $mant = $self -> copy(); # mantissa return $mant unless wantarray; # scalar context my $expo = $class -> binf('+'); # exponent return ($mant, $expo); # list context } # Finite number. my $mant = $class -> bzero(); $mant -> {sign} = $self -> {sign}; $mant -> {_m} = $MBI->_copy($self -> {_m}); return $mant unless wantarray; my $expo = $class -> bzero(); $expo -> {sign} = $self -> {_es}; $expo -> {_m} = $MBI->_copy($self -> {_e}); return ($mant, $expo); } sub nparts { my $self = shift; my $class = ref $self; Carp::croak("nparts() is an instance method, not a class method") unless $class; # Not-a-number. if ($self -> is_nan()) { my $mant = $self -> copy(); # mantissa return $mant unless wantarray; # scalar context my $expo = $class -> bnan(); # exponent return ($mant, $expo); # list context } # Infinity. if ($self -> is_inf()) { my $mant = $self -> copy(); # mantissa return $mant unless wantarray; # scalar context my $expo = $class -> binf('+'); # exponent return ($mant, $expo); # list context } # Finite number. my ($mant, $expo) = $self -> sparts(); if ($mant -> bcmp(0)) { my ($ndigtot, $ndigfrac) = $mant -> length(); my $expo10adj = $ndigtot - $ndigfrac - 1; if ($expo10adj != 0) { my $factor = "1e" . -$expo10adj; $mant -> bmul($factor); return $mant unless wantarray; $expo -> badd($expo10adj); return ($mant, $expo); } } return $mant unless wantarray; return ($mant, $expo); } sub eparts { my $self = shift; my $class = ref $self; Carp::croak("eparts() is an instance method, not a class method") unless $class; # Not-a-number and Infinity. return $self -> sparts() if $self -> is_nan() || $self -> is_inf(); # Finite number. my ($mant, $expo) = $self -> nparts(); my $c = $expo -> copy() -> bmod(3); $mant -> blsft($c, 10); return $mant unless wantarray; $expo -> bsub($c); return ($mant, $expo); } sub dparts { my $self = shift; my $class = ref $self; Carp::croak("dparts() is an instance method, not a class method") unless $class; # Not-a-number and Infinity. if ($self -> is_nan() || $self -> is_inf()) { my $int = $self -> copy(); return $int unless wantarray; my $frc = $class -> bzero(); return ($int, $frc); } my $int = $self -> copy(); my $frc = $class -> bzero(); # If the input has a fraction part. if ($int->{_es} eq '-') { $int->{_m} = $MBI -> _rsft($int->{_m}, $int->{_e}, 10); $int->{_e} = $MBI -> _zero(); $int->{_es} = '+'; $int->{sign} = '+' if $MBI->_is_zero($int->{_m}); # avoid -0 return $int unless wantarray; $frc = $self -> copy() -> bsub($int); return ($int, $frc); } return $int unless wantarray; return ($int, $frc); } ############################################################################### # String conversion methods ############################################################################### sub bstr { # (ref to BFLOAT or num_str) return num_str # Convert number from internal format to (non-scientific) string format. # internal format is always normalized (no leading zeros, "-0" => "+0") my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); if ($x->{sign} !~ /^[+-]$/) { return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN return 'inf'; # +inf } my $es = '0'; my $len = 1; my $cad = 0; my $dot = '.'; # $x is zero? my $not_zero = !($x->{sign} eq '+' && $MBI->_is_zero($x->{_m})); if ($not_zero) { $es = $MBI->_str($x->{_m}); $len = CORE::length($es); my $e = $MBI->_num($x->{_e}); $e = -$e if $x->{_es} eq '-'; if ($e < 0) { $dot = ''; # if _e is bigger than a scalar, the following will blow your memory if ($e <= -$len) { my $r = abs($e) - $len; $es = '0.'. ('0' x $r) . $es; $cad = -($len+$r); } else { substr($es, $e, 0) = '.'; $cad = $MBI->_num($x->{_e}); $cad = -$cad if $x->{_es} eq '-'; } } elsif ($e > 0) { # expand with zeros $es .= '0' x $e; $len += $e; $cad = 0; } } # if not zero $es = '-'.$es if $x->{sign} eq '-'; # if set accuracy or precision, pad with zeros on the right side if ((defined $x->{_a}) && ($not_zero)) { # 123400 => 6, 0.1234 => 4, 0.001234 => 4 my $zeros = $x->{_a} - $cad; # cad == 0 => 12340 $zeros = $x->{_a} - $len if $cad != $len; $es .= $dot.'0' x $zeros if $zeros > 0; } elsif ((($x->{_p} || 0) < 0)) { # 123400 => 6, 0.1234 => 4, 0.001234 => 6 my $zeros = -$x->{_p} + $cad; $es .= $dot.'0' x $zeros if $zeros > 0; } $es; } # Decimal notation, e.g., "12345.6789". sub bdstr { my $x = shift; if ($x->{sign} ne '+' && $x->{sign} ne '-') { return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN return 'inf'; # +inf } my $mant = $MBI->_str($x->{_m}); my $expo = $x -> exponent(); my $str = $mant; if ($expo >= 0) { $str .= "0" x $expo; } else { my $mantlen = CORE::length($mant); my $c = $mantlen + $expo; $str = "0" x (1 - $c) . $str if $c <= 0; substr($str, $expo, 0) = '.'; } return $x->{sign} eq '-' ? "-$str" : $str; } # Scientific notation with significand/mantissa as an integer, e.g., "12345.6789" # is written as "123456789e-4". sub bsstr { my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); if ($x->{sign} ne '+' && $x->{sign} ne '-') { return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN return 'inf'; # +inf } my $str = $MBI->_str($x->{_m}) . 'e' . $x->{_es}. $MBI->_str($x->{_e}); return $x->{sign} eq '-' ? "-$str" : $str; } # Normalized notation, e.g., "12345.6789" is written as "1.23456789e+4". sub bnstr { my $x = shift; if ($x->{sign} ne '+' && $x->{sign} ne '-') { return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN return 'inf'; # +inf } my ($mant, $expo) = $x -> nparts(); my $esgn = $expo < 0 ? '-' : '+'; my $eabs = $expo -> babs() -> bfround(0) -> bstr(); #$eabs = '0' . $eabs if length($eabs) < 2; return $mant . 'e' . $esgn . $eabs; } # Engineering notation, e.g., "12345.6789" is written as "12.3456789e+3". sub bestr { my $x = shift; if ($x->{sign} ne '+' && $x->{sign} ne '-') { return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN return 'inf'; # +inf } my ($mant, $expo) = $x -> eparts(); my $esgn = $expo < 0 ? '-' : '+'; my $eabs = $expo -> babs() -> bfround(0) -> bstr(); #$eabs = '0' . $eabs if length($eabs) < 2; return $mant . 'e' . $esgn . $eabs; } sub to_hex { # return number as hexadecimal string (only for integers defined) my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_); return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc return '0' if $x->is_zero(); return $nan if $x->{_es} ne '+'; # how to do 1e-1 in hex? my $z = $MBI->_copy($x->{_m}); if (! $MBI->_is_zero($x->{_e})) { # > 0 $z = $MBI->_lsft($z, $x->{_e}, 10); } my $str = $MBI->_to_hex($z); return $x->{sign} eq '-' ? "-$str" : $str; } sub to_oct { # return number as octal digit string (only for integers defined) my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_); return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc return '0' if $x->is_zero(); return $nan if $x->{_es} ne '+'; # how to do 1e-1 in octal? my $z = $MBI->_copy($x->{_m}); if (! $MBI->_is_zero($x->{_e})) { # > 0 $z = $MBI->_lsft($z, $x->{_e}, 10); } my $str = $MBI->_to_oct($z); return $x->{sign} eq '-' ? "-$str" : $str; } sub to_bin { # return number as binary digit string (only for integers defined) my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_); return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc return '0' if $x->is_zero(); return $nan if $x->{_es} ne '+'; # how to do 1e-1 in binary? my $z = $MBI->_copy($x->{_m}); if (! $MBI->_is_zero($x->{_e})) { # > 0 $z = $MBI->_lsft($z, $x->{_e}, 10); } my $str = $MBI->_to_bin($z); return $x->{sign} eq '-' ? "-$str" : $str; } sub as_hex { # return number as hexadecimal string (only for integers defined) my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_); return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc return '0x0' if $x->is_zero(); return $nan if $x->{_es} ne '+'; # how to do 1e-1 in hex? my $z = $MBI->_copy($x->{_m}); if (! $MBI->_is_zero($x->{_e})) { # > 0 $z = $MBI->_lsft($z, $x->{_e}, 10); } my $str = $MBI->_as_hex($z); return $x->{sign} eq '-' ? "-$str" : $str; } sub as_oct { # return number as octal digit string (only for integers defined) my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_); return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc return '00' if $x->is_zero(); return $nan if $x->{_es} ne '+'; # how to do 1e-1 in octal? my $z = $MBI->_copy($x->{_m}); if (! $MBI->_is_zero($x->{_e})) { # > 0 $z = $MBI->_lsft($z, $x->{_e}, 10); } my $str = $MBI->_as_oct($z); return $x->{sign} eq '-' ? "-$str" : $str; } sub as_bin { # return number as binary digit string (only for integers defined) my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_); return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc return '0b0' if $x->is_zero(); return $nan if $x->{_es} ne '+'; # how to do 1e-1 in binary? my $z = $MBI->_copy($x->{_m}); if (! $MBI->_is_zero($x->{_e})) { # > 0 $z = $MBI->_lsft($z, $x->{_e}, 10); } my $str = $MBI->_as_bin($z); return $x->{sign} eq '-' ? "-$str" : $str; } sub numify { # Make a Perl scalar number from a Math::BigFloat object. my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); if ($x -> is_nan()) { require Math::Complex; my $inf = Math::Complex::Inf(); return $inf - $inf; } if ($x -> is_inf()) { require Math::Complex; my $inf = Math::Complex::Inf(); return $x -> is_negative() ? -$inf : $inf; } # Create a string and let Perl's atoi()/atof() handle the rest. return 0 + $x -> bsstr(); } ############################################################################### # Private methods and functions. ############################################################################### sub import { my $class = shift; my $l = scalar @_; my $lib = ''; my @a; my $lib_kind = 'try'; $IMPORT=1; for (my $i = 0; $i < $l ; $i++) { if ($_[$i] eq ':constant') { # This causes overlord er load to step in. 'binary' and 'integer' # are handled by BigInt. overload::constant float => sub { $class->new(shift); }; } elsif ($_[$i] eq 'upgrade') { # this causes upgrading $upgrade = $_[$i+1]; # or undef to disable $i++; } elsif ($_[$i] eq 'downgrade') { # this causes downgrading $downgrade = $_[$i+1]; # or undef to disable $i++; } elsif ($_[$i] =~ /^(lib|try|only)\z/) { # alternative library $lib = $_[$i+1] || ''; # default Calc $lib_kind = $1; # lib, try or only $i++; } elsif ($_[$i] eq 'with') { # alternative class for our private parts() # XXX: no longer supported # $MBI = $_[$i+1] || 'Math::BigInt'; $i++; } else { push @a, $_[$i]; } } $lib =~ tr/a-zA-Z0-9,://cd; # restrict to sane characters # let use Math::BigInt lib => 'GMP'; use Math::BigFloat; still work my $mbilib = eval { Math::BigInt->config('lib') }; if ((defined $mbilib) && ($MBI eq 'Math::BigInt::Calc')) { # MBI already loaded Math::BigInt->import($lib_kind, "$lib, $mbilib", 'objectify'); } else { # MBI not loaded, or with ne "Math::BigInt::Calc" $lib .= ",$mbilib" if defined $mbilib; $lib =~ s/^,//; # don't leave empty # replacement library can handle lib statement, but also could ignore it # Perl < 5.6.0 dies with "out of memory!" when eval() and ':constant' is # used in the same script, or eval inside import(). So we require MBI: require Math::BigInt; Math::BigInt->import($lib_kind => $lib, 'objectify'); } if ($@) { Carp::croak("Couldn't load $lib: $! $@"); } # find out which one was actually loaded $MBI = Math::BigInt->config('lib'); # register us with MBI to get notified of future lib changes Math::BigInt::_register_callback($class, sub { $MBI = $_[0]; }); $class->export_to_level(1, $class, @a); # export wanted functions } sub _len_to_steps { # Given D (digits in decimal), compute N so that N! (N factorial) is # at least D digits long. D should be at least 50. my $d = shift; # two constants for the Ramanujan estimate of ln(N!) my $lg2 = log(2 * 3.14159265) / 2; my $lg10 = log(10); # D = 50 => N => 42, so L = 40 and R = 50 my $l = 40; my $r = $d; # Otherwise this does not work under -Mbignum and we do not yet have "no bignum;" :( $l = $l->numify if ref($l); $r = $r->numify if ref($r); $lg2 = $lg2->numify if ref($lg2); $lg10 = $lg10->numify if ref($lg10); # binary search for the right value (could this be written as the reverse of lg(n!)?) while ($r - $l > 1) { my $n = int(($r - $l) / 2) + $l; my $ramanujan = int(($n * log($n) - $n + log($n * (1 + 4*$n*(1+2*$n))) / 6 + $lg2) / $lg10); $ramanujan > $d ? $r = $n : $l = $n; } $l; } sub _log { # internal log function to calculate ln() based on Taylor series. # Modifies $x in place. my ($class, $x, $scale) = @_; # in case of $x == 1, result is 0 return $x->bzero() if $x->is_one(); # XXX TODO: rewrite this in a similar manner to bexp() # http://www.efunda.com/math/taylor_series/logarithmic.cfm?search_string=log # u = x-1, v = x+1 # _ _ # Taylor: | u 1 u^3 1 u^5 | # ln (x) = 2 | --- + - * --- + - * --- + ... | x > 0 # |_ v 3 v^3 5 v^5 _| # This takes much more steps to calculate the result and is thus not used # u = x-1 # _ _ # Taylor: | u 1 u^2 1 u^3 | # ln (x) = 2 | --- + - * --- + - * --- + ... | x > 1/2 # |_ x 2 x^2 3 x^3 _| my ($limit, $v, $u, $below, $factor, $two, $next, $over, $f); $v = $x->copy(); $v->binc(); # v = x+1 $x->bdec(); $u = $x->copy(); # u = x-1; x = x-1 $x->bdiv($v, $scale); # first term: u/v $below = $v->copy(); $over = $u->copy(); $u *= $u; $v *= $v; # u^2, v^2 $below->bmul($v); # u^3, v^3 $over->bmul($u); $factor = $class->new(3); $f = $class->new(2); my $steps = 0; $limit = $class->new("1E-". ($scale-1)); while (3 < 5) { # we calculate the next term, and add it to the last # when the next term is below our limit, it won't affect the outcome # anymore, so we stop # calculating the next term simple from over/below will result in quite # a time hog if the input has many digits, since over and below will # accumulate more and more digits, and the result will also have many # digits, but in the end it is rounded to $scale digits anyway. So if we # round $over and $below first, we save a lot of time for the division # (not with log(1.2345), but try log (123**123) to see what I mean. This # can introduce a rounding error if the division result would be f.i. # 0.1234500000001 and we round it to 5 digits it would become 0.12346, but # if we truncated $over and $below we might get 0.12345. Does this matter # for the end result? So we give $over and $below 4 more digits to be # on the safe side (unscientific error handling as usual... :+D $next = $over->copy()->bround($scale+4) ->bdiv($below->copy()->bmul($factor)->bround($scale+4), $scale); ## old version: ## $next = $over->copy()->bdiv($below->copy()->bmul($factor), $scale); last if $next->bacmp($limit) <= 0; delete $next->{_a}; delete $next->{_p}; $x->badd($next); # calculate things for the next term $over *= $u; $below *= $v; $factor->badd($f); if (DEBUG) { $steps++; print "step $steps = $x\n" if $steps % 10 == 0; } } print "took $steps steps\n" if DEBUG; $x->bmul($f); # $x *= 2 } sub _log_10 { # Internal log function based on reducing input to the range of 0.1 .. 9.99 # and then "correcting" the result to the proper one. Modifies $x in place. my ($class, $x, $scale) = @_; # Taking blog() from numbers greater than 10 takes a *very long* time, so we # break the computation down into parts based on the observation that: # blog(X*Y) = blog(X) + blog(Y) # We set Y here to multiples of 10 so that $x becomes below 1 - the smaller # $x is the faster it gets. Since 2*$x takes about 10 times as # long, we make it faster by about a factor of 100 by dividing $x by 10. # The same observation is valid for numbers smaller than 0.1, e.g. computing # log(1) is fastest, and the further away we get from 1, the longer it takes. # So we also 'break' this down by multiplying $x with 10 and subtract the # log(10) afterwards to get the correct result. # To get $x even closer to 1, we also divide by 2 and then use log(2) to # correct for this. For instance if $x is 2.4, we use the formula: # blog(2.4 * 2) == blog (1.2) + blog(2) # and thus calculate only blog(1.2) and blog(2), which is faster in total # than calculating blog(2.4). # In addition, the values for blog(2) and blog(10) are cached. # Calculate nr of digits before dot: my $dbd = $MBI->_num($x->{_e}); $dbd = -$dbd if $x->{_es} eq '-'; $dbd += $MBI->_len($x->{_m}); # more than one digit (e.g. at least 10), but *not* exactly 10 to avoid # infinite recursion my $calc = 1; # do some calculation? # disable the shortcut for 10, since we need log(10) and this would recurse # infinitely deep if ($x->{_es} eq '+' && $MBI->_is_one($x->{_e}) && $MBI->_is_one($x->{_m})) { $dbd = 0; # disable shortcut # we can use the cached value in these cases if ($scale <= $LOG_10_A) { $x->bzero(); $x->badd($LOG_10); # modify $x in place $calc = 0; # no need to calc, but round } # if we can't use the shortcut, we continue normally } else { # disable the shortcut for 2, since we maybe have it cached if (($MBI->_is_zero($x->{_e}) && $MBI->_is_two($x->{_m}))) { $dbd = 0; # disable shortcut # we can use the cached value in these cases if ($scale <= $LOG_2_A) { $x->bzero(); $x->badd($LOG_2); # modify $x in place $calc = 0; # no need to calc, but round } # if we can't use the shortcut, we continue normally } } # if $x = 0.1, we know the result must be 0-log(10) if ($calc != 0 && $x->{_es} eq '-' && $MBI->_is_one($x->{_e}) && $MBI->_is_one($x->{_m})) { $dbd = 0; # disable shortcut # we can use the cached value in these cases if ($scale <= $LOG_10_A) { $x->bzero(); $x->bsub($LOG_10); $calc = 0; # no need to calc, but round } } return if $calc == 0; # already have the result # default: these correction factors are undef and thus not used my $l_10; # value of ln(10) to A of $scale my $l_2; # value of ln(2) to A of $scale my $two = $class->new(2); # $x == 2 => 1, $x == 13 => 2, $x == 0.1 => 0, $x == 0.01 => -1 # so don't do this shortcut for 1 or 0 if (($dbd > 1) || ($dbd < 0)) { # convert our cached value to an object if not already (avoid doing this # at import() time, since not everybody needs this) $LOG_10 = $class->new($LOG_10, undef, undef) unless ref $LOG_10; #print "x = $x, dbd = $dbd, calc = $calc\n"; # got more than one digit before the dot, or more than one zero after the # dot, so do: # log(123) == log(1.23) + log(10) * 2 # log(0.0123) == log(1.23) - log(10) * 2 if ($scale <= $LOG_10_A) { # use cached value $l_10 = $LOG_10->copy(); # copy for mul } else { # else: slower, compute and cache result # also disable downgrade for this code path local $Math::BigFloat::downgrade = undef; # shorten the time to calculate log(10) based on the following: # log(1.25 * 8) = log(1.25) + log(8) # = log(1.25) + log(2) + log(2) + log(2) # first get $l_2 (and possible compute and cache log(2)) $LOG_2 = $class->new($LOG_2, undef, undef) unless ref $LOG_2; if ($scale <= $LOG_2_A) { # use cached value $l_2 = $LOG_2->copy(); # copy() for the mul below } else { # else: slower, compute and cache result $l_2 = $two->copy(); $class->_log($l_2, $scale); # scale+4, actually $LOG_2 = $l_2->copy(); # cache the result for later # the copy() is for mul below $LOG_2_A = $scale; } # now calculate log(1.25): $l_10 = $class->new('1.25'); $class->_log($l_10, $scale); # scale+4, actually # log(1.25) + log(2) + log(2) + log(2): $l_10->badd($l_2); $l_10->badd($l_2); $l_10->badd($l_2); $LOG_10 = $l_10->copy(); # cache the result for later # the copy() is for mul below $LOG_10_A = $scale; } $dbd-- if ($dbd > 1); # 20 => dbd=2, so make it dbd=1 $l_10->bmul($class->new($dbd)); # log(10) * (digits_before_dot-1) my $dbd_sign = '+'; if ($dbd < 0) { $dbd = -$dbd; $dbd_sign = '-'; } ($x->{_e}, $x->{_es}) = _e_sub($x->{_e}, $MBI->_new($dbd), $x->{_es}, $dbd_sign); # 123 => 1.23 } # Now: 0.1 <= $x < 10 (and possible correction in l_10) ### Since $x in the range 0.5 .. 1.5 is MUCH faster, we do a repeated div ### or mul by 2 (maximum times 3, since x < 10 and x > 0.1) $HALF = $class->new($HALF) unless ref($HALF); my $twos = 0; # default: none (0 times) while ($x->bacmp($HALF) <= 0) { # X <= 0.5 $twos--; $x->bmul($two); } while ($x->bacmp($two) >= 0) { # X >= 2 $twos++; $x->bdiv($two, $scale+4); # keep all digits } $x->bround($scale+4); # $twos > 0 => did mul 2, < 0 => did div 2 (but we never did both) # So calculate correction factor based on ln(2): if ($twos != 0) { $LOG_2 = $class->new($LOG_2, undef, undef) unless ref $LOG_2; if ($scale <= $LOG_2_A) { # use cached value $l_2 = $LOG_2->copy(); # copy() for the mul below } else { # else: slower, compute and cache result # also disable downgrade for this code path local $Math::BigFloat::downgrade = undef; $l_2 = $two->copy(); $class->_log($l_2, $scale); # scale+4, actually $LOG_2 = $l_2->copy(); # cache the result for later # the copy() is for mul below $LOG_2_A = $scale; } $l_2->bmul($twos); # * -2 => subtract, * 2 => add } else { undef $l_2; } $class->_log($x, $scale); # need to do the "normal" way $x->badd($l_10) if defined $l_10; # correct it by ln(10) $x->badd($l_2) if defined $l_2; # and maybe by ln(2) # all done, $x contains now the result $x; } sub _e_add { # Internal helper sub to take two positive integers and their signs and # then add them. Input ($CALC, $CALC, ('+'|'-'), ('+'|'-')), output # ($CALC, ('+'|'-')). my ($x, $y, $xs, $ys) = @_; # if the signs are equal we can add them (-5 + -3 => -(5 + 3) => -8) if ($xs eq $ys) { $x = $MBI->_add($x, $y); # +a + +b or -a + -b } else { my $a = $MBI->_acmp($x, $y); if ($a == 0) { # This does NOT modify $x in-place. TODO: Fix this? $x = $MBI->_zero(); # result is 0 $xs = '+'; return ($x, $xs); } if ($a > 0) { $x = $MBI->_sub($x, $y); # abs sub } else { # a < 0 $x = $MBI->_sub ($y, $x, 1); # abs sub $xs = $ys; } } $xs = '+' if $xs eq '-' && $MBI->_is_zero($x); # no "-0" return ($x, $xs); } sub _e_sub { # Internal helper sub to take two positive integers and their signs and # then subtract them. Input ($CALC, $CALC, ('+'|'-'), ('+'|'-')), # output ($CALC, ('+'|'-')) my ($x, $y, $xs, $ys) = @_; # flip sign $ys = $ys eq '+' ? '-' : '+'; # swap sign of second operand ... _e_add($x, $y, $xs, $ys); # ... and let _e_add() do the job } sub _pow { # Calculate a power where $y is a non-integer, like 2 ** 0.3 my ($x, $y, @r) = @_; my $class = ref($x); # if $y == 0.5, it is sqrt($x) $HALF = $class->new($HALF) unless ref($HALF); return $x->bsqrt(@r, $y) if $y->bcmp($HALF) == 0; # Using: # a ** x == e ** (x * ln a) # u = y * ln x # _ _ # Taylor: | u u^2 u^3 | # x ** y = 1 + | --- + --- + ----- + ... | # |_ 1 1*2 1*2*3 _| # we need to limit the accuracy to protect against overflow my $fallback = 0; my ($scale, @params); ($x, @params) = $x->_find_round_parameters(@r); return $x if $x->is_nan(); # error in _find_round_parameters? # no rounding at all, so must use fallback if (scalar @params == 0) { # simulate old behaviour $params[0] = $class->div_scale(); # and round to it as accuracy $params[1] = undef; # disable P $scale = $params[0]+4; # at least four more for proper round $params[2] = $r[2]; # round mode by caller or undef $fallback = 1; # to clear a/p afterwards } else { # the 4 below is empirical, and there might be cases where it is not # enough... $scale = abs($params[0] || $params[1]) + 4; # take whatever is defined } # when user set globals, they would interfere with our calculation, so # disable them and later re-enable them no strict 'refs'; my $abr = "$class\::accuracy"; my $ab = $$abr; $$abr = undef; my $pbr = "$class\::precision"; my $pb = $$pbr; $$pbr = undef; # we also need to disable any set A or P on $x (_find_round_parameters took # them already into account), since these would interfere, too delete $x->{_a}; delete $x->{_p}; # need to disable $upgrade in BigInt, to avoid deep recursion local $Math::BigInt::upgrade = undef; my ($limit, $v, $u, $below, $factor, $next, $over); $u = $x->copy()->blog(undef, $scale)->bmul($y); my $do_invert = ($u->{sign} eq '-'); $u->bneg() if $do_invert; $v = $class->bone(); # 1 $factor = $class->new(2); # 2 $x->bone(); # first term: 1 $below = $v->copy(); $over = $u->copy(); $limit = $class->new("1E-". ($scale-1)); #my $steps = 0; while (3 < 5) { # we calculate the next term, and add it to the last # when the next term is below our limit, it won't affect the outcome # anymore, so we stop: $next = $over->copy()->bdiv($below, $scale); last if $next->bacmp($limit) <= 0; $x->badd($next); # calculate things for the next term $over *= $u; $below *= $factor; $factor->binc(); last if $x->{sign} !~ /^[-+]$/; #$steps++; } if ($do_invert) { my $x_copy = $x->copy(); $x->bone->bdiv($x_copy, $scale); } # shortcut to not run through _find_round_parameters again if (defined $params[0]) { $x->bround($params[0], $params[2]); # then round accordingly } else { $x->bfround($params[1], $params[2]); # then round accordingly } if ($fallback) { # clear a/p after round, since user did not request it delete $x->{_a}; delete $x->{_p}; } # restore globals $$abr = $ab; $$pbr = $pb; $x; } 1; __END__ =pod =head1 NAME Math::BigFloat - Arbitrary size floating point math package =head1 SYNOPSIS use Math::BigFloat; # Configuration methods (may be used as class methods and instance methods) Math::BigFloat->accuracy(); # get class accuracy Math::BigFloat->accuracy($n); # set class accuracy Math::BigFloat->precision(); # get class precision Math::BigFloat->precision($n); # set class precision Math::BigFloat->round_mode(); # get class rounding mode Math::BigFloat->round_mode($m); # set global round mode, must be one of # 'even', 'odd', '+inf', '-inf', 'zero', # 'trunc', or 'common' Math::BigFloat->config(); # return hash with configuration # Constructor methods (when the class methods below are used as instance # methods, the value is assigned the invocand) $x = Math::BigFloat->new($str); # defaults to 0 $x = Math::BigFloat->new('0x123'); # from hexadecimal $x = Math::BigFloat->new('0b101'); # from binary $x = Math::BigFloat->from_hex('0xc.afep+3'); # from hex $x = Math::BigFloat->from_hex('cafe'); # ditto $x = Math::BigFloat->from_oct('1.3267p-4'); # from octal $x = Math::BigFloat->from_oct('0377'); # ditto $x = Math::BigFloat->from_bin('0b1.1001p-4'); # from binary $x = Math::BigFloat->from_bin('0101'); # ditto $x = Math::BigFloat->bzero(); # create a +0 $x = Math::BigFloat->bone(); # create a +1 $x = Math::BigFloat->bone('-'); # create a -1 $x = Math::BigFloat->binf(); # create a +inf $x = Math::BigFloat->binf('-'); # create a -inf $x = Math::BigFloat->bnan(); # create a Not-A-Number $x = Math::BigFloat->bpi(); # returns pi $y = $x->copy(); # make a copy (unlike $y = $x) $y = $x->as_int(); # return as BigInt # Boolean methods (these don't modify the invocand) $x->is_zero(); # if $x is 0 $x->is_one(); # if $x is +1 $x->is_one("+"); # ditto $x->is_one("-"); # if $x is -1 $x->is_inf(); # if $x is +inf or -inf $x->is_inf("+"); # if $x is +inf $x->is_inf("-"); # if $x is -inf $x->is_nan(); # if $x is NaN $x->is_positive(); # if $x > 0 $x->is_pos(); # ditto $x->is_negative(); # if $x < 0 $x->is_neg(); # ditto $x->is_odd(); # if $x is odd $x->is_even(); # if $x is even $x->is_int(); # if $x is an integer # Comparison methods $x->bcmp($y); # compare numbers (undef, < 0, == 0, > 0) $x->bacmp($y); # compare absolutely (undef, < 0, == 0, > 0) $x->beq($y); # true if and only if $x == $y $x->bne($y); # true if and only if $x != $y $x->blt($y); # true if and only if $x < $y $x->ble($y); # true if and only if $x <= $y $x->bgt($y); # true if and only if $x > $y $x->bge($y); # true if and only if $x >= $y # Arithmetic methods $x->bneg(); # negation $x->babs(); # absolute value $x->bsgn(); # sign function (-1, 0, 1, or NaN) $x->bnorm(); # normalize (no-op) $x->binc(); # increment $x by 1 $x->bdec(); # decrement $x by 1 $x->badd($y); # addition (add $y to $x) $x->bsub($y); # subtraction (subtract $y from $x) $x->bmul($y); # multiplication (multiply $x by $y) $x->bmuladd($y,$z); # $x = $x * $y + $z $x->bdiv($y); # division (floored), set $x to quotient # return (quo,rem) or quo if scalar $x->btdiv($y); # division (truncated), set $x to quotient # return (quo,rem) or quo if scalar $x->bmod($y); # modulus (x % y) $x->btmod($y); # modulus (truncated) $x->bmodinv($mod); # modular multiplicative inverse $x->bmodpow($y,$mod); # modular exponentiation (($x ** $y) % $mod) $x->bpow($y); # power of arguments (x ** y) $x->blog(); # logarithm of $x to base e (Euler's number) $x->blog($base); # logarithm of $x to base $base (e.g., base 2) $x->bexp(); # calculate e ** $x where e is Euler's number $x->bnok($y); # x over y (binomial coefficient n over k) $x->bsin(); # sine $x->bcos(); # cosine $x->batan(); # inverse tangent $x->batan2($y); # two-argument inverse tangent $x->bsqrt(); # calculate square-root $x->broot($y); # $y'th root of $x (e.g. $y == 3 => cubic root) $x->bfac(); # factorial of $x (1*2*3*4*..$x) $x->blsft($n); # left shift $n places in base 2 $x->blsft($n,$b); # left shift $n places in base $b # returns (quo,rem) or quo (scalar context) $x->brsft($n); # right shift $n places in base 2 $x->brsft($n,$b); # right shift $n places in base $b # returns (quo,rem) or quo (scalar context) # Bitwise methods $x->band($y); # bitwise and $x->bior($y); # bitwise inclusive or $x->bxor($y); # bitwise exclusive or $x->bnot(); # bitwise not (two's complement) # Rounding methods $x->round($A,$P,$mode); # round to accuracy or precision using # rounding mode $mode $x->bround($n); # accuracy: preserve $n digits $x->bfround($n); # $n > 0: round to $nth digit left of dec. point # $n < 0: round to $nth digit right of dec. point $x->bfloor(); # round towards minus infinity $x->bceil(); # round towards plus infinity $x->bint(); # round towards zero # Other mathematical methods $x->bgcd($y); # greatest common divisor $x->blcm($y); # least common multiple # Object property methods (do not modify the invocand) $x->sign(); # the sign, either +, - or NaN $x->digit($n); # the nth digit, counting from the right $x->digit(-$n); # the nth digit, counting from the left $x->length(); # return number of digits in number ($xl,$f) = $x->length(); # length of number and length of fraction # part, latter is always 0 digits long # for Math::BigInt objects $x->mantissa(); # return (signed) mantissa as BigInt $x->exponent(); # return exponent as BigInt $x->parts(); # return (mantissa,exponent) as BigInt $x->sparts(); # mantissa and exponent (as integers) $x->nparts(); # mantissa and exponent (normalised) $x->eparts(); # mantissa and exponent (engineering notation) $x->dparts(); # integer and fraction part # Conversion methods (do not modify the invocand) $x->bstr(); # decimal notation, possibly zero padded $x->bsstr(); # string in scientific notation with integers $x->bnstr(); # string in normalized notation $x->bestr(); # string in engineering notation $x->bdstr(); # string in decimal notation $x->as_hex(); # as signed hexadecimal string with prefixed 0x $x->as_bin(); # as signed binary string with prefixed 0b $x->as_oct(); # as signed octal string with prefixed 0 # Other conversion methods $x->numify(); # return as scalar (might overflow or underflow) =head1 DESCRIPTION Math::BigFloat provides support for arbitrary precision floating point. Overloading is also provided for Perl operators. All operators (including basic math operations) are overloaded if you declare your big floating point numbers as $x = Math::BigFloat -> new('12_3.456_789_123_456_789E-2'); Operations with overloaded operators preserve the arguments, which is exactly what you expect. =head2 Input Input values to these routines may be any scalar number or string that looks like a number and represents a floating point number. =over =item * Leading and trailing whitespace is ignored. =item * Leading and trailing zeros are ignored. =item * If the string has a "0x" prefix, it is interpreted as a hexadecimal number. =item * If the string has a "0b" prefix, it is interpreted as a binary number. =item * For hexadecimal and binary numbers, the exponent must be separated from the significand (mantissa) by the letter "p" or "P", not "e" or "E" as with decimal numbers. =item * One underline is allowed between any two digits, including hexadecimal and binary digits. =item * If the string can not be interpreted, NaN is returned. =back Octal numbers are typically prefixed by "0", but since leading zeros are stripped, these methods can not automatically recognize octal numbers, so use the constructor from_oct() to interpret octal strings. Some examples of valid string input Input string Resulting value 123 123 1.23e2 123 12300e-2 123 0xcafe 51966 0b1101 13 67_538_754 67538754 -4_5_6.7_8_9e+0_1_0 -4567890000000 0x1.921fb5p+1 3.14159262180328369140625e+0 0b1.1001p-4 9.765625e-2 =head2 Output Output values are usually Math::BigFloat objects. Boolean operators C, C, C, etc. return true or false. Comparison operators C and C) return -1, 0, 1, or undef. =head1 METHODS Math::BigFloat supports all methods that Math::BigInt supports, except it calculates non-integer results when possible. Please see L for a full description of each method. Below are just the most important differences: =head2 Configuration methods =over =item accuracy() $x->accuracy(5); # local for $x CLASS->accuracy(5); # global for all members of CLASS # Note: This also applies to new()! $A = $x->accuracy(); # read out accuracy that affects $x $A = CLASS->accuracy(); # read out global accuracy Set or get the global or local accuracy, aka how many significant digits the results have. If you set a global accuracy, then this also applies to new()! Warning! The accuracy I, e.g. once you created a number under the influence of C<< CLASS->accuracy($A) >>, all results from math operations with that number will also be rounded. In most cases, you should probably round the results explicitly using one of L, L or L or by passing the desired accuracy to the math operation as additional parameter: my $x = Math::BigInt->new(30000); my $y = Math::BigInt->new(7); print scalar $x->copy()->bdiv($y, 2); # print 4300 print scalar $x->copy()->bdiv($y)->bround(2); # print 4300 =item precision() $x->precision(-2); # local for $x, round at the second # digit right of the dot $x->precision(2); # ditto, round at the second digit # left of the dot CLASS->precision(5); # Global for all members of CLASS # This also applies to new()! CLASS->precision(-5); # ditto $P = CLASS->precision(); # read out global precision $P = $x->precision(); # read out precision that affects $x Note: You probably want to use L instead. With L you set the number of digits each result should have, with L you set the place where to round! =back =head2 Constructor methods =over =item from_hex() $x -> from_hex("0x1.921fb54442d18p+1"); $x = Math::BigFloat -> from_hex("0x1.921fb54442d18p+1"); Interpret input as a hexadecimal string.A prefix ("0x", "x", ignoring case) is optional. A single underscore character ("_") may be placed between any two digits. If the input is invalid, a NaN is returned. The exponent is in base 2 using decimal digits. If called as an instance method, the value is assigned to the invocand. =item from_oct() $x -> from_oct("1.3267p-4"); $x = Math::BigFloat -> from_oct("1.3267p-4"); Interpret input as an octal string. A single underscore character ("_") may be placed between any two digits. If the input is invalid, a NaN is returned. The exponent is in base 2 using decimal digits. If called as an instance method, the value is assigned to the invocand. =item from_bin() $x -> from_bin("0b1.1001p-4"); $x = Math::BigFloat -> from_bin("0b1.1001p-4"); Interpret input as a hexadecimal string. A prefix ("0b" or "b", ignoring case) is optional. A single underscore character ("_") may be placed between any two digits. If the input is invalid, a NaN is returned. The exponent is in base 2 using decimal digits. If called as an instance method, the value is assigned to the invocand. =item bpi() print Math::BigFloat->bpi(100), "\n"; Calculate PI to N digits (including the 3 before the dot). The result is rounded according to the current rounding mode, which defaults to "even". This method was added in v1.87 of Math::BigInt (June 2007). =back =head2 Arithmetic methods =over =item bmuladd() $x->bmuladd($y,$z); Multiply $x by $y, and then add $z to the result. This method was added in v1.87 of Math::BigInt (June 2007). =item bdiv() $q = $x->bdiv($y); ($q, $r) = $x->bdiv($y); In scalar context, divides $x by $y and returns the result to the given or default accuracy/precision. In list context, does floored division (F-division), returning an integer $q and a remainder $r so that $x = $q * $y + $r. The remainer (modulo) is equal to what is returned by C<$x->bmod($y)>. =item bmod() $x->bmod($y); Returns $x modulo $y. When $x is finite, and $y is finite and non-zero, the result is identical to the remainder after floored division (F-division). If, in addition, both $x and $y are integers, the result is identical to the result from Perl's % operator. =item bexp() $x->bexp($accuracy); # calculate e ** X Calculates the expression C where C is Euler's number. This method was added in v1.82 of Math::BigInt (April 2007). =item bnok() $x->bnok($y); # x over y (binomial coefficient n over k) Calculates the binomial coefficient n over k, also called the "choose" function. The result is equivalent to: ( n ) n! | - | = ------- ( k ) k!(n-k)! This method was added in v1.84 of Math::BigInt (April 2007). =item bsin() my $x = Math::BigFloat->new(1); print $x->bsin(100), "\n"; Calculate the sinus of $x, modifying $x in place. This method was added in v1.87 of Math::BigInt (June 2007). =item bcos() my $x = Math::BigFloat->new(1); print $x->bcos(100), "\n"; Calculate the cosinus of $x, modifying $x in place. This method was added in v1.87 of Math::BigInt (June 2007). =item batan() my $x = Math::BigFloat->new(1); print $x->batan(100), "\n"; Calculate the arcus tanges of $x, modifying $x in place. See also L. This method was added in v1.87 of Math::BigInt (June 2007). =item batan2() my $y = Math::BigFloat->new(2); my $x = Math::BigFloat->new(3); print $y->batan2($x), "\n"; Calculate the arcus tanges of C<$y> divided by C<$x>, modifying $y in place. See also L. This method was added in v1.87 of Math::BigInt (June 2007). =item as_float() This method is called when Math::BigFloat encounters an object it doesn't know how to handle. For instance, assume $x is a Math::BigFloat, or subclass thereof, and $y is defined, but not a Math::BigFloat, or subclass thereof. If you do $x -> badd($y); $y needs to be converted into an object that $x can deal with. This is done by first checking if $y is something that $x might be upgraded to. If that is the case, no further attempts are made. The next is to see if $y supports the method C. The method C is expected to return either an object that has the same class as $x, a subclass thereof, or a string that Cnew()> can parse to create an object. In Math::BigFloat, C has the same effect as C. =back =head2 ACCURACY AND PRECISION See also: L. Math::BigFloat supports both precision (rounding to a certain place before or after the dot) and accuracy (rounding to a certain number of digits). For a full documentation, examples and tips on these topics please see the large section about rounding in L. Since things like C or C<1 / 3> must presented with a limited accuracy lest a operation consumes all resources, each operation produces no more than the requested number of digits. If there is no global precision or accuracy set, B the operation in question was not called with a requested precision or accuracy, B the input $x has no accuracy or precision set, then a fallback parameter will be used. For historical reasons, it is called C and can be accessed via: $d = Math::BigFloat->div_scale(); # query Math::BigFloat->div_scale($n); # set to $n digits The default value for C is 40. In case the result of one operation has more digits than specified, it is rounded. The rounding mode taken is either the default mode, or the one supplied to the operation after the I: $x = Math::BigFloat->new(2); Math::BigFloat->accuracy(5); # 5 digits max $y = $x->copy()->bdiv(3); # gives 0.66667 $y = $x->copy()->bdiv(3,6); # gives 0.666667 $y = $x->copy()->bdiv(3,6,undef,'odd'); # gives 0.666667 Math::BigFloat->round_mode('zero'); $y = $x->copy()->bdiv(3,6); # will also give 0.666667 Note that C<< Math::BigFloat->accuracy() >> and C<< Math::BigFloat->precision() >> set the global variables, and thus B newly created number will be subject to the global rounding B. This means that in the examples above, the C<3> as argument to C will also get an accuracy of B<5>. It is less confusing to either calculate the result fully, and afterwards round it explicitly, or use the additional parameters to the math functions like so: use Math::BigFloat; $x = Math::BigFloat->new(2); $y = $x->copy()->bdiv(3); print $y->bround(5),"\n"; # gives 0.66667 or use Math::BigFloat; $x = Math::BigFloat->new(2); $y = $x->copy()->bdiv(3,5); # gives 0.66667 print "$y\n"; =head2 Rounding =over =item bfround ( +$scale ) Rounds to the $scale'th place left from the '.', counting from the dot. The first digit is numbered 1. =item bfround ( -$scale ) Rounds to the $scale'th place right from the '.', counting from the dot. =item bfround ( 0 ) Rounds to an integer. =item bround ( +$scale ) Preserves accuracy to $scale digits from the left (aka significant digits) and pads the rest with zeros. If the number is between 1 and -1, the significant digits count from the first non-zero after the '.' =item bround ( -$scale ) and bround ( 0 ) These are effectively no-ops. =back All rounding functions take as a second parameter a rounding mode from one of the following: 'even', 'odd', '+inf', '-inf', 'zero', 'trunc' or 'common'. The default rounding mode is 'even'. By using C<< Math::BigFloat->round_mode($round_mode); >> you can get and set the default mode for subsequent rounding. The usage of C<$Math::BigFloat::$round_mode> is no longer supported. The second parameter to the round functions then overrides the default temporarily. The C function returns a BigInt from a Math::BigFloat. It uses 'trunc' as rounding mode to make it equivalent to: $x = 2.5; $y = int($x) + 2; You can override this by passing the desired rounding mode as parameter to C: $x = Math::BigFloat->new(2.5); $y = $x->as_number('odd'); # $y = 3 =head1 Autocreating constants After C all the floating point constants in the given scope are converted to C. This conversion happens at compile time. In particular perl -MMath::BigFloat=:constant -e 'print 2E-100,"\n"' prints the value of C<2E-100>. Note that without conversion of constants the expression 2E-100 will be calculated as normal floating point number. Please note that ':constant' does not affect integer constants, nor binary nor hexadecimal constants. Use L or L to get this to work. =head2 Math library Math with the numbers is done (by default) by a module called Math::BigInt::Calc. This is equivalent to saying: use Math::BigFloat lib => 'Calc'; You can change this by using: use Math::BigFloat lib => 'GMP'; B: General purpose packages should not be explicit about the library to use; let the script author decide which is best. Note: The keyword 'lib' will warn when the requested library could not be loaded. To suppress the warning use 'try' instead: use Math::BigFloat try => 'GMP'; If your script works with huge numbers and Calc is too slow for them, you can also for the loading of one of these libraries and if none of them can be used, the code will die: use Math::BigFloat only => 'GMP,Pari'; The following would first try to find Math::BigInt::Foo, then Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc: use Math::BigFloat lib => 'Foo,Math::BigInt::Bar'; See the respective low-level library documentation for further details. Please note that Math::BigFloat does B use the denoted library itself, but it merely passes the lib argument to Math::BigInt. So, instead of the need to do: use Math::BigInt lib => 'GMP'; use Math::BigFloat; you can roll it all into one line: use Math::BigFloat lib => 'GMP'; It is also possible to just require Math::BigFloat: require Math::BigFloat; This will load the necessary things (like BigInt) when they are needed, and automatically. See L for more details than you ever wanted to know about using a different low-level library. =head2 Using Math::BigInt::Lite For backwards compatibility reasons it is still possible to request a different storage class for use with Math::BigFloat: use Math::BigFloat with => 'Math::BigInt::Lite'; However, this request is ignored, as the current code now uses the low-level math library for directly storing the number parts. =head1 EXPORTS C exports nothing by default, but can export the C method: use Math::BigFloat qw/bpi/; print bpi(10), "\n"; =head1 CAVEATS Do not try to be clever to insert some operations in between switching libraries: require Math::BigFloat; my $matter = Math::BigFloat->bone() + 4; # load BigInt and Calc Math::BigFloat->import( lib => 'Pari' ); # load Pari, too my $anti_matter = Math::BigFloat->bone()+4; # now use Pari This will create objects with numbers stored in two different backend libraries, and B will happen when you use these together: my $flash_and_bang = $matter + $anti_matter; # Don't do this! =over =item stringify, bstr() Both stringify and bstr() now drop the leading '+'. The old code would return '+1.23', the new returns '1.23'. See the documentation in L for reasoning and details. =item brsft() The following will probably not print what you expect: my $c = Math::BigFloat->new('3.14159'); print $c->brsft(3,10),"\n"; # prints 0.00314153.1415 It prints both quotient and remainder, since print calls C in list context. Also, C<< $c->brsft() >> will modify $c, so be careful. You probably want to use print scalar $c->copy()->brsft(3,10),"\n"; # or if you really want to modify $c print scalar $c->brsft(3,10),"\n"; instead. =item Modifying and = Beware of: $x = Math::BigFloat->new(5); $y = $x; It will not do what you think, e.g. making a copy of $x. Instead it just makes a second reference to the B object and stores it in $y. Thus anything that modifies $x will modify $y (except overloaded math operators), and vice versa. See L for details and how to avoid that. =item precision() vs. accuracy() A common pitfall is to use L when you want to round a result to a certain number of digits: use Math::BigFloat; Math::BigFloat->precision(4); # does not do what you # think it does my $x = Math::BigFloat->new(12345); # rounds $x to "12000"! print "$x\n"; # print "12000" my $y = Math::BigFloat->new(3); # rounds $y to "0"! print "$y\n"; # print "0" $z = $x / $y; # 12000 / 0 => NaN! print "$z\n"; print $z->precision(),"\n"; # 4 Replacing L with L is probably not what you want, either: use Math::BigFloat; Math::BigFloat->accuracy(4); # enables global rounding: my $x = Math::BigFloat->new(123456); # rounded immediately # to "12350" print "$x\n"; # print "123500" my $y = Math::BigFloat->new(3); # rounded to "3 print "$y\n"; # print "3" print $z = $x->copy()->bdiv($y),"\n"; # 41170 print $z->accuracy(),"\n"; # 4 What you want to use instead is: use Math::BigFloat; my $x = Math::BigFloat->new(123456); # no rounding print "$x\n"; # print "123456" my $y = Math::BigFloat->new(3); # no rounding print "$y\n"; # print "3" print $z = $x->copy()->bdiv($y,4),"\n"; # 41150 print $z->accuracy(),"\n"; # undef In addition to computing what you expected, the last example also does B "taint" the result with an accuracy or precision setting, which would influence any further operation. =back =head1 BUGS Please report any bugs or feature requests to C, or through the web interface at L (requires login). We will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 SUPPORT You can find documentation for this module with the perldoc command. perldoc Math::BigFloat You can also look for information at: =over 4 =item * RT: CPAN's request tracker L =item * AnnoCPAN: Annotated CPAN documentation L =item * CPAN Ratings L =item * Search CPAN L =item * CPAN Testers Matrix L =item * The Bignum mailing list =over 4 =item * Post to mailing list C =item * View mailing list L =item * Subscribe/Unsubscribe L =back =back =head1 LICENSE This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself. =head1 SEE ALSO L and L as well as the backends L, L, and L. The pragmas L, L and L also might be of interest because they solve the autoupgrading/downgrading issue, at least partly. =head1 AUTHORS =over 4 =item * Mark Biggar, overloaded interface by Ilya Zakharevich, 1996-2001. =item * Completely rewritten by Tels L in 2001-2008. =item * Florian Ragwitz Eflora@cpan.orgE, 2010. =item * Peter John Acklam Epjacklam@online.noE, 2011-. =back =cut BigInt.pm000064400000632255152530054110006267 0ustar00package Math::BigInt; # # "Mike had an infinite amount to do and a negative amount of time in which # to do it." - Before and After # # The following hash values are used: # value: unsigned int with actual value (as a Math::BigInt::Calc or similar) # sign : +, -, NaN, +inf, -inf # _a : accuracy # _p : precision # Remember not to take shortcuts ala $xs = $x->{value}; $CALC->foo($xs); since # underlying lib might change the reference! use 5.006001; use strict; use warnings; use Carp (); our $VERSION = '1.999811'; our @ISA = qw(Exporter); our @EXPORT_OK = qw(objectify bgcd blcm); my $class = "Math::BigInt"; # Inside overload, the first arg is always an object. If the original code had # it reversed (like $x = 2 * $y), then the third parameter is true. # In some cases (like add, $x = $x + 2 is the same as $x = 2 + $x) this makes # no difference, but in some cases it does. # For overloaded ops with only one argument we simple use $_[0]->copy() to # preserve the argument. # Thus inheritance of overload operators becomes possible and transparent for # our subclasses without the need to repeat the entire overload section there. use overload # overload key: with_assign '+' => sub { $_[0] -> copy() -> badd($_[1]); }, '-' => sub { my $c = $_[0] -> copy; $_[2] ? $c -> bneg() -> badd($_[1]) : $c -> bsub($_[1]); }, '*' => sub { $_[0] -> copy() -> bmul($_[1]); }, '/' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bdiv($_[0]) : $_[0] -> copy -> bdiv($_[1]); }, '%' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bmod($_[0]) : $_[0] -> copy -> bmod($_[1]); }, '**' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bpow($_[0]) : $_[0] -> copy -> bpow($_[1]); }, '<<' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> blsft($_[0]) : $_[0] -> copy -> blsft($_[1]); }, '>>' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> brsft($_[0]) : $_[0] -> copy -> brsft($_[1]); }, # 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]) : $_[0] -> copy -> band($_[1]); }, '&=' => sub { $_[0] -> band($_[1]); }, '|' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bior($_[0]) : $_[0] -> copy -> bior($_[1]); }, '|=' => sub { $_[0] -> bior($_[1]); }, '^' => sub { $_[2] ? ref($_[0]) -> new($_[1]) -> bxor($_[0]) : $_[0] -> copy -> bxor($_[1]); }, '^=' => 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]); }, 'cos' => sub { $_[0] -> copy -> bcos(); }, 'sin' => sub { $_[0] -> copy -> bsin(); }, 'exp' => sub { $_[0] -> copy() -> bexp($_[1]); }, 'abs' => sub { $_[0] -> copy() -> babs(); }, 'log' => sub { $_[0] -> copy() -> blog(); }, 'sqrt' => sub { $_[0] -> copy() -> bsqrt(); }, 'int' => sub { $_[0] -> copy() -> bint(); }, # overload key: conversion 'bool' => sub { $_[0] -> is_zero() ? '' : 1; }, '""' => sub { $_[0] -> bstr(); }, '0+' => sub { $_[0] -> numify(); }, '=' => sub { $_[0]->copy(); }, ; ############################################################################## # global constants, flags and accessory # These vars are public, but their direct usage is not recommended, use the # accessor methods instead our $round_mode = 'even'; # one of 'even', 'odd', '+inf', '-inf', 'zero', 'trunc' or 'common' our $accuracy = undef; our $precision = undef; our $div_scale = 40; our $upgrade = undef; # default is no upgrade our $downgrade = undef; # default is no downgrade # These are internally, and not to be used from the outside at all our $_trap_nan = 0; # are NaNs ok? set w/ config() our $_trap_inf = 0; # are infs ok? set w/ config() my $nan = 'NaN'; # constants for easier life my $CALC = 'Math::BigInt::Calc'; # module to do the low level math # default is Calc.pm my $IMPORT = 0; # was import() called yet? # used to make require work my %WARN; # warn only once for low-level libs my %CAN; # cache for $CALC->can(...) my %CALLBACKS; # callbacks to notify on lib loads my $EMU_LIB = 'Math/BigInt/CalcEmu.pm'; # emulate low-level math ############################################################################## # the old code had $rnd_mode, so we need to support it, too our $rnd_mode = 'even'; sub TIESCALAR { my ($class) = @_; bless \$round_mode, $class; } sub FETCH { return $round_mode; } sub STORE { $rnd_mode = $_[0]->round_mode($_[1]); } BEGIN { # tie to enable $rnd_mode to work transparently tie $rnd_mode, 'Math::BigInt'; # set up some handy alias names *as_int = \&as_number; *is_pos = \&is_positive; *is_neg = \&is_negative; } ############################################################################### # Configuration methods ############################################################################### sub round_mode { no strict 'refs'; # make Class->round_mode() work my $self = shift; my $class = ref($self) || $self || __PACKAGE__; if (defined $_[0]) { my $m = shift; if ($m !~ /^(even|odd|\+inf|\-inf|zero|trunc|common)$/) { Carp::croak("Unknown round mode '$m'"); } return ${"${class}::round_mode"} = $m; } ${"${class}::round_mode"}; } sub upgrade { no strict 'refs'; # make Class->upgrade() work my $self = shift; my $class = ref($self) || $self || __PACKAGE__; # need to set new value? if (@_ > 0) { return ${"${class}::upgrade"} = $_[0]; } ${"${class}::upgrade"}; } sub downgrade { no strict 'refs'; # make Class->downgrade() work my $self = shift; my $class = ref($self) || $self || __PACKAGE__; # need to set new value? if (@_ > 0) { return ${"${class}::downgrade"} = $_[0]; } ${"${class}::downgrade"}; } sub div_scale { no strict 'refs'; # make Class->div_scale() work my $self = shift; my $class = ref($self) || $self || __PACKAGE__; if (defined $_[0]) { if ($_[0] < 0) { Carp::croak('div_scale must be greater than zero'); } ${"${class}::div_scale"} = $_[0]; } ${"${class}::div_scale"}; } sub accuracy { # $x->accuracy($a); ref($x) $a # $x->accuracy(); ref($x) # Class->accuracy(); class # Class->accuracy($a); class $a my $x = shift; my $class = ref($x) || $x || __PACKAGE__; no strict 'refs'; # need to set new value? if (@_ > 0) { my $a = shift; # convert objects to scalars to avoid deep recursion. If object doesn't # have numify(), then hopefully it will have overloading for int() and # boolean test without wandering into a deep recursion path... $a = $a->numify() if ref($a) && $a->can('numify'); if (defined $a) { # also croak on non-numerical if (!$a || $a <= 0) { Carp::croak('Argument to accuracy must be greater than zero'); } if (int($a) != $a) { Carp::croak('Argument to accuracy must be an integer'); } } if (ref($x)) { # $object->accuracy() or fallback to global $x->bround($a) if $a; # not for undef, 0 $x->{_a} = $a; # set/overwrite, even if not rounded delete $x->{_p}; # clear P $a = ${"${class}::accuracy"} unless defined $a; # proper return value } else { ${"${class}::accuracy"} = $a; # set global A ${"${class}::precision"} = undef; # clear global P } return $a; # shortcut } my $a; # $object->accuracy() or fallback to global $a = $x->{_a} if ref($x); # but don't return global undef, when $x's accuracy is 0! $a = ${"${class}::accuracy"} if !defined $a; $a; } sub precision { # $x->precision($p); ref($x) $p # $x->precision(); ref($x) # Class->precision(); class # Class->precision($p); class $p my $x = shift; my $class = ref($x) || $x || __PACKAGE__; no strict 'refs'; if (@_ > 0) { my $p = shift; # convert objects to scalars to avoid deep recursion. If object doesn't # have numify(), then hopefully it will have overloading for int() and # boolean test without wandering into a deep recursion path... $p = $p->numify() if ref($p) && $p->can('numify'); if ((defined $p) && (int($p) != $p)) { Carp::croak('Argument to precision must be an integer'); } if (ref($x)) { # $object->precision() or fallback to global $x->bfround($p) if $p; # not for undef, 0 $x->{_p} = $p; # set/overwrite, even if not rounded delete $x->{_a}; # clear A $p = ${"${class}::precision"} unless defined $p; # proper return value } else { ${"${class}::precision"} = $p; # set global P ${"${class}::accuracy"} = undef; # clear global A } return $p; # shortcut } my $p; # $object->precision() or fallback to global $p = $x->{_p} if ref($x); # but don't return global undef, when $x's precision is 0! $p = ${"${class}::precision"} if !defined $p; $p; } sub config { # return (or set) configuration data as hash ref my $class = shift || __PACKAGE__; no strict 'refs'; if (@_ > 1 || (@_ == 1 && (ref($_[0]) eq 'HASH'))) { # try to set given options as arguments from hash my $args = $_[0]; if (ref($args) ne 'HASH') { $args = { @_ }; } # these values can be "set" my $set_args = {}; foreach my $key (qw/ accuracy precision round_mode div_scale upgrade downgrade trap_inf trap_nan /) { $set_args->{$key} = $args->{$key} if exists $args->{$key}; delete $args->{$key}; } if (keys %$args > 0) { Carp::croak("Illegal key(s) '", join("', '", keys %$args), "' passed to $class\->config()"); } foreach my $key (keys %$set_args) { if ($key =~ /^trap_(inf|nan)\z/) { ${"${class}::_trap_$1"} = ($set_args->{"trap_$1"} ? 1 : 0); next; } # use a call instead of just setting the $variable to check argument $class->$key($set_args->{$key}); } } # now return actual configuration my $cfg = { lib => $CALC, lib_version => ${"${CALC}::VERSION"}, class => $class, trap_nan => ${"${class}::_trap_nan"}, trap_inf => ${"${class}::_trap_inf"}, version => ${"${class}::VERSION"}, }; foreach my $key (qw/ accuracy precision round_mode div_scale upgrade downgrade /) { $cfg->{$key} = ${"${class}::$key"}; } if (@_ == 1 && (ref($_[0]) ne 'HASH')) { # calls of the style config('lib') return just this value return $cfg->{$_[0]}; } $cfg; } sub _scale_a { # select accuracy parameter based on precedence, # used by bround() and bfround(), may return undef for scale (means no op) my ($x, $scale, $mode) = @_; $scale = $x->{_a} unless defined $scale; no strict 'refs'; my $class = ref($x); $scale = ${ $class . '::accuracy' } unless defined $scale; $mode = ${ $class . '::round_mode' } unless defined $mode; if (defined $scale) { $scale = $scale->can('numify') ? $scale->numify() : "$scale" if ref($scale); $scale = int($scale); } ($scale, $mode); } sub _scale_p { # select precision parameter based on precedence, # used by bround() and bfround(), may return undef for scale (means no op) my ($x, $scale, $mode) = @_; $scale = $x->{_p} unless defined $scale; no strict 'refs'; my $class = ref($x); $scale = ${ $class . '::precision' } unless defined $scale; $mode = ${ $class . '::round_mode' } unless defined $mode; if (defined $scale) { $scale = $scale->can('numify') ? $scale->numify() : "$scale" if ref($scale); $scale = int($scale); } ($scale, $mode); } ############################################################################### # Constructor methods ############################################################################### sub new { # Create a new Math::BigInt object from a string or another Math::BigInt # object. See hash keys documented at top. # The argument could be an object, so avoid ||, && etc. on it. This would # cause costly overloaded code to be called. The only allowed ops are ref() # and defined. my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; # The POD says: # # "Currently, Math::BigInt->new() defaults to 0, while Math::BigInt->new('') # results in 'NaN'. This might change in the future, so use always the # following explicit forms to get a zero or NaN: # $zero = Math::BigInt->bzero(); # $nan = Math::BigInt->bnan(); # # But although this use has been discouraged for more than 10 years, people # apparently still use it, so we still support it. return $self->bzero() unless @_; my ($wanted, $a, $p, $r) = @_; # Always return a new object, so it called as an instance method, copy the # invocand, and if called as a class method, initialize a new object. $self = $selfref ? $self -> copy() : bless {}, $class; unless (defined $wanted) { #Carp::carp("Use of uninitialized value in new()"); return $self->bzero($a, $p, $r); } if (ref($wanted) && $wanted->isa($class)) { # MBI or subclass # Using "$copy = $wanted -> copy()" here fails some tests. Fixme! my $copy = $class -> copy($wanted); if ($selfref) { %$self = %$copy; } else { $self = $copy; } return $self; } $class->import() if $IMPORT == 0; # make require work # Shortcut for non-zero scalar integers with no non-zero exponent. if (!ref($wanted) && $wanted =~ / ^ ([+-]?) # optional sign ([1-9][0-9]*) # non-zero significand (\.0*)? # ... with optional zero fraction ([Ee][+-]?0+)? # optional zero exponent \z /x) { my $sgn = $1; my $abs = $2; $self->{sign} = $sgn || '+'; $self->{value} = $CALC->_new($abs); no strict 'refs'; if (defined($a) || defined($p) || defined(${"${class}::precision"}) || defined(${"${class}::accuracy"})) { $self->round($a, $p, $r) unless @_ >= 3 && !defined $a && !defined $p; } return $self; } # Handle Infs. if ($wanted =~ /^\s*([+-]?)inf(inity)?\s*\z/i) { my $sgn = $1 || '+'; $self->{sign} = $sgn . 'inf'; # set a default sign for bstr() return $class->binf($sgn); } # Handle explicit NaNs (not the ones returned due to invalid input). if ($wanted =~ /^\s*([+-]?)nan\s*\z/i) { $self = $class -> bnan(); $self->round($a, $p, $r) unless @_ >= 3 && !defined $a && !defined $p; return $self; } # Handle hexadecimal numbers. if ($wanted =~ /^\s*[+-]?0[Xx]/) { $self = $class -> from_hex($wanted); $self->round($a, $p, $r) unless @_ >= 3 && !defined $a && !defined $p; return $self; } # Handle binary numbers. if ($wanted =~ /^\s*[+-]?0[Bb]/) { $self = $class -> from_bin($wanted); $self->round($a, $p, $r) unless @_ >= 3 && !defined $a && !defined $p; return $self; } # Split string into mantissa, exponent, integer, fraction, value, and sign. my ($mis, $miv, $mfv, $es, $ev) = _split($wanted); if (!ref $mis) { if ($_trap_nan) { Carp::croak("$wanted is not a number in $class"); } $self->{value} = $CALC->_zero(); $self->{sign} = $nan; return $self; } if (!ref $miv) { # _from_hex or _from_bin $self->{value} = $mis->{value}; $self->{sign} = $mis->{sign}; return $self; # throw away $mis } # Make integer from mantissa by adjusting exponent, then convert to a # Math::BigInt. $self->{sign} = $$mis; # store sign $self->{value} = $CALC->_zero(); # for all the NaN cases my $e = int("$$es$$ev"); # exponent (avoid recursion) if ($e > 0) { my $diff = $e - CORE::length($$mfv); if ($diff < 0) { # Not integer if ($_trap_nan) { Carp::croak("$wanted not an integer in $class"); } #print "NOI 1\n"; return $upgrade->new($wanted, $a, $p, $r) if defined $upgrade; $self->{sign} = $nan; } else { # diff >= 0 # adjust fraction and add it to value #print "diff > 0 $$miv\n"; $$miv = $$miv . ($$mfv . '0' x $diff); } } else { if ($$mfv ne '') { # e <= 0 # fraction and negative/zero E => NOI if ($_trap_nan) { Carp::croak("$wanted not an integer in $class"); } #print "NOI 2 \$\$mfv '$$mfv'\n"; return $upgrade->new($wanted, $a, $p, $r) if defined $upgrade; $self->{sign} = $nan; } elsif ($e < 0) { # xE-y, and empty mfv # Split the mantissa at the decimal point. E.g., if # $$miv = 12345 and $e = -2, then $frac = 45 and $$miv = 123. my $frac = substr($$miv, $e); # $frac is fraction part substr($$miv, $e) = ""; # $$miv is now integer part if ($frac =~ /[^0]/) { if ($_trap_nan) { Carp::croak("$wanted not an integer in $class"); } #print "NOI 3\n"; return $upgrade->new($wanted, $a, $p, $r) if defined $upgrade; $self->{sign} = $nan; } } } unless ($self->{sign} eq $nan) { $self->{sign} = '+' if $$miv eq '0'; # normalize -0 => +0 $self->{value} = $CALC->_new($$miv) if $self->{sign} =~ /^[+-]$/; } # If any of the globals are set, use them to round, and store them inside # $self. Do not round for new($x, undef, undef) since that is used by MBF # to signal no rounding. $self->round($a, $p, $r) unless @_ >= 3 && !defined $a && !defined $p; $self; } # Create a Math::BigInt from a hexadecimal string. sub from_hex { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; # Don't modify constant (read-only) objects. return if $selfref && $self->modify('from_hex'); my $str = shift; # If called as a class method, initialize a new object. $self = $class -> bzero() unless $selfref; if ($str =~ s/ ^ \s* ( [+-]? ) (0?x)? ( [0-9a-fA-F]* ( _ [0-9a-fA-F]+ )* ) \s* $ //x) { # Get a "clean" version of the string, i.e., non-emtpy and with no # underscores or invalid characters. my $sign = $1; my $chrs = $3; $chrs =~ tr/_//d; $chrs = '0' unless CORE::length $chrs; # The library method requires a prefix. $self->{value} = $CALC->_from_hex('0x' . $chrs); # Place the sign. $self->{sign} = $sign eq '-' && ! $CALC->_is_zero($self->{value}) ? '-' : '+'; return $self; } # CORE::hex() parses as much as it can, and ignores any trailing garbage. # For backwards compatibility, we return NaN. return $self->bnan(); } # Create a Math::BigInt from an octal string. sub from_oct { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; # Don't modify constant (read-only) objects. return if $selfref && $self->modify('from_oct'); my $str = shift; # If called as a class method, initialize a new object. $self = $class -> bzero() unless $selfref; if ($str =~ s/ ^ \s* ( [+-]? ) ( [0-7]* ( _ [0-7]+ )* ) \s* $ //x) { # Get a "clean" version of the string, i.e., non-emtpy and with no # underscores or invalid characters. my $sign = $1; my $chrs = $2; $chrs =~ tr/_//d; $chrs = '0' unless CORE::length $chrs; # The library method requires a prefix. $self->{value} = $CALC->_from_oct('0' . $chrs); # Place the sign. $self->{sign} = $sign eq '-' && ! $CALC->_is_zero($self->{value}) ? '-' : '+'; return $self; } # CORE::oct() parses as much as it can, and ignores any trailing garbage. # For backwards compatibility, we return NaN. return $self->bnan(); } # Create a Math::BigInt from a binary string. sub from_bin { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; # Don't modify constant (read-only) objects. return if $selfref && $self->modify('from_bin'); my $str = shift; # If called as a class method, initialize a new object. $self = $class -> bzero() unless $selfref; if ($str =~ s/ ^ \s* ( [+-]? ) (0?b)? ( [01]* ( _ [01]+ )* ) \s* $ //x) { # Get a "clean" version of the string, i.e., non-emtpy and with no # underscores or invalid characters. my $sign = $1; my $chrs = $3; $chrs =~ tr/_//d; $chrs = '0' unless CORE::length $chrs; # The library method requires a prefix. $self->{value} = $CALC->_from_bin('0b' . $chrs); # Place the sign. $self->{sign} = $sign eq '-' && ! $CALC->_is_zero($self->{value}) ? '-' : '+'; return $self; } # For consistency with from_hex() and from_oct(), we return NaN when the # input is invalid. return $self->bnan(); } # Create a Math::BigInt from a byte string. sub from_bytes { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; # Don't modify constant (read-only) objects. return if $selfref && $self->modify('from_bytes'); Carp::croak("from_bytes() requires a newer version of the $CALC library.") unless $CALC->can('_from_bytes'); my $str = shift; # If called as a class method, initialize a new object. $self = $class -> bzero() unless $selfref; $self -> {sign} = '+'; $self -> {value} = $CALC -> _from_bytes($str); return $self; } sub bzero { # create/assign '+0' if (@_ == 0) { #Carp::carp("Using bzero() as a function is deprecated;", # " use bzero() 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 # Don't modify constant (read-only) objects. return if $selfref && $self->modify('bzero'); $self = bless {}, $class unless $selfref; $self->{sign} = '+'; $self->{value} = $CALC->_zero(); 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}); } } return $self; } sub bone { # Create or assign '+1' (or -1 if given sign '-'). 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__; } my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; $self->import() if $IMPORT == 0; # make require work # Don't modify constant (read-only) objects. return if $selfref && $self->modify('bone'); my $sign = shift; $sign = defined $sign && $sign =~ /^\s*-/ ? "-" : "+"; $self = bless {}, $class unless $selfref; $self->{sign} = $sign; $self->{value} = $CALC->_one(); 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}); } } return $self; } sub binf { # create/assign a '+inf' or '-inf' 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__; } my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; { no strict 'refs'; if (${"${class}::_trap_inf"}) { Carp::croak("Tried to create +-inf in $class->binf()"); } } $self->import() if $IMPORT == 0; # make require work # Don't modify constant (read-only) objects. return if $selfref && $self->modify('binf'); my $sign = shift; $sign = defined $sign && $sign =~ /^\s*-/ ? "-" : "+"; $self = bless {}, $class unless $selfref; $self -> {sign} = $sign . 'inf'; $self -> {value} = $CALC -> _zero(); return $self; } sub bnan { # create/assign a 'NaN' if (@_ == 0) { #Carp::carp("Using bnan() as a function is deprecated;", # " use bnan() as a method instead"); unshift @_, __PACKAGE__; } my $self = shift; my $selfref = ref($self); my $class = $selfref || $self; { no strict 'refs'; if (${"${class}::_trap_nan"}) { Carp::croak("Tried to create NaN in $class->bnan()"); } } $self->import() if $IMPORT == 0; # make require work # Don't modify constant (read-only) objects. return if $selfref && $self->modify('bnan'); $self = bless {}, $class unless $selfref; $self -> {sign} = $nan; $self -> {value} = $CALC -> _zero(); return $self; } sub bpi { # Calculate PI to N digits. Unless upgrading is in effect, returns the # result truncated to an integer, that is, always returns '3'. my ($self, $n) = @_; if (@_ == 1) { # called like Math::BigInt::bpi(10); $n = $self; $self = $class; } $self = ref($self) if ref($self); return $upgrade->new($n) if defined $upgrade; # hard-wired to "3" $self->new(3); } sub copy { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; # If called as a class method, the object to copy is the next argument. $self = shift() unless $selfref; my $copy = bless {}, $class; $copy->{sign} = $self->{sign}; $copy->{value} = $CALC->_copy($self->{value}); $copy->{_a} = $self->{_a} if exists $self->{_a}; $copy->{_p} = $self->{_p} if exists $self->{_p}; return $copy; } sub as_number { # An object might be asked to return itself as bigint on certain overloaded # operations. This does exactly this, so that sub classes can simple inherit # it or override with their own integer conversion routine. $_[0]->copy(); } ############################################################################### # Boolean methods ############################################################################### sub is_zero { # return true if arg (BINT or num_str) is zero (array '+', '0') my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); return 0 if $x->{sign} !~ /^\+$/; # -, NaN & +-inf aren't $CALC->_is_zero($x->{value}); } sub is_one { # return true if arg (BINT or num_str) is +1, or -1 if sign is given my ($class, $x, $sign) = ref($_[0]) ? (undef, @_) : objectify(1, @_); $sign = '+' if !defined $sign || $sign ne '-'; return 0 if $x->{sign} ne $sign; # -1 != +1, NaN, +-inf aren't either $CALC->_is_one($x->{value}); } sub is_finite { my $x = shift; return $x->{sign} eq '+' || $x->{sign} eq '-'; } sub is_inf { # return true if arg (BINT or num_str) is +-inf my ($class, $x, $sign) = ref($_[0]) ? (undef, @_) : objectify(1, @_); if (defined $sign) { $sign = '[+-]inf' if $sign eq ''; # +- doesn't matter, only that's inf $sign = "[$1]inf" if $sign =~ /^([+-])(inf)?$/; # extract '+' or '-' return $x->{sign} =~ /^$sign$/ ? 1 : 0; } $x->{sign} =~ /^[+-]inf$/ ? 1 : 0; # only +-inf is infinity } sub is_nan { # return true if arg (BINT or num_str) is NaN my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); $x->{sign} eq $nan ? 1 : 0; } sub is_positive { # return true when arg (BINT or num_str) is positive (> 0) my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); return 1 if $x->{sign} eq '+inf'; # +inf is positive # 0+ is neither positive nor negative ($x->{sign} eq '+' && !$x->is_zero()) ? 1 : 0; } sub is_negative { # return true when arg (BINT or num_str) is negative (< 0) my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); $x->{sign} =~ /^-/ ? 1 : 0; # -inf is negative, but NaN is not } sub is_odd { # return true when arg (BINT or num_str) is odd, false for even my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); return 0 if $x->{sign} !~ /^[+-]$/; # NaN & +-inf aren't $CALC->_is_odd($x->{value}); } sub is_even { # return true when arg (BINT or num_str) is even, false for odd my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); return 0 if $x->{sign} !~ /^[+-]$/; # NaN & +-inf aren't $CALC->_is_even($x->{value}); } sub is_int { # return true when arg (BINT or num_str) is an integer # always true for Math::BigInt, but different for Math::BigFloat objects my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); $x->{sign} =~ /^[+-]$/ ? 1 : 0; # inf/-inf/NaN aren't } ############################################################################### # Comparison methods ############################################################################### sub bcmp { # Compares 2 values. Returns one of undef, <0, =0, >0. (suitable for sort) # (BINT or num_str, BINT or num_str) return cond_code # set up parameters my ($class, $x, $y) = ref($_[0]) && ref($_[0]) eq ref($_[1]) ? (ref($_[0]), @_) : objectify(2, @_); return $upgrade->bcmp($x, $y) if defined $upgrade && ((!$x->isa($class)) || (!$y->isa($class))); if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/)) { # handle +-inf and NaN return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan)); return 0 if $x->{sign} eq $y->{sign} && $x->{sign} =~ /^[+-]inf$/; return +1 if $x->{sign} eq '+inf'; return -1 if $x->{sign} eq '-inf'; return -1 if $y->{sign} eq '+inf'; return +1; } # check sign for speed first return 1 if $x->{sign} eq '+' && $y->{sign} eq '-'; # does also 0 <=> -y return -1 if $x->{sign} eq '-' && $y->{sign} eq '+'; # does also -x <=> 0 # have same sign, so compare absolute values. Don't make tests for zero # here because it's actually slower than testing in Calc (especially w/ Pari # et al) # post-normalized compare for internal use (honors signs) if ($x->{sign} eq '+') { # $x and $y both > 0 return $CALC->_acmp($x->{value}, $y->{value}); } # $x && $y both < 0 $CALC->_acmp($y->{value}, $x->{value}); # swapped acmp (lib returns 0, 1, -1) } sub bacmp { # Compares 2 values, ignoring their signs. # Returns one of undef, <0, =0, >0. (suitable for sort) # (BINT, BINT) return cond_code # set up parameters my ($class, $x, $y) = ref($_[0]) && ref($_[0]) eq ref($_[1]) ? (ref($_[0]), @_) : objectify(2, @_); return $upgrade->bacmp($x, $y) if defined $upgrade && ((!$x->isa($class)) || (!$y->isa($class))); if (($x->{sign} !~ /^[+-]$/) || ($y->{sign} !~ /^[+-]$/)) { # handle +-inf and NaN return undef if (($x->{sign} eq $nan) || ($y->{sign} eq $nan)); return 0 if $x->{sign} =~ /^[+-]inf$/ && $y->{sign} =~ /^[+-]inf$/; return 1 if $x->{sign} =~ /^[+-]inf$/ && $y->{sign} !~ /^[+-]inf$/; return -1; } $CALC->_acmp($x->{value}, $y->{value}); # lib does only 0, 1, -1 } sub beq { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; Carp::croak 'beq() is an instance method, not a class method' unless $selfref; Carp::croak 'Wrong number of arguments for beq()' unless @_ == 1; my $cmp = $self -> bcmp(shift); return defined($cmp) && ! $cmp; } sub bne { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; Carp::croak 'bne() is an instance method, not a class method' unless $selfref; Carp::croak 'Wrong number of arguments for bne()' unless @_ == 1; my $cmp = $self -> bcmp(shift); return defined($cmp) && ! $cmp ? '' : 1; } sub blt { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; Carp::croak 'blt() is an instance method, not a class method' unless $selfref; Carp::croak 'Wrong number of arguments for blt()' unless @_ == 1; my $cmp = $self -> bcmp(shift); return defined($cmp) && $cmp < 0; } sub ble { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; Carp::croak 'ble() is an instance method, not a class method' unless $selfref; Carp::croak 'Wrong number of arguments for ble()' unless @_ == 1; my $cmp = $self -> bcmp(shift); return defined($cmp) && $cmp <= 0; } sub bgt { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; Carp::croak 'bgt() is an instance method, not a class method' unless $selfref; Carp::croak 'Wrong number of arguments for bgt()' unless @_ == 1; my $cmp = $self -> bcmp(shift); return defined($cmp) && $cmp > 0; } sub bge { my $self = shift; my $selfref = ref $self; my $class = $selfref || $self; Carp::croak 'bge() is an instance method, not a class method' unless $selfref; Carp::croak 'Wrong number of arguments for bge()' unless @_ == 1; my $cmp = $self -> bcmp(shift); return defined($cmp) && $cmp >= 0; } ############################################################################### # Arithmetic methods ############################################################################### sub bneg { # (BINT or num_str) return BINT # negate number or make a negated number from string my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); return $x if $x->modify('bneg'); # for +0 do not negate (to have always normalized +0). Does nothing for 'NaN' $x->{sign} =~ tr/+-/-+/ unless ($x->{sign} eq '+' && $CALC->_is_zero($x->{value})); $x; } sub babs { # (BINT or num_str) return BINT # make number absolute, or return absolute BINT from string my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); return $x if $x->modify('babs'); # post-normalized abs for internal use (does nothing for NaN) $x->{sign} =~ s/^-/+/; $x; } sub bsgn { # Signum function. my $self = shift; return $self if $self->modify('bsgn'); return $self -> bone("+") if $self -> is_pos(); return $self -> bone("-") if $self -> is_neg(); return $self; # zero or NaN } sub bnorm { # (numstr or BINT) return BINT # Normalize number -- no-op here my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); $x; } sub binc { # increment arg by one my ($class, $x, $a, $p, $r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_); return $x if $x->modify('binc'); if ($x->{sign} eq '+') { $x->{value} = $CALC->_inc($x->{value}); return $x->round($a, $p, $r); } elsif ($x->{sign} eq '-') { $x->{value} = $CALC->_dec($x->{value}); $x->{sign} = '+' if $CALC->_is_zero($x->{value}); # -1 +1 => -0 => +0 return $x->round($a, $p, $r); } # inf, nan handling etc $x->badd($class->bone(), $a, $p, $r); # badd does round } sub bdec { # decrement arg by one my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_); return $x if $x->modify('bdec'); if ($x->{sign} eq '-') { # x already < 0 $x->{value} = $CALC->_inc($x->{value}); } else { return $x->badd($class->bone('-'), @r) unless $x->{sign} eq '+'; # inf or NaN # >= 0 if ($CALC->_is_zero($x->{value})) { # == 0 $x->{value} = $CALC->_one(); $x->{sign} = '-'; # 0 => -1 } else { # > 0 $x->{value} = $CALC->_dec($x->{value}); } } $x->round(@r); } #sub bstrcmp { # my $self = shift; # my $selfref = ref $self; # my $class = $selfref || $self; # # Carp::croak 'bstrcmp() is an instance method, not a class method' # unless $selfref; # Carp::croak 'Wrong number of arguments for bstrcmp()' unless @_ == 1; # # return $self -> bstr() CORE::cmp shift; #} # #sub bstreq { # my $self = shift; # my $selfref = ref $self; # my $class = $selfref || $self; # # Carp::croak 'bstreq() is an instance method, not a class method' # unless $selfref; # Carp::croak 'Wrong number of arguments for bstreq()' unless @_ == 1; # # my $cmp = $self -> bstrcmp(shift); # return defined($cmp) && ! $cmp; #} # #sub bstrne { # my $self = shift; # my $selfref = ref $self; # my $class = $selfref || $self; # # Carp::croak 'bstrne() is an instance method, not a class method' # unless $selfref; # Carp::croak 'Wrong number of arguments for bstrne()' unless @_ == 1; # # my $cmp = $self -> bstrcmp(shift); # return defined($cmp) && ! $cmp ? '' : 1; #} # #sub bstrlt { # my $self = shift; # my $selfref = ref $self; # my $class = $selfref || $self; # # Carp::croak 'bstrlt() is an instance method, not a class method' # unless $selfref; # Carp::croak 'Wrong number of arguments for bstrlt()' unless @_ == 1; # # my $cmp = $self -> bstrcmp(shift); # return defined($cmp) && $cmp < 0; #} # #sub bstrle { # my $self = shift; # my $selfref = ref $self; # my $class = $selfref || $self; # # Carp::croak 'bstrle() is an instance method, not a class method' # unless $selfref; # Carp::croak 'Wrong number of arguments for bstrle()' unless @_ == 1; # # my $cmp = $self -> bstrcmp(shift); # return defined($cmp) && $cmp <= 0; #} # #sub bstrgt { # my $self = shift; # my $selfref = ref $self; # my $class = $selfref || $self; # # Carp::croak 'bstrgt() is an instance method, not a class method' # unless $selfref; # Carp::croak 'Wrong number of arguments for bstrgt()' unless @_ == 1; # # my $cmp = $self -> bstrcmp(shift); # return defined($cmp) && $cmp > 0; #} # #sub bstrge { # my $self = shift; # my $selfref = ref $self; # my $class = $selfref || $self; # # Carp::croak 'bstrge() is an instance method, not a class method' # unless $selfref; # Carp::croak 'Wrong number of arguments for bstrge()' unless @_ == 1; # # my $cmp = $self -> bstrcmp(shift); # return defined($cmp) && $cmp >= 0; #} sub badd { # add second arg (BINT or string) to first (BINT) (modifies first) # return result as BINT # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } return $x if $x->modify('badd'); return $upgrade->badd($upgrade->new($x), $upgrade->new($y), @r) if defined $upgrade && ((!$x->isa($class)) || (!$y->isa($class))); $r[3] = $y; # no push! # inf and NaN handling if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/) { # NaN first return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan)); # inf handling if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/)) { # +inf++inf or -inf+-inf => same, rest is NaN return $x if $x->{sign} eq $y->{sign}; return $x->bnan(); } # +-inf + something => +inf # something +-inf => +-inf $x->{sign} = $y->{sign}, return $x if $y->{sign} =~ /^[+-]inf$/; return $x; } my ($sx, $sy) = ($x->{sign}, $y->{sign}); # get signs if ($sx eq $sy) { $x->{value} = $CALC->_add($x->{value}, $y->{value}); # same sign, abs add } else { my $a = $CALC->_acmp ($y->{value}, $x->{value}); # absolute compare if ($a > 0) { $x->{value} = $CALC->_sub($y->{value}, $x->{value}, 1); # abs sub w/ swap $x->{sign} = $sy; } elsif ($a == 0) { # speedup, if equal, set result to 0 $x->{value} = $CALC->_zero(); $x->{sign} = '+'; } else # a < 0 { $x->{value} = $CALC->_sub($x->{value}, $y->{value}); # abs sub } } $x->round(@r); } sub bsub { # (BINT or num_str, BINT or num_str) return BINT # subtract second arg from first, modify first # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } return $x if $x -> modify('bsub'); return $upgrade -> new($x) -> bsub($upgrade -> new($y), @r) if defined $upgrade && (!$x -> isa($class) || !$y -> isa($class)); return $x -> round(@r) if $y -> is_zero(); # To correctly handle the lone special case $x -> bsub($x), we note the # sign of $x, then flip the sign from $y, and if the sign of $x did change, # too, then we caught the special case: my $xsign = $x -> {sign}; $y -> {sign} =~ tr/+-/-+/; # does nothing for NaN if ($xsign ne $x -> {sign}) { # special case of $x -> bsub($x) results in 0 return $x -> bzero(@r) if $xsign =~ /^[+-]$/; return $x -> bnan(); # NaN, -inf, +inf } $x -> badd($y, @r); # badd does not leave internal zeros $y -> {sign} =~ tr/+-/-+/; # refix $y (does nothing for NaN) $x; # already rounded by badd() or no rounding } sub bmul { # multiply the first number by the second number # (BINT or num_str, BINT or num_str) return BINT # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } return $x if $x->modify('bmul'); return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan)); # inf handling if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/)) { return $x->bnan() if $x->is_zero() || $y->is_zero(); # result will always be +-inf: # +inf * +/+inf => +inf, -inf * -/-inf => +inf # +inf * -/-inf => -inf, -inf * +/+inf => -inf return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/); return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/); return $x->binf('-'); } return $upgrade->bmul($x, $upgrade->new($y), @r) if defined $upgrade && !$y->isa($class); $r[3] = $y; # no push here $x->{sign} = $x->{sign} eq $y->{sign} ? '+' : '-'; # +1 * +1 or -1 * -1 => + $x->{value} = $CALC->_mul($x->{value}, $y->{value}); # do actual math $x->{sign} = '+' if $CALC->_is_zero($x->{value}); # no -0 $x->round(@r); } sub bmuladd { # multiply two numbers and then add the third to the result # (BINT or num_str, BINT or num_str, BINT or num_str) return BINT # set up parameters my ($class, $x, $y, $z, @r) = objectify(3, @_); return $x if $x->modify('bmuladd'); return $x->bnan() if (($x->{sign} eq $nan) || ($y->{sign} eq $nan) || ($z->{sign} eq $nan)); # inf handling of x and y if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/)) { return $x->bnan() if $x->is_zero() || $y->is_zero(); # result will always be +-inf: # +inf * +/+inf => +inf, -inf * -/-inf => +inf # +inf * -/-inf => -inf, -inf * +/+inf => -inf return $x->binf() if ($x->{sign} =~ /^\+/ && $y->{sign} =~ /^\+/); return $x->binf() if ($x->{sign} =~ /^-/ && $y->{sign} =~ /^-/); return $x->binf('-'); } # inf handling x*y and z if (($z->{sign} =~ /^[+-]inf$/)) { # something +-inf => +-inf $x->{sign} = $z->{sign}, return $x if $z->{sign} =~ /^[+-]inf$/; } return $upgrade->bmuladd($x, $upgrade->new($y), $upgrade->new($z), @r) if defined $upgrade && (!$y->isa($class) || !$z->isa($class) || !$x->isa($class)); # TODO: what if $y and $z have A or P set? $r[3] = $z; # no push here $x->{sign} = $x->{sign} eq $y->{sign} ? '+' : '-'; # +1 * +1 or -1 * -1 => + $x->{value} = $CALC->_mul($x->{value}, $y->{value}); # do actual math $x->{sign} = '+' if $CALC->_is_zero($x->{value}); # no -0 my ($sx, $sz) = ( $x->{sign}, $z->{sign} ); # get signs if ($sx eq $sz) { $x->{value} = $CALC->_add($x->{value}, $z->{value}); # same sign, abs add } else { my $a = $CALC->_acmp ($z->{value}, $x->{value}); # absolute compare if ($a > 0) { $x->{value} = $CALC->_sub($z->{value}, $x->{value}, 1); # abs sub w/ swap $x->{sign} = $sz; } elsif ($a == 0) { # speedup, if equal, set result to 0 $x->{value} = $CALC->_zero(); $x->{sign} = '+'; } else # a < 0 { $x->{value} = $CALC->_sub($x->{value}, $z->{value}); # abs sub } } $x->round(@r); } sub bdiv { # This does floored division, where the quotient is floored, i.e., rounded # towards negative infinity. As a consequence, the remainder has the same # sign as the divisor. # Set up parameters. my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify() is costly, so avoid it if we can. if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } return $x if $x -> modify('bdiv'); my $wantarray = wantarray; # call only once # At least one argument is NaN. Return NaN for both quotient and the # modulo/remainder. if ($x -> is_nan() || $y -> is_nan()) { return $wantarray ? ($x -> bnan(), $class -> bnan()) : $x -> bnan(); } # Divide by zero and modulo zero. # # Division: Use the common convention that x / 0 is inf with the same sign # as x, except when x = 0, where we return NaN. This is also what earlier # versions did. # # Modulo: In modular arithmetic, the congruence relation z = x (mod y) # means that there is some integer k such that z - x = k y. If y = 0, we # get z - x = 0 or z = x. This is also what earlier versions did, except # that 0 % 0 returned NaN. # # inf / 0 = inf inf % 0 = inf # 5 / 0 = inf 5 % 0 = 5 # 0 / 0 = NaN 0 % 0 = 0 # -5 / 0 = -inf -5 % 0 = -5 # -inf / 0 = -inf -inf % 0 = -inf if ($y -> is_zero()) { my $rem; if ($wantarray) { $rem = $x -> copy(); } if ($x -> is_zero()) { $x -> bnan(); } else { $x -> binf($x -> {sign}); } return $wantarray ? ($x, $rem) : $x; } # Numerator (dividend) is +/-inf, and denominator is finite and non-zero. # The divide by zero cases are covered above. In all of the cases listed # below we return the same as core Perl. # # inf / -inf = NaN inf % -inf = NaN # inf / -5 = -inf inf % -5 = NaN # inf / 5 = inf inf % 5 = NaN # inf / inf = NaN inf % inf = NaN # # -inf / -inf = NaN -inf % -inf = NaN # -inf / -5 = inf -inf % -5 = NaN # -inf / 5 = -inf -inf % 5 = NaN # -inf / inf = NaN -inf % inf = NaN if ($x -> is_inf()) { my $rem; $rem = $class -> bnan() if $wantarray; if ($y -> is_inf()) { $x -> bnan(); } else { my $sign = $x -> bcmp(0) == $y -> bcmp(0) ? '+' : '-'; $x -> binf($sign); } return $wantarray ? ($x, $rem) : $x; } # Denominator (divisor) is +/-inf. The cases when the numerator is +/-inf # are covered above. In the modulo cases (in the right column) we return # the same as core Perl, which does floored division, so for consistency we # also do floored division in the division cases (in the left column). # # -5 / inf = -1 -5 % inf = inf # 0 / inf = 0 0 % inf = 0 # 5 / inf = 0 5 % inf = 5 # # -5 / -inf = 0 -5 % -inf = -5 # 0 / -inf = 0 0 % -inf = 0 # 5 / -inf = -1 5 % -inf = -inf if ($y -> is_inf()) { my $rem; if ($x -> is_zero() || $x -> bcmp(0) == $y -> bcmp(0)) { $rem = $x -> copy() if $wantarray; $x -> bzero(); } else { $rem = $class -> binf($y -> {sign}) if $wantarray; $x -> bone('-'); } return $wantarray ? ($x, $rem) : $x; } # At this point, both the numerator and denominator are finite numbers, and # the denominator (divisor) is non-zero. return $upgrade -> bdiv($upgrade -> new($x), $upgrade -> new($y), @r) if defined $upgrade; $r[3] = $y; # no push! # Inialize remainder. my $rem = $class -> bzero(); # Are both operands the same object, i.e., like $x -> bdiv($x)? If so, # flipping the sign of $y also flips the sign of $x. my $xsign = $x -> {sign}; my $ysign = $y -> {sign}; $y -> {sign} =~ tr/+-/-+/; # Flip the sign of $y, and see ... my $same = $xsign ne $x -> {sign}; # ... if that changed the sign of $x. $y -> {sign} = $ysign; # Re-insert the original sign. if ($same) { $x -> bone(); } else { ($x -> {value}, $rem -> {value}) = $CALC -> _div($x -> {value}, $y -> {value}); if ($CALC -> _is_zero($rem -> {value})) { if ($xsign eq $ysign || $CALC -> _is_zero($x -> {value})) { $x -> {sign} = '+'; } else { $x -> {sign} = '-'; } } else { if ($xsign eq $ysign) { $x -> {sign} = '+'; } else { if ($xsign eq '+') { $x -> badd(1); } else { $x -> bsub(1); } $x -> {sign} = '-'; } } } $x -> round(@r); if ($wantarray) { unless ($CALC -> _is_zero($rem -> {value})) { if ($xsign ne $ysign) { $rem = $y -> copy() -> babs() -> bsub($rem); } $rem -> {sign} = $ysign; } $rem -> {_a} = $x -> {_a}; $rem -> {_p} = $x -> {_p}; $rem -> round(@r); return ($x, $rem); } return $x; } sub btdiv { # This does truncated division, where the quotient is truncted, i.e., # rounded towards zero. # # ($q, $r) = $x -> btdiv($y) returns $q and $r so that $q is int($x / $y) # and $q * $y + $r = $x. # Set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if we can. if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } return $x if $x -> modify('btdiv'); my $wantarray = wantarray; # call only once # At least one argument is NaN. Return NaN for both quotient and the # modulo/remainder. if ($x -> is_nan() || $y -> is_nan()) { return $wantarray ? ($x -> bnan(), $class -> bnan()) : $x -> bnan(); } # Divide by zero and modulo zero. # # Division: Use the common convention that x / 0 is inf with the same sign # as x, except when x = 0, where we return NaN. This is also what earlier # versions did. # # Modulo: In modular arithmetic, the congruence relation z = x (mod y) # means that there is some integer k such that z - x = k y. If y = 0, we # get z - x = 0 or z = x. This is also what earlier versions did, except # that 0 % 0 returned NaN. # # inf / 0 = inf inf % 0 = inf # 5 / 0 = inf 5 % 0 = 5 # 0 / 0 = NaN 0 % 0 = 0 # -5 / 0 = -inf -5 % 0 = -5 # -inf / 0 = -inf -inf % 0 = -inf if ($y -> is_zero()) { my $rem; if ($wantarray) { $rem = $x -> copy(); } if ($x -> is_zero()) { $x -> bnan(); } else { $x -> binf($x -> {sign}); } return $wantarray ? ($x, $rem) : $x; } # Numerator (dividend) is +/-inf, and denominator is finite and non-zero. # The divide by zero cases are covered above. In all of the cases listed # below we return the same as core Perl. # # inf / -inf = NaN inf % -inf = NaN # inf / -5 = -inf inf % -5 = NaN # inf / 5 = inf inf % 5 = NaN # inf / inf = NaN inf % inf = NaN # # -inf / -inf = NaN -inf % -inf = NaN # -inf / -5 = inf -inf % -5 = NaN # -inf / 5 = -inf -inf % 5 = NaN # -inf / inf = NaN -inf % inf = NaN if ($x -> is_inf()) { my $rem; $rem = $class -> bnan() if $wantarray; if ($y -> is_inf()) { $x -> bnan(); } else { my $sign = $x -> bcmp(0) == $y -> bcmp(0) ? '+' : '-'; $x -> binf($sign); } return $wantarray ? ($x, $rem) : $x; } # Denominator (divisor) is +/-inf. The cases when the numerator is +/-inf # are covered above. In the modulo cases (in the right column) we return # the same as core Perl, which does floored division, so for consistency we # also do floored division in the division cases (in the left column). # # -5 / inf = 0 -5 % inf = -5 # 0 / inf = 0 0 % inf = 0 # 5 / inf = 0 5 % inf = 5 # # -5 / -inf = 0 -5 % -inf = -5 # 0 / -inf = 0 0 % -inf = 0 # 5 / -inf = 0 5 % -inf = 5 if ($y -> is_inf()) { my $rem; $rem = $x -> copy() if $wantarray; $x -> bzero(); return $wantarray ? ($x, $rem) : $x; } return $upgrade -> btdiv($upgrade -> new($x), $upgrade -> new($y), @r) if defined $upgrade; $r[3] = $y; # no push! # Inialize remainder. my $rem = $class -> bzero(); # Are both operands the same object, i.e., like $x -> bdiv($x)? If so, # flipping the sign of $y also flips the sign of $x. my $xsign = $x -> {sign}; my $ysign = $y -> {sign}; $y -> {sign} =~ tr/+-/-+/; # Flip the sign of $y, and see ... my $same = $xsign ne $x -> {sign}; # ... if that changed the sign of $x. $y -> {sign} = $ysign; # Re-insert the original sign. if ($same) { $x -> bone(); } else { ($x -> {value}, $rem -> {value}) = $CALC -> _div($x -> {value}, $y -> {value}); $x -> {sign} = $xsign eq $ysign ? '+' : '-'; $x -> {sign} = '+' if $CALC -> _is_zero($x -> {value}); $x -> round(@r); } if (wantarray) { $rem -> {sign} = $xsign; $rem -> {sign} = '+' if $CALC -> _is_zero($rem -> {value}); $rem -> {_a} = $x -> {_a}; $rem -> {_p} = $x -> {_p}; $rem -> round(@r); return ($x, $rem); } return $x; } sub bmod { # This is the remainder after floored division. # Set up parameters. my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } return $x if $x -> modify('bmod'); $r[3] = $y; # no push! # At least one argument is NaN. if ($x -> is_nan() || $y -> is_nan()) { return $x -> bnan(); } # Modulo zero. See documentation for bdiv(). if ($y -> is_zero()) { return $x; } # Numerator (dividend) is +/-inf. if ($x -> is_inf()) { return $x -> bnan(); } # Denominator (divisor) is +/-inf. if ($y -> is_inf()) { if ($x -> is_zero() || $x -> bcmp(0) == $y -> bcmp(0)) { return $x; } else { return $x -> binf($y -> sign()); } } # Calc new sign and in case $y == +/- 1, return $x. $x -> {value} = $CALC -> _mod($x -> {value}, $y -> {value}); if ($CALC -> _is_zero($x -> {value})) { $x -> {sign} = '+'; # do not leave -0 } else { $x -> {value} = $CALC -> _sub($y -> {value}, $x -> {value}, 1) # $y-$x if ($x -> {sign} ne $y -> {sign}); $x -> {sign} = $y -> {sign}; } $x -> round(@r); } sub btmod { # Remainder after truncated division. # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } return $x if $x -> modify('btmod'); # At least one argument is NaN. if ($x -> is_nan() || $y -> is_nan()) { return $x -> bnan(); } # Modulo zero. See documentation for btdiv(). if ($y -> is_zero()) { return $x; } # Numerator (dividend) is +/-inf. if ($x -> is_inf()) { return $x -> bnan(); } # Denominator (divisor) is +/-inf. if ($y -> is_inf()) { return $x; } return $upgrade -> btmod($upgrade -> new($x), $upgrade -> new($y), @r) if defined $upgrade; $r[3] = $y; # no push! my $xsign = $x -> {sign}; my $ysign = $y -> {sign}; $x -> {value} = $CALC -> _mod($x -> {value}, $y -> {value}); $x -> {sign} = $xsign; $x -> {sign} = '+' if $CALC -> _is_zero($x -> {value}); $x -> round(@r); return $x; } sub bmodinv { # Return modular multiplicative inverse: # # z is the modular inverse of x (mod y) if and only if # # x*z ≡ 1 (mod y) # # If the modulus y is larger than one, x and z are relative primes (i.e., # their greatest common divisor is one). # # If no modular multiplicative inverse exists, NaN is returned. # set up parameters my ($class, $x, $y, @r) = (undef, @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } return $x if $x->modify('bmodinv'); # Return NaN if one or both arguments is +inf, -inf, or nan. return $x->bnan() if ($y->{sign} !~ /^[+-]$/ || $x->{sign} !~ /^[+-]$/); # Return NaN if $y is zero; 1 % 0 makes no sense. return $x->bnan() if $y->is_zero(); # Return 0 in the trivial case. $x % 1 or $x % -1 is zero for all finite # integers $x. return $x->bzero() if ($y->is_one() || $y->is_one('-')); # Return NaN if $x = 0, or $x modulo $y is zero. The only valid case when # $x = 0 is when $y = 1 or $y = -1, but that was covered above. # # Note that computing $x modulo $y here affects the value we'll feed to # $CALC->_modinv() below when $x and $y have opposite signs. E.g., if $x = # 5 and $y = 7, those two values are fed to _modinv(), but if $x = -5 and # $y = 7, the values fed to _modinv() are $x = 2 (= -5 % 7) and $y = 7. # The value if $x is affected only when $x and $y have opposite signs. $x->bmod($y); return $x->bnan() if $x->is_zero(); # Compute the modular multiplicative inverse of the absolute values. We'll # correct for the signs of $x and $y later. Return NaN if no GCD is found. ($x->{value}, $x->{sign}) = $CALC->_modinv($x->{value}, $y->{value}); return $x->bnan() if !defined $x->{value}; # Library inconsistency workaround: _modinv() in Math::BigInt::GMP versions # <= 1.32 return undef rather than a "+" for the sign. $x->{sign} = '+' unless defined $x->{sign}; # When one or both arguments are negative, we have the following # relations. If x and y are positive: # # modinv(-x, -y) = -modinv(x, y) # modinv(-x, y) = y - modinv(x, y) = -modinv(x, y) (mod y) # modinv( x, -y) = modinv(x, y) - y = modinv(x, y) (mod -y) # We must swap the sign of the result if the original $x is negative. # However, we must compensate for ignoring the signs when computing the # inverse modulo. The net effect is that we must swap the sign of the # result if $y is negative. $x -> bneg() if $y->{sign} eq '-'; # Compute $x modulo $y again after correcting the sign. $x -> bmod($y) if $x->{sign} ne $y->{sign}; return $x; } sub bmodpow { # Modular exponentiation. Raises a very large number to a very large exponent # in a given very large modulus quickly, thanks to binary exponentiation. # Supports negative exponents. my ($class, $num, $exp, $mod, @r) = objectify(3, @_); return $num if $num->modify('bmodpow'); # When the exponent 'e' is negative, use the following relation, which is # based on finding the multiplicative inverse 'd' of 'b' modulo 'm': # # b^(-e) (mod m) = d^e (mod m) where b*d = 1 (mod m) $num->bmodinv($mod) if ($exp->{sign} eq '-'); # Check for valid input. All operands must be finite, and the modulus must be # non-zero. return $num->bnan() if ($num->{sign} =~ /NaN|inf/ || # NaN, -inf, +inf $exp->{sign} =~ /NaN|inf/ || # NaN, -inf, +inf $mod->{sign} =~ /NaN|inf/); # NaN, -inf, +inf # Modulo zero. See documentation for Math::BigInt's bmod() method. if ($mod -> is_zero()) { if ($num -> is_zero()) { return $class -> bnan(); } else { return $num -> copy(); } } # Compute 'a (mod m)', ignoring the signs on 'a' and 'm'. If the resulting # value is zero, the output is also zero, regardless of the signs on 'a' and # 'm'. my $value = $CALC->_modpow($num->{value}, $exp->{value}, $mod->{value}); my $sign = '+'; # If the resulting value is non-zero, we have four special cases, depending # on the signs on 'a' and 'm'. unless ($CALC->_is_zero($value)) { # There is a negative sign on 'a' (= $num**$exp) only if the number we # are exponentiating ($num) is negative and the exponent ($exp) is odd. if ($num->{sign} eq '-' && $exp->is_odd()) { # When both the number 'a' and the modulus 'm' have a negative sign, # use this relation: # # -a (mod -m) = -(a (mod m)) if ($mod->{sign} eq '-') { $sign = '-'; } # When only the number 'a' has a negative sign, use this relation: # # -a (mod m) = m - (a (mod m)) else { # Use copy of $mod since _sub() modifies the first argument. my $mod = $CALC->_copy($mod->{value}); $value = $CALC->_sub($mod, $value); $sign = '+'; } } else { # When only the modulus 'm' has a negative sign, use this relation: # # a (mod -m) = (a (mod m)) - m # = -(m - (a (mod m))) if ($mod->{sign} eq '-') { # Use copy of $mod since _sub() modifies the first argument. my $mod = $CALC->_copy($mod->{value}); $value = $CALC->_sub($mod, $value); $sign = '-'; } # When neither the number 'a' nor the modulus 'm' have a negative # sign, directly return the already computed value. # # (a (mod m)) } } $num->{value} = $value; $num->{sign} = $sign; return $num; } sub bpow { # (BINT or num_str, BINT or num_str) return BINT # compute power of two numbers -- stolen from Knuth Vol 2 pg 233 # modifies first argument # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } return $x if $x->modify('bpow'); return $x->bnan() if $x->{sign} eq $nan || $y->{sign} eq $nan; # inf handling if (($x->{sign} =~ /^[+-]inf$/) || ($y->{sign} =~ /^[+-]inf$/)) { if (($x->{sign} =~ /^[+-]inf$/) && ($y->{sign} =~ /^[+-]inf$/)) { # +-inf ** +-inf return $x->bnan(); } # +-inf ** Y if ($x->{sign} =~ /^[+-]inf/) { # +inf ** 0 => NaN return $x->bnan() if $y->is_zero(); # -inf ** -1 => 1/inf => 0 return $x->bzero() if $y->is_one('-') && $x->is_negative(); # +inf ** Y => inf return $x if $x->{sign} eq '+inf'; # -inf ** Y => -inf if Y is odd return $x if $y->is_odd(); return $x->babs(); } # X ** +-inf # 1 ** +inf => 1 return $x if $x->is_one(); # 0 ** inf => 0 return $x if $x->is_zero() && $y->{sign} =~ /^[+]/; # 0 ** -inf => inf return $x->binf() if $x->is_zero(); # -1 ** -inf => NaN return $x->bnan() if $x->is_one('-') && $y->{sign} =~ /^[-]/; # -X ** -inf => 0 return $x->bzero() if $x->{sign} eq '-' && $y->{sign} =~ /^[-]/; # -1 ** inf => NaN return $x->bnan() if $x->{sign} eq '-'; # X ** inf => inf return $x->binf() if $y->{sign} =~ /^[+]/; # X ** -inf => 0 return $x->bzero(); } return $upgrade->bpow($upgrade->new($x), $y, @r) if defined $upgrade && (!$y->isa($class) || $y->{sign} eq '-'); $r[3] = $y; # no push! # cases 0 ** Y, X ** 0, X ** 1, 1 ** Y are handled by Calc or Emu my $new_sign = '+'; $new_sign = $y->is_odd() ? '-' : '+' if ($x->{sign} ne '+'); # 0 ** -7 => ( 1 / (0 ** 7)) => 1 / 0 => +inf return $x->binf() if $y->{sign} eq '-' && $x->{sign} eq '+' && $CALC->_is_zero($x->{value}); # 1 ** -y => 1 / (1 ** |y|) # so do test for negative $y after above's clause return $x->bnan() if $y->{sign} eq '-' && !$CALC->_is_one($x->{value}); $x->{value} = $CALC->_pow($x->{value}, $y->{value}); $x->{sign} = $new_sign; $x->{sign} = '+' if $CALC->_is_zero($y->{value}); $x->round(@r); } sub blog { # Return the logarithm of the operand. If a second operand is defined, that # value is used as the base, otherwise the base is assumed to be Euler's # constant. my ($class, $x, $base, @r); # Don't objectify the base, since an undefined base, as in $x->blog() or # $x->blog(undef) signals that the base is Euler's number. if (!ref($_[0]) && $_[0] =~ /^[A-Za-z]|::/) { # E.g., Math::BigInt->blog(256, 2) ($class, $x, $base, @r) = defined $_[2] ? objectify(2, @_) : objectify(1, @_); } else { # E.g., Math::BigInt::blog(256, 2) or $x->blog(2) ($class, $x, $base, @r) = defined $_[1] ? objectify(2, @_) : objectify(1, @_); } return $x if $x->modify('blog'); # Handle all exception cases and all trivial cases. I have used Wolfram # Alpha (http://www.wolframalpha.com) as the reference for these cases. return $x -> bnan() if $x -> is_nan(); if (defined $base) { $base = $class -> new($base) unless ref $base; if ($base -> is_nan() || $base -> is_one()) { return $x -> bnan(); } elsif ($base -> is_inf() || $base -> is_zero()) { return $x -> bnan() if $x -> is_inf() || $x -> is_zero(); return $x -> bzero(); } elsif ($base -> is_negative()) { # -inf < base < 0 return $x -> bzero() if $x -> is_one(); # x = 1 return $x -> bone() if $x == $base; # x = base return $x -> bnan(); # otherwise } return $x -> bone() if $x == $base; # 0 < base && 0 < x < inf } # We now know that the base is either undefined or >= 2 and finite. return $x -> binf('+') if $x -> is_inf(); # x = +/-inf return $x -> bnan() if $x -> is_neg(); # -inf < x < 0 return $x -> bzero() if $x -> is_one(); # x = 1 return $x -> binf('-') if $x -> is_zero(); # x = 0 # At this point we are done handling all exception cases and trivial cases. return $upgrade -> blog($upgrade -> new($x), $base, @r) if defined $upgrade; # fix for bug #24969: # the default base is e (Euler's number) which is not an integer if (!defined $base) { require Math::BigFloat; my $u = Math::BigFloat->blog(Math::BigFloat->new($x))->as_int(); # modify $x in place $x->{value} = $u->{value}; $x->{sign} = $u->{sign}; return $x; } my ($rc, $exact) = $CALC->_log_int($x->{value}, $base->{value}); return $x->bnan() unless defined $rc; # not possible to take log? $x->{value} = $rc; $x->round(@r); } sub bexp { # Calculate e ** $x (Euler's number to the power of X), truncated to # an integer value. my ($class, $x, @r) = ref($_[0]) ? (ref($_[0]), @_) : objectify(1, @_); return $x if $x->modify('bexp'); # inf, -inf, NaN, <0 => NaN return $x->bnan() if $x->{sign} eq 'NaN'; return $x->bone() if $x->is_zero(); return $x if $x->{sign} eq '+inf'; return $x->bzero() if $x->{sign} eq '-inf'; my $u; { # run through Math::BigFloat unless told otherwise require Math::BigFloat unless defined $upgrade; local $upgrade = 'Math::BigFloat' unless defined $upgrade; # calculate result, truncate it to integer $u = $upgrade->bexp($upgrade->new($x), @r); } if (defined $upgrade) { $x = $u; } else { $u = $u->as_int(); # modify $x in place $x->{value} = $u->{value}; $x->round(@r); } } sub bnok { # Calculate n over k (binomial coefficient or "choose" function) as integer. # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } return $x if $x->modify('bnok'); return $x->bnan() if $x->{sign} eq 'NaN' || $y->{sign} eq 'NaN'; return $x->binf() if $x->{sign} eq '+inf'; # k > n or k < 0 => 0 my $cmp = $x->bacmp($y); return $x->bzero() if $cmp < 0 || substr($y->{sign}, 0, 1) eq "-"; if ($CALC->can('_nok')) { $x->{value} = $CALC->_nok($x->{value}, $y->{value}); } else { # ( 7 ) 7! 1*2*3*4 * 5*6*7 5 * 6 * 7 6 7 # ( - ) = --------- = --------------- = --------- = 5 * - * - # ( 3 ) (7-3)! 3! 1*2*3*4 * 1*2*3 1 * 2 * 3 2 3 my $n = $x -> {value}; my $k = $y -> {value}; # If k > n/2, or, equivalently, 2*k > n, compute nok(n, k) as # nok(n, n-k) to minimize the number if iterations in the loop. { my $twok = $CALC->_mul($CALC->_two(), $CALC->_copy($k)); if ($CALC->_acmp($twok, $n) > 0) { $k = $CALC->_sub($CALC->_copy($n), $k); } } if ($CALC->_is_zero($k)) { $n = $CALC->_one(); } else { # Make a copy of the original n, since we'll be modifying n # in-place. my $n_orig = $CALC->_copy($n); $CALC->_sub($n, $k); $CALC->_inc($n); my $f = $CALC->_copy($n); $CALC->_inc($f); my $d = $CALC->_two(); # while f <= n (the original n, that is) ... while ($CALC->_acmp($f, $n_orig) <= 0) { $CALC->_mul($n, $f); $CALC->_div($n, $d); $CALC->_inc($f); $CALC->_inc($d); } } $x -> {value} = $n; } $x->round(@r); } sub bsin { # Calculate sinus(x) to N digits. Unless upgrading is in effect, returns the # result truncated to an integer. my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_); return $x if $x->modify('bsin'); return $x->bnan() if $x->{sign} !~ /^[+-]\z/; # -inf +inf or NaN => NaN return $upgrade->new($x)->bsin(@r) if defined $upgrade; require Math::BigFloat; # calculate the result and truncate it to integer my $t = Math::BigFloat->new($x)->bsin(@r)->as_int(); $x->bone() if $t->is_one(); $x->bzero() if $t->is_zero(); $x->round(@r); } sub bcos { # Calculate cosinus(x) to N digits. Unless upgrading is in effect, returns the # result truncated to an integer. my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_); return $x if $x->modify('bcos'); return $x->bnan() if $x->{sign} !~ /^[+-]\z/; # -inf +inf or NaN => NaN return $upgrade->new($x)->bcos(@r) if defined $upgrade; require Math::BigFloat; # calculate the result and truncate it to integer my $t = Math::BigFloat->new($x)->bcos(@r)->as_int(); $x->bone() if $t->is_one(); $x->bzero() if $t->is_zero(); $x->round(@r); } sub batan { # Calculate arcus tangens of x to N digits. Unless upgrading is in effect, returns the # result truncated to an integer. my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_); return $x if $x->modify('batan'); return $x->bnan() if $x->{sign} !~ /^[+-]\z/; # -inf +inf or NaN => NaN return $upgrade->new($x)->batan(@r) if defined $upgrade; # calculate the result and truncate it to integer my $t = Math::BigFloat->new($x)->batan(@r); $x->{value} = $CALC->_new($x->as_int()->bstr()); $x->round(@r); } sub batan2 { # calculate arcus tangens of ($y/$x) # set up parameters my ($class, $y, $x, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $y, $x, @r) = objectify(2, @_); } return $y if $y->modify('batan2'); return $y->bnan() if ($y->{sign} eq $nan) || ($x->{sign} eq $nan); # Y X # != 0 -inf result is +- pi if ($x->is_inf() || $y->is_inf()) { # upgrade to Math::BigFloat etc. return $upgrade->new($y)->batan2($upgrade->new($x), @r) if defined $upgrade; if ($y->is_inf()) { if ($x->{sign} eq '-inf') { # calculate 3 pi/4 => 2.3.. => 2 $y->bone(substr($y->{sign}, 0, 1)); $y->bmul($class->new(2)); } elsif ($x->{sign} eq '+inf') { # calculate pi/4 => 0.7 => 0 $y->bzero(); } else { # calculate pi/2 => 1.5 => 1 $y->bone(substr($y->{sign}, 0, 1)); } } else { if ($x->{sign} eq '+inf') { # calculate pi/4 => 0.7 => 0 $y->bzero(); } else { # PI => 3.1415.. => 3 $y->bone(substr($y->{sign}, 0, 1)); $y->bmul($class->new(3)); } } return $y; } return $upgrade->new($y)->batan2($upgrade->new($x), @r) if defined $upgrade; require Math::BigFloat; my $r = Math::BigFloat->new($y) ->batan2(Math::BigFloat->new($x), @r) ->as_int(); $x->{value} = $r->{value}; $x->{sign} = $r->{sign}; $x; } sub bsqrt { # calculate square root of $x my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_); return $x if $x->modify('bsqrt'); return $x->bnan() if $x->{sign} !~ /^\+/; # -x or -inf or NaN => NaN return $x if $x->{sign} eq '+inf'; # sqrt(+inf) == inf return $upgrade->bsqrt($x, @r) if defined $upgrade; $x->{value} = $CALC->_sqrt($x->{value}); $x->round(@r); } sub broot { # calculate $y'th root of $x # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); $y = $class->new(2) unless defined $y; # objectify is costly, so avoid it if ((!ref($x)) || (ref($x) ne ref($y))) { ($class, $x, $y, @r) = objectify(2, $class || $class, @_); } return $x if $x->modify('broot'); # NaN handling: $x ** 1/0, x or y NaN, or y inf/-inf or y == 0 return $x->bnan() if $x->{sign} !~ /^\+/ || $y->is_zero() || $y->{sign} !~ /^\+$/; return $x->round(@r) if $x->is_zero() || $x->is_one() || $x->is_inf() || $y->is_one(); return $upgrade->new($x)->broot($upgrade->new($y), @r) if defined $upgrade; $x->{value} = $CALC->_root($x->{value}, $y->{value}); $x->round(@r); } sub bfac { # (BINT or num_str, BINT or num_str) return BINT # compute factorial number from $x, modify $x in place my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_); return $x if $x->modify('bfac') || $x->{sign} eq '+inf'; # inf => inf return $x->bnan() if $x->{sign} ne '+'; # NaN, <0 etc => NaN $x->{value} = $CALC->_fac($x->{value}); $x->round(@r); } sub bdfac { # compute double factorial, modify $x in place my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_); return $x if $x->modify('bdfac') || $x->{sign} eq '+inf'; # inf => inf return $x->bnan() if $x->{sign} ne '+'; # NaN, <0 etc => NaN Carp::croak("bdfac() requires a newer version of the $CALC library.") unless $CALC->can('_dfac'); $x->{value} = $CALC->_dfac($x->{value}); $x->round(@r); } sub bfib { # compute Fibonacci number(s) my ($class, $x, @r) = objectify(1, @_); Carp::croak("bfib() requires a newer version of the $CALC library.") unless $CALC->can('_fib'); return $x if $x->modify('bfib'); # List context. if (wantarray) { return () if $x -> is_nan(); Carp::croak("bfib() can't return an infinitely long list of numbers") if $x -> is_inf(); # Use the backend library to compute the first $x Fibonacci numbers. my @values = $CALC->_fib($x->{value}); # Make objects out of them. The last element in the array is the # invocand. for (my $i = 0 ; $i < $#values ; ++ $i) { my $fib = $class -> bzero(); $fib -> {value} = $values[$i]; $values[$i] = $fib; } $x -> {value} = $values[-1]; $values[-1] = $x; # If negative, insert sign as appropriate. if ($x -> is_neg()) { for (my $i = 2 ; $i <= $#values ; $i += 2) { $values[$i]{sign} = '-'; } } @values = map { $_ -> round(@r) } @values; return @values; } # Scalar context. else { return $x if $x->modify('bdfac') || $x -> is_inf('+'); return $x->bnan() if $x -> is_nan() || $x -> is_inf('-'); $x->{sign} = $x -> is_neg() && $x -> is_even() ? '-' : '+'; $x->{value} = $CALC->_fib($x->{value}); return $x->round(@r); } } sub blucas { # compute Lucas number(s) my ($class, $x, @r) = objectify(1, @_); Carp::croak("blucas() requires a newer version of the $CALC library.") unless $CALC->can('_lucas'); return $x if $x->modify('blucas'); # List context. if (wantarray) { return () if $x -> is_nan(); Carp::croak("blucas() can't return an infinitely long list of numbers") if $x -> is_inf(); # Use the backend library to compute the first $x Lucas numbers. my @values = $CALC->_lucas($x->{value}); # Make objects out of them. The last element in the array is the # invocand. for (my $i = 0 ; $i < $#values ; ++ $i) { my $lucas = $class -> bzero(); $lucas -> {value} = $values[$i]; $values[$i] = $lucas; } $x -> {value} = $values[-1]; $values[-1] = $x; # If negative, insert sign as appropriate. if ($x -> is_neg()) { for (my $i = 2 ; $i <= $#values ; $i += 2) { $values[$i]{sign} = '-'; } } @values = map { $_ -> round(@r) } @values; return @values; } # Scalar context. else { return $x if $x -> is_inf('+'); return $x->bnan() if $x -> is_nan() || $x -> is_inf('-'); $x->{sign} = $x -> is_neg() && $x -> is_even() ? '-' : '+'; $x->{value} = $CALC->_lucas($x->{value}); return $x->round(@r); } } sub blsft { # (BINT or num_str, BINT or num_str) return BINT # compute x << y, base n, y >= 0 # set up parameters my ($class, $x, $y, $b, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, $b, @r) = objectify(2, @_); } return $x if $x -> modify('blsft'); return $x -> bnan() if ($x -> {sign} !~ /^[+-]$/ || $y -> {sign} !~ /^[+-]$/); return $x -> round(@r) if $y -> is_zero(); $b = 2 if !defined $b; return $x -> bnan() if $b <= 0 || $y -> {sign} eq '-'; $x -> {value} = $CALC -> _lsft($x -> {value}, $y -> {value}, $b); $x -> round(@r); } sub brsft { # (BINT or num_str, BINT or num_str) return BINT # compute x >> y, base n, y >= 0 # set up parameters my ($class, $x, $y, $b, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, $b, @r) = objectify(2, @_); } return $x if $x -> modify('brsft'); return $x -> bnan() if ($x -> {sign} !~ /^[+-]$/ || $y -> {sign} !~ /^[+-]$/); return $x -> round(@r) if $y -> is_zero(); return $x -> bzero(@r) if $x -> is_zero(); # 0 => 0 $b = 2 if !defined $b; return $x -> bnan() if $b <= 0 || $y -> {sign} eq '-'; # this only works for negative numbers when shifting in base 2 if (($x -> {sign} eq '-') && ($b == 2)) { return $x -> round(@r) if $x -> is_one('-'); # -1 => -1 if (!$y -> is_one()) { # although this is O(N*N) in calc (as_bin!) it is O(N) in Pari et # al but perhaps there is a better emulation for two's complement # shift... # if $y != 1, we must simulate it by doing: # convert to bin, flip all bits, shift, and be done $x -> binc(); # -3 => -2 my $bin = $x -> as_bin(); $bin =~ s/^-0b//; # strip '-0b' prefix $bin =~ tr/10/01/; # flip bits # now shift if ($y >= CORE::length($bin)) { $bin = '0'; # shifting to far right creates -1 # 0, because later increment makes # that 1, attached '-' makes it '-1' # because -1 >> x == -1 ! } else { $bin =~ s/.{$y}$//; # cut off at the right side $bin = '1' . $bin; # extend left side by one dummy '1' $bin =~ tr/10/01/; # flip bits back } my $res = $class -> new('0b' . $bin); # add prefix and convert back $res -> binc(); # remember to increment $x -> {value} = $res -> {value}; # take over value return $x -> round(@r); # we are done now, magic, isn't? } # x < 0, n == 2, y == 1 $x -> bdec(); # n == 2, but $y == 1: this fixes it } $x -> {value} = $CALC -> _rsft($x -> {value}, $y -> {value}, $b); $x -> round(@r); } ############################################################################### # Bitwise methods ############################################################################### sub band { #(BINT or num_str, BINT or num_str) return BINT # compute x & y # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } return $x if $x->modify('band'); $r[3] = $y; # no push! return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/); my $sx = $x->{sign} eq '+' ? 1 : -1; my $sy = $y->{sign} eq '+' ? 1 : -1; if ($sx == 1 && $sy == 1) { $x->{value} = $CALC->_and($x->{value}, $y->{value}); return $x->round(@r); } if ($CAN{signed_and}) { $x->{value} = $CALC->_signed_and($x->{value}, $y->{value}, $sx, $sy); return $x->round(@r); } require $EMU_LIB; __emu_band($class, $x, $y, $sx, $sy, @r); } sub bior { #(BINT or num_str, BINT or num_str) return BINT # compute x | y # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } return $x if $x->modify('bior'); $r[3] = $y; # no push! return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/); my $sx = $x->{sign} eq '+' ? 1 : -1; my $sy = $y->{sign} eq '+' ? 1 : -1; # the sign of X follows the sign of X, e.g. sign of Y irrelevant for bior() # don't use lib for negative values if ($sx == 1 && $sy == 1) { $x->{value} = $CALC->_or($x->{value}, $y->{value}); return $x->round(@r); } # if lib can do negative values, let it handle this if ($CAN{signed_or}) { $x->{value} = $CALC->_signed_or($x->{value}, $y->{value}, $sx, $sy); return $x->round(@r); } require $EMU_LIB; __emu_bior($class, $x, $y, $sx, $sy, @r); } sub bxor { #(BINT or num_str, BINT or num_str) return BINT # compute x ^ y # set up parameters my ($class, $x, $y, @r) = (ref($_[0]), @_); # objectify is costly, so avoid it if ((!ref($_[0])) || (ref($_[0]) ne ref($_[1]))) { ($class, $x, $y, @r) = objectify(2, @_); } return $x if $x->modify('bxor'); $r[3] = $y; # no push! return $x->bnan() if ($x->{sign} !~ /^[+-]$/ || $y->{sign} !~ /^[+-]$/); my $sx = $x->{sign} eq '+' ? 1 : -1; my $sy = $y->{sign} eq '+' ? 1 : -1; # don't use lib for negative values if ($sx == 1 && $sy == 1) { $x->{value} = $CALC->_xor($x->{value}, $y->{value}); return $x->round(@r); } # if lib can do negative values, let it handle this if ($CAN{signed_xor}) { $x->{value} = $CALC->_signed_xor($x->{value}, $y->{value}, $sx, $sy); return $x->round(@r); } require $EMU_LIB; __emu_bxor($class, $x, $y, $sx, $sy, @r); } sub bnot { # (num_str or BINT) return BINT # represent ~x as twos-complement number # we don't need $class, so undef instead of ref($_[0]) make it slightly faster my ($class, $x, $a, $p, $r) = ref($_[0]) ? (undef, @_) : objectify(1, @_); return $x if $x->modify('bnot'); $x->binc()->bneg(); # binc already does round } ############################################################################### # Rounding methods ############################################################################### sub round { # Round $self according to given parameters, or given second argument's # parameters or global defaults # for speed reasons, _find_round_parameters is embedded here: my ($self, $a, $p, $r, @args) = @_; # $a accuracy, if given by caller # $p precision, if given by caller # $r round_mode, if given by caller # @args all 'other' arguments (0 for unary, 1 for binary ops) my $class = ref($self); # find out class of argument(s) no strict 'refs'; # now pick $a or $p, but only if we have got "arguments" if (!defined $a) { foreach ($self, @args) { # take the defined one, or if both defined, the one that is smaller $a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a); } } if (!defined $p) { # even if $a is defined, take $p, to signal error for both defined foreach ($self, @args) { # take the defined one, or if both defined, the one that is bigger # -2 > -3, and 3 > 2 $p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p); } } # if still none defined, use globals (#2) $a = ${"$class\::accuracy"} unless defined $a; $p = ${"$class\::precision"} unless defined $p; # A == 0 is useless, so undef it to signal no rounding $a = undef if defined $a && $a == 0; # no rounding today? return $self unless defined $a || defined $p; # early out # set A and set P is an fatal error return $self->bnan() if defined $a && defined $p; $r = ${"$class\::round_mode"} unless defined $r; if ($r !~ /^(even|odd|[+-]inf|zero|trunc|common)$/) { Carp::croak("Unknown round mode '$r'"); } # now round, by calling either bround or bfround: if (defined $a) { $self->bround(int($a), $r) if !defined $self->{_a} || $self->{_a} >= $a; } else { # both can't be undefined due to early out $self->bfround(int($p), $r) if !defined $self->{_p} || $self->{_p} <= $p; } # bround() or bfround() already called bnorm() if nec. $self; } sub bround { # accuracy: +$n preserve $n digits from left, # -$n preserve $n digits from right (f.i. for 0.1234 style in MBF) # no-op for $n == 0 # and overwrite the rest with 0's, return normalized number # do not return $x->bnorm(), but $x my $x = shift; $x = $class->new($x) unless ref $x; my ($scale, $mode) = $x->_scale_a(@_); return $x if !defined $scale || $x->modify('bround'); # no-op if ($x->is_zero() || $scale == 0) { $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2 return $x; } return $x if $x->{sign} !~ /^[+-]$/; # inf, NaN # we have fewer digits than we want to scale to my $len = $x->length(); # convert $scale to a scalar in case it is an object (put's a limit on the # number length, but this would already limited by memory constraints), makes # it faster $scale = $scale->numify() if ref ($scale); # scale < 0, but > -len (not >=!) if (($scale < 0 && $scale < -$len-1) || ($scale >= $len)) { $x->{_a} = $scale if !defined $x->{_a} || $x->{_a} > $scale; # 3 > 2 return $x; } # count of 0's to pad, from left (+) or right (-): 9 - +6 => 3, or |-6| => 6 my ($pad, $digit_round, $digit_after); $pad = $len - $scale; $pad = abs($scale-1) if $scale < 0; # do not use digit(), it is very costly for binary => decimal # getting the entire string is also costly, but we need to do it only once my $xs = $CALC->_str($x->{value}); my $pl = -$pad-1; # pad: 123: 0 => -1, at 1 => -2, at 2 => -3, at 3 => -4 # pad+1: 123: 0 => 0, at 1 => -1, at 2 => -2, at 3 => -3 $digit_round = '0'; $digit_round = substr($xs, $pl, 1) if $pad <= $len; $pl++; $pl ++ if $pad >= $len; $digit_after = '0'; $digit_after = substr($xs, $pl, 1) if $pad > 0; # in case of 01234 we round down, for 6789 up, and only in case 5 we look # closer at the remaining digits of the original $x, remember decision my $round_up = 1; # default round up $round_up -- if ($mode eq 'trunc') || # trunc by round down ($digit_after =~ /[01234]/) || # round down anyway, # 6789 => round up ($digit_after eq '5') && # not 5000...0000 ($x->_scan_for_nonzero($pad, $xs, $len) == 0) && ( ($mode eq 'even') && ($digit_round =~ /[24680]/) || ($mode eq 'odd') && ($digit_round =~ /[13579]/) || ($mode eq '+inf') && ($x->{sign} eq '-') || ($mode eq '-inf') && ($x->{sign} eq '+') || ($mode eq 'zero') # round down if zero, sign adjusted below ); my $put_back = 0; # not yet modified if (($pad > 0) && ($pad <= $len)) { substr($xs, -$pad, $pad) = '0' x $pad; # replace with '00...' $put_back = 1; # need to put back } elsif ($pad > $len) { $x->bzero(); # round to '0' } if ($round_up) { # what gave test above? $put_back = 1; # need to put back $pad = $len, $xs = '0' x $pad if $scale < 0; # tlr: whack 0.51=>1.0 # we modify directly the string variant instead of creating a number and # adding it, since that is faster (we already have the string) my $c = 0; $pad ++; # for $pad == $len case while ($pad <= $len) { $c = substr($xs, -$pad, 1) + 1; $c = '0' if $c eq '10'; substr($xs, -$pad, 1) = $c; $pad++; last if $c != 0; # no overflow => early out } $xs = '1'.$xs if $c == 0; } $x->{value} = $CALC->_new($xs) if $put_back == 1; # put back, if needed $x->{_a} = $scale if $scale >= 0; if ($scale < 0) { $x->{_a} = $len+$scale; $x->{_a} = 0 if $scale < -$len; } $x; } sub bfround { # precision: round to the $Nth digit left (+$n) or right (-$n) from the '.' # $n == 0 || $n == 1 => round to integer my $x = shift; my $class = ref($x) || $x; $x = $class->new($x) unless ref $x; my ($scale, $mode) = $x->_scale_p(@_); return $x if !defined $scale || $x->modify('bfround'); # no-op # no-op for Math::BigInt objects if $n <= 0 $x->bround($x->length()-$scale, $mode) if $scale > 0; delete $x->{_a}; # delete to save memory $x->{_p} = $scale; # store new _p $x; } sub fround { # Exists to make life easier for switch between MBF and MBI (should we # autoload fxxx() like MBF does for bxxx()?) my $x = shift; $x = $class->new($x) unless ref $x; $x->bround(@_); } sub bfloor { # round towards minus infinity; no-op since it's already integer my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_); $x->round(@r); } sub bceil { # round towards plus infinity; no-op since it's already int my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_); $x->round(@r); } sub bint { # round towards zero; no-op since it's already integer my ($class, $x, @r) = ref($_[0]) ? (undef, @_) : objectify(1, @_); $x->round(@r); } ############################################################################### # Other mathematical methods ############################################################################### sub bgcd { # (BINT or num_str, BINT or num_str) return BINT # does not modify arguments, but returns new object # GCD -- Euclid's algorithm, variant C (Knuth Vol 3, pg 341 ff) my ($class, @args) = objectify(0, @_); my $x = shift @args; $x = ref($x) && $x -> isa($class) ? $x -> copy() : $class -> new($x); return $class->bnan() if $x->{sign} !~ /^[+-]$/; # x NaN? while (@args) { my $y = shift @args; $y = $class->new($y) unless ref($y) && $y -> isa($class); return $class->bnan() if $y->{sign} !~ /^[+-]$/; # y NaN? $x->{value} = $CALC->_gcd($x->{value}, $y->{value}); last if $CALC->_is_one($x->{value}); } return $x -> babs(); } sub blcm { # (BINT or num_str, BINT or num_str) return BINT # does not modify arguments, but returns new object # Least Common Multiple my ($class, @args) = objectify(0, @_); my $x = shift @args; $x = ref($x) && $x -> isa($class) ? $x -> copy() : $class -> new($x); return $class->bnan() if $x->{sign} !~ /^[+-]$/; # x NaN? while (@args) { my $y = shift @args; $y = $class -> new($y) unless ref($y) && $y -> isa($class); return $x->bnan() if $y->{sign} !~ /^[+-]$/; # y not integer $x -> {value} = $CALC->_lcm($x -> {value}, $y -> {value}); } return $x -> babs(); } ############################################################################### # Object property methods ############################################################################### sub sign { # return the sign of the number: +/-/-inf/+inf/NaN my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); $x->{sign}; } sub digit { # return the nth decimal digit, negative values count backward, 0 is right my ($class, $x, $n) = ref($_[0]) ? (undef, @_) : objectify(1, @_); $n = $n->numify() if ref($n); $CALC->_digit($x->{value}, $n || 0); } sub length { my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); my $e = $CALC->_len($x->{value}); wantarray ? ($e, 0) : $e; } sub exponent { # return a copy of the exponent (here always 0, NaN or 1 for $m == 0) my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_); if ($x->{sign} !~ /^[+-]$/) { my $s = $x->{sign}; $s =~ s/^[+-]//; # NaN, -inf, +inf => NaN or inf return $class->new($s); } return $class->bzero() if $x->is_zero(); # 12300 => 2 trailing zeros => exponent is 2 $class->new($CALC->_zeros($x->{value})); } sub mantissa { # return the mantissa (compatible to Math::BigFloat, e.g. reduced) my ($class, $x) = ref($_[0]) ? (ref($_[0]), $_[0]) : objectify(1, @_); if ($x->{sign} !~ /^[+-]$/) { # for NaN, +inf, -inf: keep the sign return $class->new($x->{sign}); } my $m = $x->copy(); delete $m->{_p}; delete $m->{_a}; # that's a bit inefficient: my $zeros = $CALC->_zeros($m->{value}); $m->brsft($zeros, 10) if $zeros != 0; $m; } sub parts { # return a copy of both the exponent and the mantissa my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); ($x->mantissa(), $x->exponent()); } sub sparts { my $self = shift; my $class = ref $self; Carp::croak("sparts() is an instance method, not a class method") unless $class; # Not-a-number. if ($self -> is_nan()) { my $mant = $self -> copy(); # mantissa return $mant unless wantarray; # scalar context my $expo = $class -> bnan(); # exponent return ($mant, $expo); # list context } # Infinity. if ($self -> is_inf()) { my $mant = $self -> copy(); # mantissa return $mant unless wantarray; # scalar context my $expo = $class -> binf('+'); # exponent return ($mant, $expo); # list context } # Finite number. my $mant = $self -> copy(); my $nzeros = $CALC -> _zeros($mant -> {value}); $mant -> brsft($nzeros, 10) if $nzeros != 0; return $mant unless wantarray; my $expo = $class -> new($nzeros); return ($mant, $expo); } sub nparts { my $self = shift; my $class = ref $self; Carp::croak("nparts() is an instance method, not a class method") unless $class; # Not-a-number. if ($self -> is_nan()) { my $mant = $self -> copy(); # mantissa return $mant unless wantarray; # scalar context my $expo = $class -> bnan(); # exponent return ($mant, $expo); # list context } # Infinity. if ($self -> is_inf()) { my $mant = $self -> copy(); # mantissa return $mant unless wantarray; # scalar context my $expo = $class -> binf('+'); # exponent return ($mant, $expo); # list context } # Finite number. my ($mant, $expo) = $self -> sparts(); if ($mant -> bcmp(0)) { my ($ndigtot, $ndigfrac) = $mant -> length(); my $expo10adj = $ndigtot - $ndigfrac - 1; if ($expo10adj != 0) { return $upgrade -> new($self) -> nparts() if $upgrade; $mant -> bnan(); return $mant unless wantarray; $expo -> badd($expo10adj); return ($mant, $expo); } } return $mant unless wantarray; return ($mant, $expo); } sub eparts { my $self = shift; my $class = ref $self; Carp::croak("eparts() is an instance method, not a class method") unless $class; # Not-a-number and Infinity. return $self -> sparts() if $self -> is_nan() || $self -> is_inf(); # Finite number. my ($mant, $expo) = $self -> sparts(); if ($mant -> bcmp(0)) { my $ndigmant = $mant -> length(); $expo -> badd($ndigmant); # $c is the number of digits that will be in the integer part of the # final mantissa. my $c = $expo -> copy() -> bdec() -> bmod(3) -> binc(); $expo -> bsub($c); if ($ndigmant > $c) { return $upgrade -> new($self) -> eparts() if $upgrade; $mant -> bnan(); return $mant unless wantarray; return ($mant, $expo); } $mant -> blsft($c - $ndigmant, 10); } return $mant unless wantarray; return ($mant, $expo); } sub dparts { my $self = shift; my $class = ref $self; Carp::croak("dparts() is an instance method, not a class method") unless $class; my $int = $self -> copy(); return $int unless wantarray; my $frc = $class -> bzero(); return ($int, $frc); } ############################################################################### # String conversion methods ############################################################################### sub bstr { my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); if ($x->{sign} ne '+' && $x->{sign} ne '-') { return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN return 'inf'; # +inf } my $str = $CALC->_str($x->{value}); return $x->{sign} eq '-' ? "-$str" : $str; } # Scientific notation with significand/mantissa as an integer, e.g., "12345" is # written as "1.2345e+4". sub bsstr { my ($class, $x) = ref($_[0]) ? (undef, $_[0]) : objectify(1, @_); if ($x->{sign} ne '+' && $x->{sign} ne '-') { return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN return 'inf'; # +inf } my ($m, $e) = $x -> parts(); my $str = $CALC->_str($m->{value}) . 'e+' . $CALC->_str($e->{value}); return $x->{sign} eq '-' ? "-$str" : $str; } # Normalized notation, e.g., "12345" is written as "12345e+0". sub bnstr { my $x = shift; if ($x->{sign} ne '+' && $x->{sign} ne '-') { return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN return 'inf'; # +inf } return $x -> bstr() if $x -> is_nan() || $x -> is_inf(); my ($mant, $expo) = $x -> parts(); # The "fraction posision" is the position (offset) for the decimal point # relative to the end of the digit string. my $fracpos = $mant -> length() - 1; if ($fracpos == 0) { my $str = $CALC->_str($mant->{value}) . "e+" . $CALC->_str($expo->{value}); return $x->{sign} eq '-' ? "-$str" : $str; } $expo += $fracpos; my $mantstr = $CALC->_str($mant -> {value}); substr($mantstr, -$fracpos, 0) = '.'; my $str = $mantstr . 'e+' . $CALC->_str($expo -> {value}); return $x->{sign} eq '-' ? "-$str" : $str; } # Engineering notation, e.g., "12345" is written as "12.345e+3". sub bestr { my $x = shift; if ($x->{sign} ne '+' && $x->{sign} ne '-') { return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN return 'inf'; # +inf } my ($mant, $expo) = $x -> parts(); my $sign = $mant -> sign(); $mant -> babs(); my $mantstr = $CALC->_str($mant -> {value}); my $mantlen = CORE::length($mantstr); my $dotidx = 1; $expo += $mantlen - 1; my $c = $expo -> copy() -> bmod(3); $expo -= $c; $dotidx += $c; if ($mantlen < $dotidx) { $mantstr .= "0" x ($dotidx - $mantlen); } elsif ($mantlen > $dotidx) { substr($mantstr, $dotidx, 0) = "."; } my $str = $mantstr . 'e+' . $CALC->_str($expo -> {value}); return $sign eq "-" ? "-$str" : $str; } # Decimal notation, e.g., "12345". sub bdstr { my $x = shift; if ($x->{sign} ne '+' && $x->{sign} ne '-') { return $x->{sign} unless $x->{sign} eq '+inf'; # -inf, NaN return 'inf'; # +inf } my $str = $CALC->_str($x->{value}); return $x->{sign} eq '-' ? "-$str" : $str; } sub to_hex { # return as hex string, with prefixed 0x my $x = shift; $x = $class->new($x) if !ref($x); return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc my $hex = $CALC->_to_hex($x->{value}); return $x->{sign} eq '-' ? "-$hex" : $hex; } sub to_oct { # return as octal string, with prefixed 0 my $x = shift; $x = $class->new($x) if !ref($x); return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc my $oct = $CALC->_to_oct($x->{value}); return $x->{sign} eq '-' ? "-$oct" : $oct; } sub to_bin { # return as binary string, with prefixed 0b my $x = shift; $x = $class->new($x) if !ref($x); return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc my $bin = $CALC->_to_bin($x->{value}); return $x->{sign} eq '-' ? "-$bin" : $bin; } sub to_bytes { # return a byte string my $x = shift; $x = $class->new($x) if !ref($x); Carp::croak("to_bytes() requires a finite, non-negative integer") if $x -> is_neg() || ! $x -> is_int(); Carp::croak("to_bytes() requires a newer version of the $CALC library.") unless $CALC->can('_to_bytes'); return $CALC->_to_bytes($x->{value}); } sub as_hex { # return as hex string, with prefixed 0x my $x = shift; $x = $class->new($x) if !ref($x); return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc my $hex = $CALC->_as_hex($x->{value}); return $x->{sign} eq '-' ? "-$hex" : $hex; } sub as_oct { # return as octal string, with prefixed 0 my $x = shift; $x = $class->new($x) if !ref($x); return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc my $oct = $CALC->_as_oct($x->{value}); return $x->{sign} eq '-' ? "-$oct" : $oct; } sub as_bin { # return as binary string, with prefixed 0b my $x = shift; $x = $class->new($x) if !ref($x); return $x->bstr() if $x->{sign} !~ /^[+-]$/; # inf, nan etc my $bin = $CALC->_as_bin($x->{value}); return $x->{sign} eq '-' ? "-$bin" : $bin; } *as_bytes = \&to_bytes; ############################################################################### # Other conversion methods ############################################################################### sub numify { # Make a Perl scalar number from a Math::BigInt object. my $x = shift; $x = $class->new($x) unless ref $x; if ($x -> is_nan()) { require Math::Complex; my $inf = Math::Complex::Inf(); return $inf - $inf; } if ($x -> is_inf()) { require Math::Complex; my $inf = Math::Complex::Inf(); return $x -> is_negative() ? -$inf : $inf; } my $num = 0 + $CALC->_num($x->{value}); return $x->{sign} eq '-' ? -$num : $num; } ############################################################################### # Private methods and functions. ############################################################################### sub objectify { # Convert strings and "foreign objects" to the objects we want. # The first argument, $count, is the number of following arguments that # objectify() looks at and converts to objects. The first is a classname. # If the given count is 0, all arguments will be used. # After the count is read, objectify obtains the name of the class to which # the following arguments are converted. If the second argument is a # reference, use the reference type as the class name. Otherwise, if it is # a string that looks like a class name, use that. Otherwise, use $class. # Caller: Gives us: # # $x->badd(1); => ref x, scalar y # Class->badd(1, 2); => classname x (scalar), scalar x, scalar y # Class->badd(Class->(1), 2); => classname x (scalar), ref x, scalar y # Math::BigInt::badd(1, 2); => scalar x, scalar y # A shortcut for the common case $x->unary_op(), in which case the argument # list is (0, $x) or (1, $x). return (ref($_[1]), $_[1]) if @_ == 2 && ($_[0] || 0) == 1 && ref($_[1]); # Check the context. unless (wantarray) { Carp::croak("${class}::objectify() needs list context"); } # Get the number of arguments to objectify. my $count = shift; # Initialize the output array. my @a = @_; # If the first argument is a reference, use that reference type as our # class name. Otherwise, if the first argument looks like a class name, # then use that as our class name. Otherwise, use the default class name. my $class; if (ref($a[0])) { # reference? $class = ref($a[0]); } elsif ($a[0] =~ /^[A-Z].*::/) { # string with class name? $class = shift @a; } else { $class = __PACKAGE__; # default class name } $count ||= @a; unshift @a, $class; no strict 'refs'; # What we upgrade to, if anything. my $up = ${"$a[0]::upgrade"}; # Disable downgrading, because Math::BigFloat -> foo('1.0', '2.0') needs # floats. my $down; if (defined ${"$a[0]::downgrade"}) { $down = ${"$a[0]::downgrade"}; ${"$a[0]::downgrade"} = undef; } for my $i (1 .. $count) { my $ref = ref $a[$i]; # Perl scalars are fed to the appropriate constructor. unless ($ref) { $a[$i] = $a[0] -> new($a[$i]); next; } # If it is an object of the right class, all is fine. next if $ref -> isa($a[0]); # Upgrading is OK, so skip further tests if the argument is upgraded. if (defined $up && $ref -> isa($up)) { next; } # See if we can call one of the as_xxx() methods. We don't know whether # the as_xxx() method returns an object or a scalar, so re-check # afterwards. my $recheck = 0; if ($a[0] -> isa('Math::BigInt')) { if ($a[$i] -> can('as_int')) { $a[$i] = $a[$i] -> as_int(); $recheck = 1; } elsif ($a[$i] -> can('as_number')) { $a[$i] = $a[$i] -> as_number(); $recheck = 1; } } elsif ($a[0] -> isa('Math::BigFloat')) { if ($a[$i] -> can('as_float')) { $a[$i] = $a[$i] -> as_float(); $recheck = $1; } } # If we called one of the as_xxx() methods, recheck. if ($recheck) { $ref = ref($a[$i]); # Perl scalars are fed to the appropriate constructor. unless ($ref) { $a[$i] = $a[0] -> new($a[$i]); next; } # If it is an object of the right class, all is fine. next if $ref -> isa($a[0]); } # Last resort. $a[$i] = $a[0] -> new($a[$i]); } # Reset the downgrading. ${"$a[0]::downgrade"} = $down; return @a; } sub import { my $class = shift; $IMPORT++; # remember we did import() my @a; my $l = scalar @_; my $warn_or_die = 0; # 0 - no warn, 1 - warn, 2 - die for (my $i = 0; $i < $l ; $i++) { if ($_[$i] eq ':constant') { # this causes overlord er load to step in overload::constant integer => sub { $class->new(shift) }, binary => sub { $class->new(shift) }; } elsif ($_[$i] eq 'upgrade') { # this causes upgrading $upgrade = $_[$i+1]; # or undef to disable $i++; } elsif ($_[$i] =~ /^(lib|try|only)\z/) { # this causes a different low lib to take care... $CALC = $_[$i+1] || ''; # lib => 1 (warn on fallback), try => 0 (no warn), only => 2 (die on fallback) $warn_or_die = 1 if $_[$i] eq 'lib'; $warn_or_die = 2 if $_[$i] eq 'only'; $i++; } else { push @a, $_[$i]; } } # any non :constant stuff is handled by our parent, Exporter if (@a > 0) { require Exporter; $class->SUPER::import(@a); # need it for subclasses $class->export_to_level(1, $class, @a); # need it for MBF } # try to load core math lib my @c = split /\s*,\s*/, $CALC; foreach (@c) { $_ =~ tr/a-zA-Z0-9://cd; # limit to sane characters } push @c, \'Calc' # if all fail, try these if $warn_or_die < 2; # but not for "only" $CALC = ''; # signal error foreach my $l (@c) { # fallback libraries are "marked" as \'string', extract string if nec. my $lib = $l; $lib = $$l if ref($l); next if ($lib || '') eq ''; $lib = 'Math::BigInt::'.$lib if $lib !~ /^Math::BigInt/i; $lib =~ s/\.pm$//; if ($] < 5.006) { # Perl < 5.6.0 dies with "out of memory!" when eval("") and ':constant' is # used in the same script, or eval("") inside import(). my @parts = split /::/, $lib; # Math::BigInt => Math BigInt my $file = pop @parts; $file .= '.pm'; # BigInt => BigInt.pm require File::Spec; $file = File::Spec->catfile (@parts, $file); eval { require "$file"; $lib->import(@c); } } else { eval "use $lib qw/@c/;"; } if ($@ eq '') { my $ok = 1; # loaded it ok, see if the api_version() is high enough if ($lib->can('api_version') && $lib->api_version() >= 1.0) { $ok = 0; # api_version matches, check if it really provides anything we need for my $method (qw/ one two ten str num add mul div sub dec inc acmp len digit is_one is_zero is_even is_odd is_two is_ten zeros new copy check from_hex from_oct from_bin as_hex as_bin as_oct rsft lsft xor and or mod sqrt root fac pow modinv modpow log_int gcd /) { if (!$lib->can("_$method")) { if (($WARN{$lib} || 0) < 2) { Carp::carp("$lib is missing method '_$method'"); $WARN{$lib} = 1; # still warn about the lib } $ok++; last; } } } if ($ok == 0) { $CALC = $lib; if ($warn_or_die > 0 && ref($l)) { my $msg = "Math::BigInt: couldn't load specified" . " math lib(s), fallback to $lib"; Carp::carp($msg) if $warn_or_die == 1; Carp::croak($msg) if $warn_or_die == 2; } last; # found a usable one, break } else { if (($WARN{$lib} || 0) < 2) { my $ver = eval "\$$lib\::VERSION" || 'unknown'; Carp::carp("Cannot load outdated $lib v$ver, please upgrade"); $WARN{$lib} = 2; # never warn again } } } } if ($CALC eq '') { if ($warn_or_die == 2) { Carp::croak("Couldn't load specified math lib(s)" . " and fallback disallowed"); } else { Carp::croak("Couldn't load any math lib(s), not even fallback to Calc.pm"); } } # notify callbacks foreach my $class (keys %CALLBACKS) { &{$CALLBACKS{$class}}($CALC); } # Fill $CAN with the results of $CALC->can(...) for emulating lower math lib # functions %CAN = (); for my $method (qw/ signed_and signed_or signed_xor /) { $CAN{$method} = $CALC->can("_$method") ? 1 : 0; } # import done } sub _register_callback { my ($class, $callback) = @_; if (ref($callback) ne 'CODE') { Carp::croak("$callback is not a coderef"); } $CALLBACKS{$class} = $callback; } sub _split_dec_string { my $str = shift; if ($str =~ s/ ^ # leading whitespace ( \s* ) # optional sign ( [+-]? ) # significand ( \d+ (?: _ \d+ )* (?: \. (?: \d+ (?: _ \d+ )* )? )? | \. \d+ (?: _ \d+ )* ) # optional exponent (?: [Ee] ( [+-]? ) ( \d+ (?: _ \d+ )* ) )? # trailing stuff ( \D .*? )? \z //x) { my $leading = $1; my $significand_sgn = $2 || '+'; my $significand_abs = $3; my $exponent_sgn = $4 || '+'; my $exponent_abs = $5 || '0'; my $trailing = $6; # Remove underscores and leading zeros. $significand_abs =~ tr/_//d; $exponent_abs =~ tr/_//d; $significand_abs =~ s/^0+(.)/$1/; $exponent_abs =~ s/^0+(.)/$1/; # If the significand contains a dot, remove it and adjust the exponent # accordingly. E.g., "1234.56789e+3" -> "123456789e-2" my $idx = index $significand_abs, '.'; if ($idx > -1) { $significand_abs =~ s/0+\z//; substr($significand_abs, $idx, 1) = ''; my $exponent = $exponent_sgn . $exponent_abs; $exponent .= $idx - CORE::length($significand_abs); $exponent_abs = abs $exponent; $exponent_sgn = $exponent < 0 ? '-' : '+'; } return($leading, $significand_sgn, $significand_abs, $exponent_sgn, $exponent_abs, $trailing); } return undef; } sub _split { # input: num_str; output: undef for invalid or # (\$mantissa_sign, \$mantissa_value, \$mantissa_fraction, # \$exp_sign, \$exp_value) # Internal, take apart a string and return the pieces. # Strip leading/trailing whitespace, leading zeros, underscore and reject # invalid input. my $x = shift; # strip white space at front, also extraneous leading zeros $x =~ s/^\s*([-]?)0*([0-9])/$1$2/g; # will not strip ' .2' $x =~ s/^\s+//; # but this will $x =~ s/\s+$//g; # strip white space at end # shortcut, if nothing to split, return early if ($x =~ /^[+-]?[0-9]+\z/) { $x =~ s/^([+-])0*([0-9])/$2/; my $sign = $1 || '+'; return (\$sign, \$x, \'', \'', \0); } # invalid starting char? return if $x !~ /^[+-]?(\.?[0-9]|0b[0-1]|0x[0-9a-fA-F])/; return Math::BigInt->from_hex($x) if $x =~ /^[+-]?0x/; # hex string return Math::BigInt->from_bin($x) if $x =~ /^[+-]?0b/; # binary string # strip underscores between digits $x =~ s/([0-9])_([0-9])/$1$2/g; $x =~ s/([0-9])_([0-9])/$1$2/g; # do twice for 1_2_3 # some possible inputs: # 2.1234 # 0.12 # 1 # 1E1 # 2.134E1 # 434E-10 # 1.02009E-2 # .2 # 1_2_3.4_5_6 # 1.4E1_2_3 # 1e3 # +.2 # 0e999 my ($m, $e, $last) = split /[Ee]/, $x; return if defined $last; # last defined => 1e2E3 or others $e = '0' if !defined $e || $e eq ""; # sign, value for exponent, mantint, mantfrac my ($es, $ev, $mis, $miv, $mfv); # valid exponent? if ($e =~ /^([+-]?)0*([0-9]+)$/) # strip leading zeros { $es = $1; $ev = $2; # valid mantissa? return if $m eq '.' || $m eq ''; my ($mi, $mf, $lastf) = split /\./, $m; return if defined $lastf; # lastf defined => 1.2.3 or others $mi = '0' if !defined $mi; $mi .= '0' if $mi =~ /^[\-\+]?$/; $mf = '0' if !defined $mf || $mf eq ''; if ($mi =~ /^([+-]?)0*([0-9]+)$/) # strip leading zeros { $mis = $1 || '+'; $miv = $2; return unless ($mf =~ /^([0-9]*?)0*$/); # strip trailing zeros $mfv = $1; # handle the 0e999 case here $ev = 0 if $miv eq '0' && $mfv eq ''; return (\$mis, \$miv, \$mfv, \$es, \$ev); } } return; # NaN, not a number } sub _trailing_zeros { # return the amount of trailing zeros in $x (as scalar) my $x = shift; $x = $class->new($x) unless ref $x; return 0 if $x->{sign} !~ /^[+-]$/; # NaN, inf, -inf etc $CALC->_zeros($x->{value}); # must handle odd values, 0 etc } sub _scan_for_nonzero { # internal, used by bround() to scan for non-zeros after a '5' my ($x, $pad, $xs, $len) = @_; return 0 if $len == 1; # "5" is trailed by invisible zeros my $follow = $pad - 1; return 0 if $follow > $len || $follow < 1; # use the string form to check whether only '0's follow or not substr ($xs, -$follow) =~ /[^0]/ ? 1 : 0; } sub _find_round_parameters { # After any operation or when calling round(), the result is rounded by # regarding the A & P from arguments, local parameters, or globals. # !!!!!!! If you change this, remember to change round(), too! !!!!!!!!!! # This procedure finds the round parameters, but it is for speed reasons # duplicated in round. Otherwise, it is tested by the testsuite and used # by bdiv(). # returns ($self) or ($self, $a, $p, $r) - sets $self to NaN of both A and P # were requested/defined (locally or globally or both) my ($self, $a, $p, $r, @args) = @_; # $a accuracy, if given by caller # $p precision, if given by caller # $r round_mode, if given by caller # @args all 'other' arguments (0 for unary, 1 for binary ops) my $class = ref($self); # find out class of argument(s) no strict 'refs'; # convert to normal scalar for speed and correctness in inner parts $a = $a->can('numify') ? $a->numify() : "$a" if defined $a && ref($a); $p = $p->can('numify') ? $p->numify() : "$p" if defined $p && ref($p); # now pick $a or $p, but only if we have got "arguments" if (!defined $a) { foreach ($self, @args) { # take the defined one, or if both defined, the one that is smaller $a = $_->{_a} if (defined $_->{_a}) && (!defined $a || $_->{_a} < $a); } } if (!defined $p) { # even if $a is defined, take $p, to signal error for both defined foreach ($self, @args) { # take the defined one, or if both defined, the one that is bigger # -2 > -3, and 3 > 2 $p = $_->{_p} if (defined $_->{_p}) && (!defined $p || $_->{_p} > $p); } } # if still none defined, use globals (#2) $a = ${"$class\::accuracy"} unless defined $a; $p = ${"$class\::precision"} unless defined $p; # A == 0 is useless, so undef it to signal no rounding $a = undef if defined $a && $a == 0; # no rounding today? return ($self) unless defined $a || defined $p; # early out # set A and set P is an fatal error return ($self->bnan()) if defined $a && defined $p; # error $r = ${"$class\::round_mode"} unless defined $r; if ($r !~ /^(even|odd|[+-]inf|zero|trunc|common)$/) { Carp::croak("Unknown round mode '$r'"); } $a = int($a) if defined $a; $p = int($p) if defined $p; ($self, $a, $p, $r); } ############################################################################### # this method returns 0 if the object can be modified, or 1 if not. # We use a fast constant sub() here, to avoid costly calls. Subclasses # may override it with special code (f.i. Math::BigInt::Constant does so) sub modify () { 0; } 1; __END__ =pod =head1 NAME Math::BigInt - Arbitrary size integer/float math package =head1 SYNOPSIS use Math::BigInt; # or make it faster with huge numbers: install (optional) # Math::BigInt::GMP and always use (it falls back to # pure Perl if the GMP library is not installed): # (See also the L section!) # warns if Math::BigInt::GMP cannot be found use Math::BigInt lib => 'GMP'; # to suppress the warning use this: # use Math::BigInt try => 'GMP'; # dies if GMP cannot be loaded: # use Math::BigInt only => 'GMP'; my $str = '1234567890'; my @values = (64, 74, 18); my $n = 1; my $sign = '-'; # Configuration methods (may be used as class methods and instance methods) Math::BigInt->accuracy(); # get class accuracy Math::BigInt->accuracy($n); # set class accuracy Math::BigInt->precision(); # get class precision Math::BigInt->precision($n); # set class precision Math::BigInt->round_mode(); # get class rounding mode Math::BigInt->round_mode($m); # set global round mode, must be one of # 'even', 'odd', '+inf', '-inf', 'zero', # 'trunc', or 'common' Math::BigInt->config(); # return hash with configuration # Constructor methods (when the class methods below are used as instance # methods, the value is assigned the invocand) $x = Math::BigInt->new($str); # defaults to 0 $x = Math::BigInt->new('0x123'); # from hexadecimal $x = Math::BigInt->new('0b101'); # from binary $x = Math::BigInt->from_hex('cafe'); # from hexadecimal $x = Math::BigInt->from_oct('377'); # from octal $x = Math::BigInt->from_bin('1101'); # from binary $x = Math::BigInt->bzero(); # create a +0 $x = Math::BigInt->bone(); # create a +1 $x = Math::BigInt->bone('-'); # create a -1 $x = Math::BigInt->binf(); # create a +inf $x = Math::BigInt->binf('-'); # create a -inf $x = Math::BigInt->bnan(); # create a Not-A-Number $x = Math::BigInt->bpi(); # returns pi $y = $x->copy(); # make a copy (unlike $y = $x) $y = $x->as_int(); # return as a Math::BigInt # Boolean methods (these don't modify the invocand) $x->is_zero(); # if $x is 0 $x->is_one(); # if $x is +1 $x->is_one("+"); # ditto $x->is_one("-"); # if $x is -1 $x->is_inf(); # if $x is +inf or -inf $x->is_inf("+"); # if $x is +inf $x->is_inf("-"); # if $x is -inf $x->is_nan(); # if $x is NaN $x->is_positive(); # if $x > 0 $x->is_pos(); # ditto $x->is_negative(); # if $x < 0 $x->is_neg(); # ditto $x->is_odd(); # if $x is odd $x->is_even(); # if $x is even $x->is_int(); # if $x is an integer # Comparison methods $x->bcmp($y); # compare numbers (undef, < 0, == 0, > 0) $x->bacmp($y); # compare absolutely (undef, < 0, == 0, > 0) $x->beq($y); # true if and only if $x == $y $x->bne($y); # true if and only if $x != $y $x->blt($y); # true if and only if $x < $y $x->ble($y); # true if and only if $x <= $y $x->bgt($y); # true if and only if $x > $y $x->bge($y); # true if and only if $x >= $y # Arithmetic methods $x->bneg(); # negation $x->babs(); # absolute value $x->bsgn(); # sign function (-1, 0, 1, or NaN) $x->bnorm(); # normalize (no-op) $x->binc(); # increment $x by 1 $x->bdec(); # decrement $x by 1 $x->badd($y); # addition (add $y to $x) $x->bsub($y); # subtraction (subtract $y from $x) $x->bmul($y); # multiplication (multiply $x by $y) $x->bmuladd($y,$z); # $x = $x * $y + $z $x->bdiv($y); # division (floored), set $x to quotient # return (quo,rem) or quo if scalar $x->btdiv($y); # division (truncated), set $x to quotient # return (quo,rem) or quo if scalar $x->bmod($y); # modulus (x % y) $x->btmod($y); # modulus (truncated) $x->bmodinv($mod); # modular multiplicative inverse $x->bmodpow($y,$mod); # modular exponentiation (($x ** $y) % $mod) $x->bpow($y); # power of arguments (x ** y) $x->blog(); # logarithm of $x to base e (Euler's number) $x->blog($base); # logarithm of $x to base $base (e.g., base 2) $x->bexp(); # calculate e ** $x where e is Euler's number $x->bnok($y); # x over y (binomial coefficient n over k) $x->bsin(); # sine $x->bcos(); # cosine $x->batan(); # inverse tangent $x->batan2($y); # two-argument inverse tangent $x->bsqrt(); # calculate square-root $x->broot($y); # $y'th root of $x (e.g. $y == 3 => cubic root) $x->bfac(); # factorial of $x (1*2*3*4*..$x) $x->blsft($n); # left shift $n places in base 2 $x->blsft($n,$b); # left shift $n places in base $b # returns (quo,rem) or quo (scalar context) $x->brsft($n); # right shift $n places in base 2 $x->brsft($n,$b); # right shift $n places in base $b # returns (quo,rem) or quo (scalar context) # Bitwise methods $x->band($y); # bitwise and $x->bior($y); # bitwise inclusive or $x->bxor($y); # bitwise exclusive or $x->bnot(); # bitwise not (two's complement) # Rounding methods $x->round($A,$P,$mode); # round to accuracy or precision using # rounding mode $mode $x->bround($n); # accuracy: preserve $n digits $x->bfround($n); # $n > 0: round to $nth digit left of dec. point # $n < 0: round to $nth digit right of dec. point $x->bfloor(); # round towards minus infinity $x->bceil(); # round towards plus infinity $x->bint(); # round towards zero # Other mathematical methods $x->bgcd($y); # greatest common divisor $x->blcm($y); # least common multiple # Object property methods (do not modify the invocand) $x->sign(); # the sign, either +, - or NaN $x->digit($n); # the nth digit, counting from the right $x->digit(-$n); # the nth digit, counting from the left $x->length(); # return number of digits in number ($xl,$f) = $x->length(); # length of number and length of fraction # part, latter is always 0 digits long # for Math::BigInt objects $x->mantissa(); # return (signed) mantissa as a Math::BigInt $x->exponent(); # return exponent as a Math::BigInt $x->parts(); # return (mantissa,exponent) as a Math::BigInt $x->sparts(); # mantissa and exponent (as integers) $x->nparts(); # mantissa and exponent (normalised) $x->eparts(); # mantissa and exponent (engineering notation) $x->dparts(); # integer and fraction part # Conversion methods (do not modify the invocand) $x->bstr(); # decimal notation, possibly zero padded $x->bsstr(); # string in scientific notation with integers $x->bnstr(); # string in normalized notation $x->bestr(); # string in engineering notation $x->bdstr(); # string in decimal notation $x->to_hex(); # as signed hexadecimal string $x->to_bin(); # as signed binary string $x->to_oct(); # as signed octal string $x->to_bytes(); # as byte string $x->as_hex(); # as signed hexadecimal string with prefixed 0x $x->as_bin(); # as signed binary string with prefixed 0b $x->as_oct(); # as signed octal string with prefixed 0 # Other conversion methods $x->numify(); # return as scalar (might overflow or underflow) =head1 DESCRIPTION Math::BigInt provides support for arbitrary precision integers. Overloading is also provided for Perl operators. =head2 Input Input values to these routines may be any scalar number or string that looks like a number and represents an integer. =over =item * Leading and trailing whitespace is ignored. =item * Leading and trailing zeros are ignored. =item * If the string has a "0x" prefix, it is interpreted as a hexadecimal number. =item * If the string has a "0b" prefix, it is interpreted as a binary number. =item * One underline is allowed between any two digits. =item * If the string can not be interpreted, NaN is returned. =back Octal numbers are typically prefixed by "0", but since leading zeros are stripped, these methods can not automatically recognize octal numbers, so use the constructor from_oct() to interpret octal strings. Some examples of valid string input Input string Resulting value 123 123 1.23e2 123 12300e-2 123 0xcafe 51966 0b1101 13 67_538_754 67538754 -4_5_6.7_8_9e+0_1_0 -4567890000000 Input given as scalar numbers might lose precision. Quote your input to ensure that no digits are lost: $x = Math::BigInt->new( 56789012345678901234 ); # bad $x = Math::BigInt->new('56789012345678901234'); # good Currently, Math::BigInt->new() defaults to 0, while Math::BigInt->new('') results in 'NaN'. This might change in the future, so use always the following explicit forms to get a zero or NaN: $zero = Math::BigInt->bzero(); $nan = Math::BigInt->bnan(); =head2 Output Output values are usually Math::BigInt objects. Boolean operators C, C, C, etc. return true or false. Comparison operators C and C) return -1, 0, 1, or undef. =head1 METHODS =head2 Configuration methods Each of the methods below (except config(), accuracy() and precision()) accepts three additional parameters. These arguments C<$A>, C<$P> and C<$R> are C, C and C. Please see the section about L for more information. Setting a class variable effects all object instance that are created afterwards. =over =item accuracy() Math::BigInt->accuracy(5); # set class accuracy $x->accuracy(5); # set instance accuracy $A = Math::BigInt->accuracy(); # get class accuracy $A = $x->accuracy(); # get instance accuracy Set or get the accuracy, i.e., the number of significant digits. The accuracy must be an integer. If the accuracy is set to C, no rounding is done. Alternatively, one can round the results explicitly using one of L, L or L or by passing the desired accuracy to the method as an additional parameter: my $x = Math::BigInt->new(30000); my $y = Math::BigInt->new(7); print scalar $x->copy()->bdiv($y, 2); # prints 4300 print scalar $x->copy()->bdiv($y)->bround(2); # prints 4300 Please see the section about L for further details. $y = Math::BigInt->new(1234567); # $y is not rounded Math::BigInt->accuracy(4); # set class accuracy to 4 $x = Math::BigInt->new(1234567); # $x is rounded automatically print "$x $y"; # prints "1235000 1234567" print $x->accuracy(); # prints "4" print $y->accuracy(); # also prints "4", since # class accuracy is 4 Math::BigInt->accuracy(5); # set class accuracy to 5 print $x->accuracy(); # prints "4", since instance # accuracy is 4 print $y->accuracy(); # prints "5", since no instance # accuracy, and class accuracy is 5 Note: Each class has it's own globals separated from Math::BigInt, but it is possible to subclass Math::BigInt and make the globals of the subclass aliases to the ones from Math::BigInt. =item precision() Math::BigInt->precision(-2); # set class precision $x->precision(-2); # set instance precision $P = Math::BigInt->precision(); # get class precision $P = $x->precision(); # get instance precision Set or get the precision, i.e., the place to round relative to the decimal point. The precision must be a integer. Setting the precision to $P means that each number is rounded up or down, depending on the rounding mode, to the nearest multiple of 10**$P. If the precision is set to C, no rounding is done. You might want to use L instead. With L you set the number of digits each result should have, with L you set the place where to round. Please see the section about L for further details. $y = Math::BigInt->new(1234567); # $y is not rounded Math::BigInt->precision(4); # set class precision to 4 $x = Math::BigInt->new(1234567); # $x is rounded automatically print $x; # prints "1230000" Note: Each class has its own globals separated from Math::BigInt, but it is possible to subclass Math::BigInt and make the globals of the subclass aliases to the ones from Math::BigInt. =item div_scale() Set/get the fallback accuracy. This is the accuracy used when neither accuracy nor precision is set explicitly. It is used when a computation might otherwise attempt to return an infinite number of digits. =item round_mode() Set/get the rounding mode. =item upgrade() Set/get the class for upgrading. When a computation might result in a non-integer, the operands are upgraded to this class. This is used for instance by L. The default is C, thus the following operation creates a Math::BigInt, not a Math::BigFloat: my $i = Math::BigInt->new(123); my $f = Math::BigFloat->new('123.1'); print $i + $f, "\n"; # prints 246 =item downgrade() Set/get the class for downgrading. The default is C. Downgrading is not done by Math::BigInt. =item modify() $x->modify('bpowd'); This method returns 0 if the object can be modified with the given operation, or 1 if not. This is used for instance by L. =item config() use Data::Dumper; print Dumper ( Math::BigInt->config() ); print Math::BigInt->config()->{lib},"\n"; print Math::BigInt->config('lib')},"\n"; Returns a hash containing the configuration, e.g. the version number, lib loaded etc. The following hash keys are currently filled in with the appropriate information. key Description Example ============================================================ lib Name of the low-level math library Math::BigInt::Calc lib_version Version of low-level math library (see 'lib') 0.30 class The class name of config() you just called Math::BigInt upgrade To which class math operations might be upgraded Math::BigFloat downgrade To which class math operations might be downgraded undef precision Global precision undef accuracy Global accuracy undef round_mode Global round mode even version version number of the class you used 1.61 div_scale Fallback accuracy for div 40 trap_nan If true, traps creation of NaN via croak() 1 trap_inf If true, traps creation of +inf/-inf via croak() 1 The following values can be set by passing C a reference to a hash: accuracy precision round_mode div_scale upgrade downgrade trap_inf trap_nan Example: $new_cfg = Math::BigInt->config( { trap_inf => 1, precision => 5 } ); =back =head2 Constructor methods =over =item new() $x = Math::BigInt->new($str,$A,$P,$R); Creates a new Math::BigInt object from a scalar or another Math::BigInt object. The input is accepted as decimal, hexadecimal (with leading '0x') or binary (with leading '0b'). See L for more info on accepted input formats. =item from_hex() $x = Math::BigInt->from_hex("0xcafe"); # input is hexadecimal Interpret input as a hexadecimal string. A "0x" or "x" prefix is optional. A single underscore character may be placed right after the prefix, if present, or between any two digits. If the input is invalid, a NaN is returned. =item from_oct() $x = Math::BigInt->from_oct("0775"); # input is octal Interpret the input as an octal string and return the corresponding value. A "0" (zero) prefix is optional. A single underscore character may be placed right after the prefix, if present, or between any two digits. If the input is invalid, a NaN is returned. =item from_bin() $x = Math::BigInt->from_bin("0b10011"); # input is binary Interpret the input as a binary string. A "0b" or "b" prefix is optional. A single underscore character may be placed right after the prefix, if present, or between any two digits. If the input is invalid, a NaN is returned. =item from_bytes() $x = Math::BigInt->from_bytes("\xf3\x6b"); # $x = 62315 Interpret the input as a byte string, assuming big endian byte order. The output is always a non-negative, finite integer. In some special cases, from_bytes() matches the conversion done by unpack(): $b = "\x4e"; # one char byte string $x = Math::BigInt->from_bytes($b); # = 78 $y = unpack "C", $b; # ditto, but scalar $b = "\xf3\x6b"; # two char byte string $x = Math::BigInt->from_bytes($b); # = 62315 $y = unpack "S>", $b; # ditto, but scalar $b = "\x2d\xe0\x49\xad"; # four char byte string $x = Math::BigInt->from_bytes($b); # = 769673645 $y = unpack "L>", $b; # ditto, but scalar $b = "\x2d\xe0\x49\xad\x2d\xe0\x49\xad"; # eight char byte string $x = Math::BigInt->from_bytes($b); # = 3305723134637787565 $y = unpack "Q>", $b; # ditto, but scalar =item bzero() $x = Math::BigInt->bzero(); $x->bzero(); Returns a new Math::BigInt object representing zero. If used as an instance method, assigns the value to the invocand. =item bone() $x = Math::BigInt->bone(); # +1 $x = Math::BigInt->bone("+"); # +1 $x = Math::BigInt->bone("-"); # -1 $x->bone(); # +1 $x->bone("+"); # +1 $x->bone('-'); # -1 Creates a new Math::BigInt object representing one. The optional argument is either '-' or '+', indicating whether you want plus one or minus one. If used as an instance method, assigns the value to the invocand. =item binf() $x = Math::BigInt->binf($sign); Creates a new Math::BigInt object representing infinity. The optional argument is either '-' or '+', indicating whether you want infinity or minus infinity. If used as an instance method, assigns the value to the invocand. $x->binf(); $x->binf('-'); =item bnan() $x = Math::BigInt->bnan(); Creates a new Math::BigInt object representing NaN (Not A Number). If used as an instance method, assigns the value to the invocand. $x->bnan(); =item bpi() $x = Math::BigInt->bpi(100); # 3 $x->bpi(100); # 3 Creates a new Math::BigInt object representing PI. If used as an instance method, assigns the value to the invocand. With Math::BigInt this always returns 3. If upgrading is in effect, returns PI, rounded to N digits with the current rounding mode: use Math::BigFloat; use Math::BigInt upgrade => "Math::BigFloat"; print Math::BigInt->bpi(3), "\n"; # 3.14 print Math::BigInt->bpi(100), "\n"; # 3.1415.... =item copy() $x->copy(); # make a true copy of $x (unlike $y = $x) =item as_int() =item as_number() These methods are called when Math::BigInt encounters an object it doesn't know how to handle. For instance, assume $x is a Math::BigInt, or subclass thereof, and $y is defined, but not a Math::BigInt, or subclass thereof. If you do $x -> badd($y); $y needs to be converted into an object that $x can deal with. This is done by first checking if $y is something that $x might be upgraded to. If that is the case, no further attempts are made. The next is to see if $y supports the method C. If it does, C is called, but if it doesn't, the next thing is to see if $y supports the method C. If it does, C is called. The method C (and C) is expected to return either an object that has the same class as $x, a subclass thereof, or a string that Cnew()> can parse to create an object. C is an alias to C. C was introduced in v1.22, while C was introduced in v1.68. In Math::BigInt, C has the same effect as C. =back =head2 Boolean methods None of these methods modify the invocand object. =over =item is_zero() $x->is_zero(); # true if $x is 0 Returns true if the invocand is zero and false otherwise. =item is_one( [ SIGN ]) $x->is_one(); # true if $x is +1 $x->is_one("+"); # ditto $x->is_one("-"); # true if $x is -1 Returns true if the invocand is one and false otherwise. =item is_finite() $x->is_finite(); # true if $x is not +inf, -inf or NaN Returns true if the invocand is a finite number, i.e., it is neither +inf, -inf, nor NaN. =item is_inf( [ SIGN ] ) $x->is_inf(); # true if $x is +inf $x->is_inf("+"); # ditto $x->is_inf("-"); # true if $x is -inf Returns true if the invocand is infinite and false otherwise. =item is_nan() $x->is_nan(); # true if $x is NaN =item is_positive() =item is_pos() $x->is_positive(); # true if > 0 $x->is_pos(); # ditto Returns true if the invocand is positive and false otherwise. A C is neither positive nor negative. =item is_negative() =item is_neg() $x->is_negative(); # true if < 0 $x->is_neg(); # ditto Returns true if the invocand is negative and false otherwise. A C is neither positive nor negative. =item is_odd() $x->is_odd(); # true if odd, false for even Returns true if the invocand is odd and false otherwise. C, C<+inf>, and C<-inf> are neither odd nor even. =item is_even() $x->is_even(); # true if $x is even Returns true if the invocand is even and false otherwise. C, C<+inf>, C<-inf> are not integers and are neither odd nor even. =item is_int() $x->is_int(); # true if $x is an integer Returns true if the invocand is an integer and false otherwise. C, C<+inf>, C<-inf> are not integers. =back =head2 Comparison methods None of these methods modify the invocand object. Note that a C is neither less than, greater than, or equal to anything else, even a C. =over =item bcmp() $x->bcmp($y); Returns -1, 0, 1 depending on whether $x is less than, equal to, or grater than $y. Returns undef if any operand is a NaN. =item bacmp() $x->bacmp($y); Returns -1, 0, 1 depending on whether the absolute value of $x is less than, equal to, or grater than the absolute value of $y. Returns undef if any operand is a NaN. =item beq() $x -> beq($y); Returns true if and only if $x is equal to $y, and false otherwise. =item bne() $x -> bne($y); Returns true if and only if $x is not equal to $y, and false otherwise. =item blt() $x -> blt($y); Returns true if and only if $x is equal to $y, and false otherwise. =item ble() $x -> ble($y); Returns true if and only if $x is less than or equal to $y, and false otherwise. =item bgt() $x -> bgt($y); Returns true if and only if $x is greater than $y, and false otherwise. =item bge() $x -> bge($y); Returns true if and only if $x is greater than or equal to $y, and false otherwise. =back =head2 Arithmetic methods These methods modify the invocand object and returns it. =over =item bneg() $x->bneg(); Negate the number, e.g. change the sign between '+' and '-', or between '+inf' and '-inf', respectively. Does nothing for NaN or zero. =item babs() $x->babs(); Set the number to its absolute value, e.g. change the sign from '-' to '+' and from '-inf' to '+inf', respectively. Does nothing for NaN or positive numbers. =item bsgn() $x->bsgn(); Signum function. Set the number to -1, 0, or 1, depending on whether the number is negative, zero, or positive, respectively. Does not modify NaNs. =item bnorm() $x->bnorm(); # normalize (no-op) Normalize the number. This is a no-op and is provided only for backwards compatibility. =item binc() $x->binc(); # increment x by 1 =item bdec() $x->bdec(); # decrement x by 1 =item badd() $x->badd($y); # addition (add $y to $x) =item bsub() $x->bsub($y); # subtraction (subtract $y from $x) =item bmul() $x->bmul($y); # multiplication (multiply $x by $y) =item bmuladd() $x->bmuladd($y,$z); Multiply $x by $y, and then add $z to the result, This method was added in v1.87 of Math::BigInt (June 2007). =item bdiv() $x->bdiv($y); # divide, set $x to quotient Divides $x by $y by doing floored division (F-division), where the quotient is the floored (rounded towards negative infinity) quotient of the two operands. In list context, returns the quotient and the remainder. The remainder is either zero or has the same sign as the second operand. In scalar context, only the quotient is returned. The quotient is always the greatest integer less than or equal to the real-valued quotient of the two operands, and the remainder (when it is non-zero) always has the same sign as the second operand; so, for example, 1 / 4 => ( 0, 1) 1 / -4 => (-1, -3) -3 / 4 => (-1, 1) -3 / -4 => ( 0, -3) -11 / 2 => (-5, 1) 11 / -2 => (-5, -1) The behavior of the overloaded operator % agrees with the behavior of Perl's built-in % operator (as documented in the perlop manpage), and the equation $x == ($x / $y) * $y + ($x % $y) holds true for any finite $x and finite, non-zero $y. Perl's "use integer" might change the behaviour of % and / for scalars. This is because under 'use integer' Perl does what the underlying C library thinks is right, and this varies. However, "use integer" does not change the way things are done with Math::BigInt objects. =item btdiv() $x->btdiv($y); # divide, set $x to quotient Divides $x by $y by doing truncated division (T-division), where quotient is the truncated (rouneded towards zero) quotient of the two operands. In list context, returns the quotient and the remainder. The remainder is either zero or has the same sign as the first operand. In scalar context, only the quotient is returned. =item bmod() $x->bmod($y); # modulus (x % y) Returns $x modulo $y, i.e., the remainder after floored division (F-division). This method is like Perl's % operator. See L. =item btmod() $x->btmod($y); # modulus Returns the remainer after truncated division (T-division). See L. =item bmodinv() $x->bmodinv($mod); # modular multiplicative inverse Returns the multiplicative inverse of C<$x> modulo C<$mod>. If $y = $x -> copy() -> bmodinv($mod) then C<$y> is the number closest to zero, and with the same sign as C<$mod>, satisfying ($x * $y) % $mod = 1 % $mod If C<$x> and C<$y> are non-zero, they must be relative primes, i.e., C. 'C' is returned when no modular multiplicative inverse exists. =item bmodpow() $num->bmodpow($exp,$mod); # modular exponentiation # ($num**$exp % $mod) Returns the value of C<$num> taken to the power C<$exp> in the modulus C<$mod> using binary exponentiation. C is far superior to writing $num ** $exp % $mod because it is much faster - it reduces internal variables into the modulus whenever possible, so it operates on smaller numbers. C also supports negative exponents. bmodpow($num, -1, $mod) is exactly equivalent to bmodinv($num, $mod) =item bpow() $x->bpow($y); # power of arguments (x ** y) C (and the rounding functions) now modifies the first argument and returns it, unlike the old code which left it alone and only returned the result. This is to be consistent with C etc. The first three modifies $x, the last one won't: print bpow($x,$i),"\n"; # modify $x print $x->bpow($i),"\n"; # ditto print $x **= $i,"\n"; # the same print $x ** $i,"\n"; # leave $x alone The form C<$x **= $y> is faster than C<$x = $x ** $y;>, though. =item blog() $x->blog($base, $accuracy); # logarithm of x to the base $base If C<$base> is not defined, Euler's number (e) is used: print $x->blog(undef, 100); # log(x) to 100 digits =item bexp() $x->bexp($accuracy); # calculate e ** X Calculates the expression C where C is Euler's number. This method was added in v1.82 of Math::BigInt (April 2007). See also L. =item bnok() $x->bnok($y); # x over y (binomial coefficient n over k) Calculates the binomial coefficient n over k, also called the "choose" function. The result is equivalent to: ( n ) n! | - | = ------- ( k ) k!(n-k)! This method was added in v1.84 of Math::BigInt (April 2007). =item bsin() my $x = Math::BigInt->new(1); print $x->bsin(100), "\n"; Calculate the sine of $x, modifying $x in place. In Math::BigInt, unless upgrading is in effect, the result is truncated to an integer. This method was added in v1.87 of Math::BigInt (June 2007). =item bcos() my $x = Math::BigInt->new(1); print $x->bcos(100), "\n"; Calculate the cosine of $x, modifying $x in place. In Math::BigInt, unless upgrading is in effect, the result is truncated to an integer. This method was added in v1.87 of Math::BigInt (June 2007). =item batan() my $x = Math::BigFloat->new(0.5); print $x->batan(100), "\n"; Calculate the arcus tangens of $x, modifying $x in place. In Math::BigInt, unless upgrading is in effect, the result is truncated to an integer. This method was added in v1.87 of Math::BigInt (June 2007). =item batan2() my $x = Math::BigInt->new(1); my $y = Math::BigInt->new(1); print $y->batan2($x), "\n"; Calculate the arcus tangens of C<$y> divided by C<$x>, modifying $y in place. In Math::BigInt, unless upgrading is in effect, the result is truncated to an integer. This method was added in v1.87 of Math::BigInt (June 2007). =item bsqrt() $x->bsqrt(); # calculate square-root C returns the square root truncated to an integer. If you want a better approximation of the square root, then use: $x = Math::BigFloat->new(12); Math::BigFloat->precision(0); Math::BigFloat->round_mode('even'); print $x->copy->bsqrt(),"\n"; # 4 Math::BigFloat->precision(2); print $x->bsqrt(),"\n"; # 3.46 print $x->bsqrt(3),"\n"; # 3.464 =item broot() $x->broot($N); Calculates the N'th root of C<$x>. =item bfac() $x->bfac(); # factorial of $x (1*2*3*4*..*$x) Returns the factorial of C<$x>, i.e., the product of all positive integers up to and including C<$x>. =item bdfac() $x->bdfac(); # double factorial of $x (1*2*3*4*..*$x) Returns the double factorial of C<$x>. If C<$x> is an even integer, returns the product of all positive, even integers up to and including C<$x>, i.e., 2*4*6*...*$x. If C<$x> is an odd integer, returns the product of all positive, odd integers, i.e., 1*3*5*...*$x. =item bfib() $F = $n->bfib(); # a single Fibonacci number @F = $n->bfib(); # a list of Fibonacci numbers In scalar context, returns a single Fibonacci number. In list context, returns a list of Fibonacci numbers. The invocand is the last element in the output. The Fibonacci sequence is defined by F(0) = 0 F(1) = 1 F(n) = F(n-1) + F(n-2) In list context, F(0) and F(n) is the first and last number in the output, respectively. For example, if $n is 12, then C<< @F = $n->bfib() >> returns the following values, F(0) to F(12): 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144 The sequence can also be extended to negative index n using the re-arranged recurrence relation F(n-2) = F(n) - F(n-1) giving the bidirectional sequence n -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 F(n) 13 -8 5 -3 2 -1 1 0 1 1 2 3 5 8 13 If $n is -12, the following values, F(0) to F(12), are returned: 0, 1, -1, 2, -3, 5, -8, 13, -21, 34, -55, 89, -144 =item blucas() $F = $n->blucas(); # a single Lucas number @F = $n->blucas(); # a list of Lucas numbers In scalar context, returns a single Lucas number. In list context, returns a list of Lucas numbers. The invocand is the last element in the output. The Lucas sequence is defined by L(0) = 2 L(1) = 1 L(n) = L(n-1) + L(n-2) In list context, L(0) and L(n) is the first and last number in the output, respectively. For example, if $n is 12, then C<< @L = $n->blucas() >> returns the following values, L(0) to L(12): 2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199, 322 The sequence can also be extended to negative index n using the re-arranged recurrence relation L(n-2) = L(n) - L(n-1) giving the bidirectional sequence n -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 L(n) 29 -18 11 -7 4 -3 1 2 1 3 4 7 11 18 29 If $n is -12, the following values, L(0) to L(-12), are returned: 2, 1, -3, 4, -7, 11, -18, 29, -47, 76, -123, 199, -322 =item brsft() $x->brsft($n); # right shift $n places in base 2 $x->brsft($n, $b); # right shift $n places in base $b The latter is equivalent to $x -> bdiv($b -> copy() -> bpow($n)) =item blsft() $x->blsft($n); # left shift $n places in base 2 $x->blsft($n, $b); # left shift $n places in base $b The latter is equivalent to $x -> bmul($b -> copy() -> bpow($n)) =back =head2 Bitwise methods =over =item band() $x->band($y); # bitwise and =item bior() $x->bior($y); # bitwise inclusive or =item bxor() $x->bxor($y); # bitwise exclusive or =item bnot() $x->bnot(); # bitwise not (two's complement) Two's complement (bitwise not). This is equivalent to, but faster than, $x->binc()->bneg(); =back =head2 Rounding methods =over =item round() $x->round($A,$P,$round_mode); Round $x to accuracy C<$A> or precision C<$P> using the round mode C<$round_mode>. =item bround() $x->bround($N); # accuracy: preserve $N digits Rounds $x to an accuracy of $N digits. =item bfround() $x->bfround($N); Rounds to a multiple of 10**$N. Examples: Input N Result 123456.123456 3 123500 123456.123456 2 123450 123456.123456 -2 123456.12 123456.123456 -3 123456.123 =item bfloor() $x->bfloor(); Round $x towards minus infinity, i.e., set $x to the largest integer less than or equal to $x. =item bceil() $x->bceil(); Round $x towards plus infinity, i.e., set $x to the smallest integer greater than or equal to $x). =item bint() $x->bint(); Round $x towards zero. =back =head2 Other mathematical methods =over =item bgcd() $x -> bgcd($y); # GCD of $x and $y $x -> bgcd($y, $z, ...); # GCD of $x, $y, $z, ... Returns the greatest common divisor (GCD). =item blcm() $x -> blcm($y); # LCM of $x and $y $x -> blcm($y, $z, ...); # LCM of $x, $y, $z, ... Returns the least common multiple (LCM). =back =head2 Object property methods =over =item sign() $x->sign(); Return the sign, of $x, meaning either C<+>, C<->, C<-inf>, C<+inf> or NaN. If you want $x to have a certain sign, use one of the following methods: $x->babs(); # '+' $x->babs()->bneg(); # '-' $x->bnan(); # 'NaN' $x->binf(); # '+inf' $x->binf('-'); # '-inf' =item digit() $x->digit($n); # return the nth digit, counting from right If C<$n> is negative, returns the digit counting from left. =item length() $x->length(); ($xl, $fl) = $x->length(); Returns the number of digits in the decimal representation of the number. In list context, returns the length of the integer and fraction part. For Math::BigInt objects, the length of the fraction part is always 0. The following probably doesn't do what you expect: $c = Math::BigInt->new(123); print $c->length(),"\n"; # prints 30 It prints both the number of digits in the number and in the fraction part since print calls C in list context. Use something like: print scalar $c->length(),"\n"; # prints 3 =item mantissa() $x->mantissa(); Return the signed mantissa of $x as a Math::BigInt. =item exponent() $x->exponent(); Return the exponent of $x as a Math::BigInt. =item parts() $x->parts(); Returns the significand (mantissa) and the exponent as integers. In Math::BigFloat, both are returned as Math::BigInt objects. =item sparts() Returns the significand (mantissa) and the exponent as integers. In scalar context, only the significand is returned. The significand is the integer with the smallest absolute value. The output of C corresponds to the output from C. In Math::BigInt, this method is identical to C. =item nparts() Returns the significand (mantissa) and exponent corresponding to normalized notation. In scalar context, only the significand is returned. For finite non-zero numbers, the significand's absolute value is greater than or equal to 1 and less than 10. The output of C corresponds to the output from C. In Math::BigInt, if the significand can not be represented as an integer, upgrading is performed or NaN is returned. =item eparts() Returns the significand (mantissa) and exponent corresponding to engineering notation. In scalar context, only the significand is returned. For finite non-zero numbers, the significand's absolute value is greater than or equal to 1 and less than 1000, and the exponent is a multiple of 3. The output of C corresponds to the output from C. In Math::BigInt, if the significand can not be represented as an integer, upgrading is performed or NaN is returned. =item dparts() Returns the integer part and the fraction part. If the fraction part can not be represented as an integer, upgrading is performed or NaN is returned. The output of C corresponds to the output from C. =back =head2 String conversion methods =over =item bstr() Returns a string representing the number using decimal notation. In Math::BigFloat, the output is zero padded according to the current accuracy or precision, if any of those are defined. =item bsstr() Returns a string representing the number using scientific notation where both the significand (mantissa) and the exponent are integers. The output corresponds to the output from C. 123 is returned as "123e+0" 1230 is returned as "123e+1" 12300 is returned as "123e+2" 12000 is returned as "12e+3" 10000 is returned as "1e+4" =item bnstr() Returns a string representing the number using normalized notation, the most common variant of scientific notation. For finite non-zero numbers, the absolute value of the significand is less than or equal to 1 and less than 10. The output corresponds to the output from C. 123 is returned as "1.23e+2" 1230 is returned as "1.23e+3" 12300 is returned as "1.23e+4" 12000 is returned as "1.2e+4" 10000 is returned as "1e+4" =item bestr() Returns a string representing the number using engineering notation. For finite non-zero numbers, the absolute value of the significand is less than or equal to 1 and less than 1000, and the exponent is a multiple of 3. The output corresponds to the output from C. 123 is returned as "123e+0" 1230 is returned as "1.23e+3" 12300 is returned as "12.3e+3" 12000 is returned as "12e+3" 10000 is returned as "10e+3" =item bdstr() Returns a string representing the number using decimal notation. The output corresponds to the output from C. 123 is returned as "123" 1230 is returned as "1230" 12300 is returned as "12300" 12000 is returned as "12000" 10000 is returned as "10000" =item to_hex() $x->to_hex(); Returns a hexadecimal string representation of the number. =item to_bin() $x->to_bin(); Returns a binary string representation of the number. =item to_oct() $x->to_oct(); Returns an octal string representation of the number. =item to_bytes() $x = Math::BigInt->new("1667327589"); $s = $x->to_bytes(); # $s = "cafe" Returns a byte string representation of the number using big endian byte order. The invocand must be a non-negative, finite integer. =item as_hex() $x->as_hex(); As, C, but with a "0x" prefix. =item as_bin() $x->as_bin(); As, C, but with a "0b" prefix. =item as_oct() $x->as_oct(); As, C, but with a "0" prefix. =item as_bytes() This is just an alias for C. =back =head2 Other conversion methods =over =item numify() print $x->numify(); Returns a Perl scalar from $x. It is used automatically whenever a scalar is needed, for instance in array index operations. =back =head1 ACCURACY and PRECISION Math::BigInt and Math::BigFloat have full support for accuracy and precision based rounding, both automatically after every operation, as well as manually. This section describes the accuracy/precision handling in Math::BigInt and Math::BigFloat as it used to be and as it is now, complete with an explanation of all terms and abbreviations. Not yet implemented things (but with correct description) are marked with '!', things that need to be answered are marked with '?'. In the next paragraph follows a short description of terms used here (because these may differ from terms used by others people or documentation). During the rest of this document, the shortcuts A (for accuracy), P (for precision), F (fallback) and R (rounding mode) are be used. =head2 Precision P Precision is a fixed number of digits before (positive) or after (negative) the decimal point. For example, 123.45 has a precision of -2. 0 means an integer like 123 (or 120). A precision of 2 means at least two digits to the left of the decimal point are zero, so 123 with P = 1 becomes 120. Note that numbers with zeros before the decimal point may have different precisions, because 1200 can have P = 0, 1 or 2 (depending on what the initial value was). It could also have p < 0, when the digits after the decimal point are zero. The string output (of floating point numbers) is padded with zeros: Initial value P A Result String ------------------------------------------------------------ 1234.01 -3 1000 1000 1234 -2 1200 1200 1234.5 -1 1230 1230 1234.001 1 1234 1234.0 1234.01 0 1234 1234 1234.01 2 1234.01 1234.01 1234.01 5 1234.01 1234.01000 For Math::BigInt objects, no padding occurs. =head2 Accuracy A Number of significant digits. Leading zeros are not counted. A number may have an accuracy greater than the non-zero digits when there are zeros in it or trailing zeros. For example, 123.456 has A of 6, 10203 has 5, 123.0506 has 7, 123.45000 has 8 and 0.000123 has 3. The string output (of floating point numbers) is padded with zeros: Initial value P A Result String ------------------------------------------------------------ 1234.01 3 1230 1230 1234.01 6 1234.01 1234.01 1234.1 8 1234.1 1234.1000 For Math::BigInt objects, no padding occurs. =head2 Fallback F When both A and P are undefined, this is used as a fallback accuracy when dividing numbers. =head2 Rounding mode R When rounding a number, different 'styles' or 'kinds' of rounding are possible. (Note that random rounding, as in Math::Round, is not implemented.) =over =item 'trunc' truncation invariably removes all digits following the rounding place, replacing them with zeros. Thus, 987.65 rounded to tens (P = 1) becomes 980, and rounded to the fourth sigdig becomes 987.6 (A = 4). 123.456 rounded to the second place after the decimal point (P = -2) becomes 123.46. All other implemented styles of rounding attempt to round to the "nearest digit." If the digit D immediately to the right of the rounding place (skipping the decimal point) is greater than 5, the number is incremented at the rounding place (possibly causing a cascade of incrementation): e.g. when rounding to units, 0.9 rounds to 1, and -19.9 rounds to -20. If D < 5, the number is similarly truncated at the rounding place: e.g. when rounding to units, 0.4 rounds to 0, and -19.4 rounds to -19. However the results of other styles of rounding differ if the digit immediately to the right of the rounding place (skipping the decimal point) is 5 and if there are no digits, or no digits other than 0, after that 5. In such cases: =item 'even' rounds the digit at the rounding place to 0, 2, 4, 6, or 8 if it is not already. E.g., when rounding to the first sigdig, 0.45 becomes 0.4, -0.55 becomes -0.6, but 0.4501 becomes 0.5. =item 'odd' rounds the digit at the rounding place to 1, 3, 5, 7, or 9 if it is not already. E.g., when rounding to the first sigdig, 0.45 becomes 0.5, -0.55 becomes -0.5, but 0.5501 becomes 0.6. =item '+inf' round to plus infinity, i.e. always round up. E.g., when rounding to the first sigdig, 0.45 becomes 0.5, -0.55 becomes -0.5, and 0.4501 also becomes 0.5. =item '-inf' round to minus infinity, i.e. always round down. E.g., when rounding to the first sigdig, 0.45 becomes 0.4, -0.55 becomes -0.6, but 0.4501 becomes 0.5. =item 'zero' round to zero, i.e. positive numbers down, negative ones up. E.g., when rounding to the first sigdig, 0.45 becomes 0.4, -0.55 becomes -0.5, but 0.4501 becomes 0.5. =item 'common' round up if the digit immediately to the right of the rounding place is 5 or greater, otherwise round down. E.g., 0.15 becomes 0.2 and 0.149 becomes 0.1. =back The handling of A & P in MBI/MBF (the old core code shipped with Perl versions <= 5.7.2) is like this: =over =item Precision * bfround($p) is able to round to $p number of digits after the decimal point * otherwise P is unused =item Accuracy (significant digits) * bround($a) rounds to $a significant digits * only bdiv() and bsqrt() take A as (optional) parameter + other operations simply create the same number (bneg etc), or more (bmul) of digits + rounding/truncating is only done when explicitly calling one of bround or bfround, and never for Math::BigInt (not implemented) * bsqrt() simply hands its accuracy argument over to bdiv. * the documentation and the comment in the code indicate two different ways on how bdiv() determines the maximum number of digits it should calculate, and the actual code does yet another thing POD: max($Math::BigFloat::div_scale,length(dividend)+length(divisor)) Comment: result has at most max(scale, length(dividend), length(divisor)) digits Actual code: scale = max(scale, length(dividend)-1,length(divisor)-1); scale += length(divisor) - length(dividend); So for lx = 3, ly = 9, scale = 10, scale will actually be 16 (10 So for lx = 3, ly = 9, scale = 10, scale will actually be 16 (10+9-3). Actually, the 'difference' added to the scale is cal- culated from the number of "significant digits" in dividend and divisor, which is derived by looking at the length of the man- tissa. Which is wrong, since it includes the + sign (oops) and actually gets 2 for '+100' and 4 for '+101'. Oops again. Thus 124/3 with div_scale=1 will get you '41.3' based on the strange assumption that 124 has 3 significant digits, while 120/7 will get you '17', not '17.1' since 120 is thought to have 2 signif- icant digits. The rounding after the division then uses the remainder and $y to determine whether it must round up or down. ? I have no idea which is the right way. That's why I used a slightly more ? simple scheme and tweaked the few failing testcases to match it. =back This is how it works now: =over =item Setting/Accessing * You can set the A global via Math::BigInt->accuracy() or Math::BigFloat->accuracy() or whatever class you are using. * You can also set P globally by using Math::SomeClass->precision() likewise. * Globals are classwide, and not inherited by subclasses. * to undefine A, use Math::SomeCLass->accuracy(undef); * to undefine P, use Math::SomeClass->precision(undef); * Setting Math::SomeClass->accuracy() clears automatically Math::SomeClass->precision(), and vice versa. * To be valid, A must be > 0, P can have any value. * If P is negative, this means round to the P'th place to the right of the decimal point; positive values mean to the left of the decimal point. P of 0 means round to integer. * to find out the current global A, use Math::SomeClass->accuracy() * to find out the current global P, use Math::SomeClass->precision() * use $x->accuracy() respective $x->precision() for the local setting of $x. * Please note that $x->accuracy() respective $x->precision() return eventually defined global A or P, when $x's A or P is not set. =item Creating numbers * When you create a number, you can give the desired A or P via: $x = Math::BigInt->new($number,$A,$P); * Only one of A or P can be defined, otherwise the result is NaN * If no A or P is give ($x = Math::BigInt->new($number) form), then the globals (if set) will be used. Thus changing the global defaults later on will not change the A or P of previously created numbers (i.e., A and P of $x will be what was in effect when $x was created) * If given undef for A and P, NO rounding will occur, and the globals will NOT be used. This is used by subclasses to create numbers without suffering rounding in the parent. Thus a subclass is able to have its own globals enforced upon creation of a number by using $x = Math::BigInt->new($number,undef,undef): use Math::BigInt::SomeSubclass; use Math::BigInt; Math::BigInt->accuracy(2); Math::BigInt::SomeSubClass->accuracy(3); $x = Math::BigInt::SomeSubClass->new(1234); $x is now 1230, and not 1200. A subclass might choose to implement this otherwise, e.g. falling back to the parent's A and P. =item Usage * If A or P are enabled/defined, they are used to round the result of each operation according to the rules below * Negative P is ignored in Math::BigInt, since Math::BigInt objects never have digits after the decimal point * Math::BigFloat uses Math::BigInt internally, but setting A or P inside Math::BigInt as globals does not tamper with the parts of a Math::BigFloat. A flag is used to mark all Math::BigFloat numbers as 'never round'. =item Precedence * It only makes sense that a number has only one of A or P at a time. If you set either A or P on one object, or globally, the other one will be automatically cleared. * If two objects are involved in an operation, and one of them has A in effect, and the other P, this results in an error (NaN). * A takes precedence over P (Hint: A comes before P). If neither of them is defined, nothing is used, i.e. the result will have as many digits as it can (with an exception for bdiv/bsqrt) and will not be rounded. * There is another setting for bdiv() (and thus for bsqrt()). If neither of A or P is defined, bdiv() will use a fallback (F) of $div_scale digits. If either the dividend's or the divisor's mantissa has more digits than the value of F, the higher value will be used instead of F. This is to limit the digits (A) of the result (just consider what would happen with unlimited A and P in the case of 1/3 :-) * bdiv will calculate (at least) 4 more digits than required (determined by A, P or F), and, if F is not used, round the result (this will still fail in the case of a result like 0.12345000000001 with A or P of 5, but this can not be helped - or can it?) * Thus you can have the math done by on Math::Big* class in two modi: + never round (this is the default): This is done by setting A and P to undef. No math operation will round the result, with bdiv() and bsqrt() as exceptions to guard against overflows. You must explicitly call bround(), bfround() or round() (the latter with parameters). Note: Once you have rounded a number, the settings will 'stick' on it and 'infect' all other numbers engaged in math operations with it, since local settings have the highest precedence. So, to get SaferRound[tm], use a copy() before rounding like this: $x = Math::BigFloat->new(12.34); $y = Math::BigFloat->new(98.76); $z = $x * $y; # 1218.6984 print $x->copy()->bround(3); # 12.3 (but A is now 3!) $z = $x * $y; # still 1218.6984, without # copy would have been 1210! + round after each op: After each single operation (except for testing like is_zero()), the method round() is called and the result is rounded appropriately. By setting proper values for A and P, you can have all-the-same-A or all-the-same-P modes. For example, Math::Currency might set A to undef, and P to -2, globally. ?Maybe an extra option that forbids local A & P settings would be in order, ?so that intermediate rounding does not 'poison' further math? =item Overriding globals * you will be able to give A, P and R as an argument to all the calculation routines; the second parameter is A, the third one is P, and the fourth is R (shift right by one for binary operations like badd). P is used only if the first parameter (A) is undefined. These three parameters override the globals in the order detailed as follows, i.e. the first defined value wins: (local: per object, global: global default, parameter: argument to sub) + parameter A + parameter P + local A (if defined on both of the operands: smaller one is taken) + local P (if defined on both of the operands: bigger one is taken) + global A + global P + global F * bsqrt() will hand its arguments to bdiv(), as it used to, only now for two arguments (A and P) instead of one =item Local settings * You can set A or P locally by using $x->accuracy() or $x->precision() and thus force different A and P for different objects/numbers. * Setting A or P this way immediately rounds $x to the new value. * $x->accuracy() clears $x->precision(), and vice versa. =item Rounding * the rounding routines will use the respective global or local settings. bround() is for accuracy rounding, while bfround() is for precision * the two rounding functions take as the second parameter one of the following rounding modes (R): 'even', 'odd', '+inf', '-inf', 'zero', 'trunc', 'common' * you can set/get the global R by using Math::SomeClass->round_mode() or by setting $Math::SomeClass::round_mode * after each operation, $result->round() is called, and the result may eventually be rounded (that is, if A or P were set either locally, globally or as parameter to the operation) * to manually round a number, call $x->round($A,$P,$round_mode); this will round the number by using the appropriate rounding function and then normalize it. * rounding modifies the local settings of the number: $x = Math::BigFloat->new(123.456); $x->accuracy(5); $x->bround(4); Here 4 takes precedence over 5, so 123.5 is the result and $x->accuracy() will be 4 from now on. =item Default values * R: 'even' * F: 40 * A: undef * P: undef =item Remarks * The defaults are set up so that the new code gives the same results as the old code (except in a few cases on bdiv): + Both A and P are undefined and thus will not be used for rounding after each operation. + round() is thus a no-op, unless given extra parameters A and P =back =head1 Infinity and Not a Number While Math::BigInt has extensive handling of inf and NaN, certain quirks remain. =over =item oct()/hex() These perl routines currently (as of Perl v.5.8.6) cannot handle passed inf. te@linux:~> perl -wle 'print 2 ** 3333' Inf te@linux:~> perl -wle 'print 2 ** 3333 == 2 ** 3333' 1 te@linux:~> perl -wle 'print oct(2 ** 3333)' 0 te@linux:~> perl -wle 'print hex(2 ** 3333)' Illegal hexadecimal digit 'I' ignored at -e line 1. 0 The same problems occur if you pass them Math::BigInt->binf() objects. Since overloading these routines is not possible, this cannot be fixed from Math::BigInt. =back =head1 INTERNALS You should neither care about nor depend on the internal representation; it might change without notice. Use B method calls like C<< $x->sign(); >> instead relying on the internal representation. =head2 MATH LIBRARY Math with the numbers is done (by default) by a module called C. This is equivalent to saying: use Math::BigInt try => 'Calc'; You can change this backend library by using: use Math::BigInt try => 'GMP'; B: General purpose packages should not be explicit about the library to use; let the script author decide which is best. If your script works with huge numbers and Calc is too slow for them, you can also for the loading of one of these libraries and if none of them can be used, the code dies: use Math::BigInt only => 'GMP,Pari'; The following would first try to find Math::BigInt::Foo, then Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc: use Math::BigInt try => 'Foo,Math::BigInt::Bar'; The library that is loaded last is used. Note that this can be overwritten at any time by loading a different library, and numbers constructed with different libraries cannot be used in math operations together. =head3 What library to use? B: General purpose packages should not be explicit about the library to use; let the script author decide which is best. L and L are in cases involving big numbers much faster than Calc, however it is slower when dealing with very small numbers (less than about 20 digits) and when converting very large numbers to decimal (for instance for printing, rounding, calculating their length in decimal etc). So please select carefully what library you want to use. Different low-level libraries use different formats to store the numbers. However, you should B depend on the number having a specific format internally. See the respective math library module documentation for further details. =head2 SIGN The sign is either '+', '-', 'NaN', '+inf' or '-inf'. A sign of 'NaN' is used to represent the result when input arguments are not numbers or as a result of 0/0. '+inf' and '-inf' represent plus respectively minus infinity. You get '+inf' when dividing a positive number by 0, and '-inf' when dividing any negative number by 0. =head1 EXAMPLES use Math::BigInt; sub bigint { Math::BigInt->new(shift); } $x = Math::BigInt->bstr("1234") # string "1234" $x = "$x"; # same as bstr() $x = Math::BigInt->bneg("1234"); # Math::BigInt "-1234" $x = Math::BigInt->babs("-12345"); # Math::BigInt "12345" $x = Math::BigInt->bnorm("-0.00"); # Math::BigInt "0" $x = bigint(1) + bigint(2); # Math::BigInt "3" $x = bigint(1) + "2"; # ditto (auto-Math::BigIntify of "2") $x = bigint(1); # Math::BigInt "1" $x = $x + 5 / 2; # Math::BigInt "3" $x = $x ** 3; # Math::BigInt "27" $x *= 2; # Math::BigInt "54" $x = Math::BigInt->new(0); # Math::BigInt "0" $x--; # Math::BigInt "-1" $x = Math::BigInt->badd(4,5) # Math::BigInt "9" print $x->bsstr(); # 9e+0 Examples for rounding: use Math::BigFloat; use Test::More; $x = Math::BigFloat->new(123.4567); $y = Math::BigFloat->new(123.456789); Math::BigFloat->accuracy(4); # no more A than 4 is ($x->copy()->bround(),123.4); # even rounding print $x->copy()->bround(),"\n"; # 123.4 Math::BigFloat->round_mode('odd'); # round to odd print $x->copy()->bround(),"\n"; # 123.5 Math::BigFloat->accuracy(5); # no more A than 5 Math::BigFloat->round_mode('odd'); # round to odd print $x->copy()->bround(),"\n"; # 123.46 $y = $x->copy()->bround(4),"\n"; # A = 4: 123.4 print "$y, ",$y->accuracy(),"\n"; # 123.4, 4 Math::BigFloat->accuracy(undef); # A not important now Math::BigFloat->precision(2); # P important print $x->copy()->bnorm(),"\n"; # 123.46 print $x->copy()->bround(),"\n"; # 123.46 Examples for converting: my $x = Math::BigInt->new('0b1'.'01' x 123); print "bin: ",$x->as_bin()," hex:",$x->as_hex()," dec: ",$x,"\n"; =head1 Autocreating constants After C all the B decimal, hexadecimal and binary constants in the given scope are converted to C. This conversion happens at compile time. In particular, perl -MMath::BigInt=:constant -e 'print 2**100,"\n"' prints the integer value of C<2**100>. Note that without conversion of constants the expression 2**100 is calculated using Perl scalars. Please note that strings and floating point constants are not affected, so that use Math::BigInt qw/:constant/; $x = 1234567890123456789012345678901234567890 + 123456789123456789; $y = '1234567890123456789012345678901234567890' + '123456789123456789'; does not give you what you expect. You need an explicit Math::BigInt->new() around one of the operands. You should also quote large constants to protect loss of precision: use Math::BigInt; $x = Math::BigInt->new('1234567889123456789123456789123456789'); Without the quotes Perl would convert the large number to a floating point constant at compile time and then hand the result to Math::BigInt, which results in an truncated result or a NaN. This also applies to integers that look like floating point constants: use Math::BigInt ':constant'; print ref(123e2),"\n"; print ref(123.2e2),"\n"; prints nothing but newlines. Use either L or L to get this to work. =head1 PERFORMANCE Using the form $x += $y; etc over $x = $x + $y is faster, since a copy of $x must be made in the second case. For long numbers, the copy can eat up to 20% of the work (in the case of addition/subtraction, less for multiplication/division). If $y is very small compared to $x, the form $x += $y is MUCH faster than $x = $x + $y since making the copy of $x takes more time then the actual addition. With a technique called copy-on-write, the cost of copying with overload could be minimized or even completely avoided. A test implementation of COW did show performance gains for overloaded math, but introduced a performance loss due to a constant overhead for all other operations. So Math::BigInt does currently not COW. The rewritten version of this module (vs. v0.01) is slower on certain operations, like C, C and C. The reason are that it does now more work and handles much more cases. The time spent in these operations is usually gained in the other math operations so that code on the average should get (much) faster. If they don't, please contact the author. Some operations may be slower for small numbers, but are significantly faster for big numbers. Other operations are now constant (O(1), like C, C etc), instead of O(N) and thus nearly always take much less time. These optimizations were done on purpose. If you find the Calc module to slow, try to install any of the replacement modules and see if they help you. =head2 Alternative math libraries You can use an alternative library to drive Math::BigInt. See the section L for more information. For more benchmark results see L. =head1 SUBCLASSING =head2 Subclassing Math::BigInt The basic design of Math::BigInt allows simple subclasses with very little work, as long as a few simple rules are followed: =over =item * The public API must remain consistent, i.e. if a sub-class is overloading addition, the sub-class must use the same name, in this case badd(). The reason for this is that Math::BigInt is optimized to call the object methods directly. =item * The private object hash keys like C<< $x->{sign} >> may not be changed, but additional keys can be added, like C<< $x->{_custom} >>. =item * Accessor functions are available for all existing object hash keys and should be used instead of directly accessing the internal hash keys. The reason for this is that Math::BigInt itself has a pluggable interface which permits it to support different storage methods. =back More complex sub-classes may have to replicate more of the logic internal of Math::BigInt if they need to change more basic behaviors. A subclass that needs to merely change the output only needs to overload C. All other object methods and overloaded functions can be directly inherited from the parent class. At the very minimum, any subclass needs to provide its own C and can store additional hash keys in the object. There are also some package globals that must be defined, e.g.: # Globals $accuracy = undef; $precision = -2; # round to 2 decimal places $round_mode = 'even'; $div_scale = 40; Additionally, you might want to provide the following two globals to allow auto-upgrading and auto-downgrading to work correctly: $upgrade = undef; $downgrade = undef; This allows Math::BigInt to correctly retrieve package globals from the subclass, like C<$SubClass::precision>. See t/Math/BigInt/Subclass.pm or t/Math/BigFloat/SubClass.pm completely functional subclass examples. Don't forget to use overload; in your subclass to automatically inherit the overloading from the parent. If you like, you can change part of the overloading, look at Math::String for an example. =head1 UPGRADING When used like this: use Math::BigInt upgrade => 'Foo::Bar'; certain operations 'upgrade' their calculation and thus the result to the class Foo::Bar. Usually this is used in conjunction with Math::BigFloat: use Math::BigInt upgrade => 'Math::BigFloat'; As a shortcut, you can use the module L: use bignum; Also good for one-liners: perl -Mbignum -le 'print 2 ** 255' This makes it possible to mix arguments of different classes (as in 2.5 + 2) as well es preserve accuracy (as in sqrt(3)). Beware: This feature is not fully implemented yet. =head2 Auto-upgrade The following methods upgrade themselves unconditionally; that is if upgrade is in effect, they always hands up their work: div bsqrt blog bexp bpi bsin bcos batan batan2 All other methods upgrade themselves only when one (or all) of their arguments are of the class mentioned in $upgrade. =head1 EXPORTS C exports nothing by default, but can export the following methods: bgcd blcm =head1 CAVEATS Some things might not work as you expect them. Below is documented what is known to be troublesome: =over =item Comparing numbers as strings Both C and C as well as stringify via overload drop the leading '+'. This is to be consistent with Perl and to make C (especially with overloading) to work as you expect. It also solves problems with C and L, which stringify arguments before comparing them. Mark Biggar said, when asked about to drop the '+' altogether, or make only C work: I agree (with the first alternative), don't add the '+' on positive numbers. It's not as important anymore with the new internal form for numbers. It made doing things like abs and neg easier, but those have to be done differently now anyway. So, the following examples now works as expected: use Test::More tests => 1; use Math::BigInt; my $x = Math::BigInt -> new(3*3); my $y = Math::BigInt -> new(3*3); is($x,3*3, 'multiplication'); print "$x eq 9" if $x eq $y; print "$x eq 9" if $x eq '9'; print "$x eq 9" if $x eq 3*3; Additionally, the following still works: print "$x == 9" if $x == $y; print "$x == 9" if $x == 9; print "$x == 9" if $x == 3*3; There is now a C method to get the string in scientific notation aka C<1e+2> instead of C<100>. Be advised that overloaded 'eq' always uses bstr() for comparison, but Perl represents some numbers as 100 and others as 1e+308. If in doubt, convert both arguments to Math::BigInt before comparing them as strings: use Test::More tests => 3; use Math::BigInt; $x = Math::BigInt->new('1e56'); $y = 1e56; is($x,$y); # fails is($x->bsstr(),$y); # okay $y = Math::BigInt->new($y); is($x,$y); # okay Alternatively, simply use C<< <=> >> for comparisons, this always gets it right. There is not yet a way to get a number automatically represented as a string that matches exactly the way Perl represents it. See also the section about L for problems in comparing NaNs. =item int() C returns (at least for Perl v5.7.1 and up) another Math::BigInt, not a Perl scalar: $x = Math::BigInt->new(123); $y = int($x); # 123 as a Math::BigInt $x = Math::BigFloat->new(123.45); $y = int($x); # 123 as a Math::BigFloat If you want a real Perl scalar, use C: $y = $x->numify(); # 123 as a scalar This is seldom necessary, though, because this is done automatically, like when you access an array: $z = $array[$x]; # does work automatically =item Modifying and = Beware of: $x = Math::BigFloat->new(5); $y = $x; This makes a second reference to the B object and stores it in $y. Thus anything that modifies $x (except overloaded operators) also modifies $y, and vice versa. Or in other words, C<=> is only safe if you modify your Math::BigInt objects only via overloaded math. As soon as you use a method call it breaks: $x->bmul(2); print "$x, $y\n"; # prints '10, 10' If you want a true copy of $x, use: $y = $x->copy(); You can also chain the calls like this, this first makes a copy and then multiply it by 2: $y = $x->copy()->bmul(2); See also the documentation for overload.pm regarding C<=>. =item Overloading -$x The following: $x = -$x; is slower than $x->bneg(); since overload calls C instead of C. The first variant needs to preserve $x since it does not know that it later gets overwritten. This makes a copy of $x and takes O(N), but $x->bneg() is O(1). =item Mixing different object types With overloaded operators, it is the first (dominating) operand that determines which method is called. Here are some examples showing what actually gets called in various cases. use Math::BigInt; use Math::BigFloat; $mbf = Math::BigFloat->new(5); $mbi2 = Math::BigInt->new(5); $mbi = Math::BigInt->new(2); # what actually gets called: $float = $mbf + $mbi; # $mbf->badd($mbi) $float = $mbf / $mbi; # $mbf->bdiv($mbi) $integer = $mbi + $mbf; # $mbi->badd($mbf) $integer = $mbi2 / $mbi; # $mbi2->bdiv($mbi) $integer = $mbi2 / $mbf; # $mbi2->bdiv($mbf) For instance, Math::BigInt->bdiv() always returns a Math::BigInt, regardless of whether the second operant is a Math::BigFloat. To get a Math::BigFloat you either need to call the operation manually, make sure each operand already is a Math::BigFloat, or cast to that type via Math::BigFloat->new(): $float = Math::BigFloat->new($mbi2) / $mbi; # = 2.5 Beware of casting the entire expression, as this would cast the result, at which point it is too late: $float = Math::BigFloat->new($mbi2 / $mbi); # = 2 Beware also of the order of more complicated expressions like: $integer = ($mbi2 + $mbi) / $mbf; # int / float => int $integer = $mbi2 / Math::BigFloat->new($mbi); # ditto If in doubt, break the expression into simpler terms, or cast all operands to the desired resulting type. Scalar values are a bit different, since: $float = 2 + $mbf; $float = $mbf + 2; both result in the proper type due to the way the overloaded math works. This section also applies to other overloaded math packages, like Math::String. One solution to you problem might be autoupgrading|upgrading. See the pragmas L, L and L for an easy way to do this. =back =head1 BUGS Please report any bugs or feature requests to C, or through the web interface at L (requires login). We will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 SUPPORT You can find documentation for this module with the perldoc command. perldoc Math::BigInt You can also look for information at: =over 4 =item * RT: CPAN's request tracker L =item * AnnoCPAN: Annotated CPAN documentation L =item * CPAN Ratings L =item * Search CPAN L =item * CPAN Testers Matrix L =item * The Bignum mailing list =over 4 =item * Post to mailing list C =item * View mailing list L =item * Subscribe/Unsubscribe L =back =back =head1 LICENSE This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself. =head1 SEE ALSO L and L as well as the backends L, L, and L. The pragmas L, L and L also might be of interest because they solve the autoupgrading/downgrading issue, at least partly. =head1 AUTHORS =over 4 =item * Mark Biggar, overloaded interface by Ilya Zakharevich, 1996-2001. =item * Completely rewritten by Tels L, 2001-2008. =item * Florian Ragwitz Eflora@cpan.orgE, 2010. =item * Peter John Acklam Epjacklam@online.noE, 2011-. =back Many people contributed in one or more ways to the final beast, see the file CREDITS for an (incomplete) list. If you miss your name, please drop me a mail. Thank you! =cut BigInt/Lib.pm000064400000156736152530054110007002 0ustar00package Math::BigInt::Lib; use 5.006001; use strict; use warnings; our $VERSION = '1.999811'; use Carp; use overload # overload key: with_assign '+' => sub { my $class = ref $_[0]; my $x = $class -> _copy($_[0]); my $y = ref($_[1]) ? $_[1] : $class -> _new($_[1]); return $class -> _add($x, $y); }, '-' => sub { my $class = ref $_[0]; my ($x, $y); if ($_[2]) { # if swapped $y = $_[0]; $x = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } else { $x = $class -> _copy($_[0]); $y = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } return $class -> _sub($x, $y); }, '*' => sub { my $class = ref $_[0]; my $x = $class -> _copy($_[0]); my $y = ref($_[1]) ? $_[1] : $class -> _new($_[1]); return $class -> _mul($x, $y); }, '/' => sub { my $class = ref $_[0]; my ($x, $y); if ($_[2]) { # if swapped $y = $_[0]; $x = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } else { $x = $class -> _copy($_[0]); $y = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } return $class -> _div($x, $y); }, '%' => sub { my $class = ref $_[0]; my ($x, $y); if ($_[2]) { # if swapped $y = $_[0]; $x = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } else { $x = $class -> _copy($_[0]); $y = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } return $class -> _mod($x, $y); }, '**' => sub { my $class = ref $_[0]; my ($x, $y); if ($_[2]) { # if swapped $y = $_[0]; $x = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } else { $x = $class -> _copy($_[0]); $y = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } return $class -> _pow($x, $y); }, '<<' => sub { my $class = ref $_[0]; my ($x, $y); if ($_[2]) { # if swapped $y = $class -> _num($_[0]); $x = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } else { $x = $_[0]; $y = ref($_[1]) ? $class -> _num($_[1]) : $_[1]; } return $class -> _blsft($x, $y); }, '>>' => sub { my $class = ref $_[0]; my ($x, $y); if ($_[2]) { # if swapped $y = $_[0]; $x = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } else { $x = $class -> _copy($_[0]); $y = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } return $class -> _brsft($x, $y); }, # overload key: num_comparison '<' => sub { my $class = ref $_[0]; my ($x, $y); if ($_[2]) { # if swapped $y = $_[0]; $x = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } else { $x = $class -> _copy($_[0]); $y = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } return $class -> _acmp($x, $y) < 0; }, '<=' => sub { my $class = ref $_[0]; my ($x, $y); if ($_[2]) { # if swapped $y = $_[0]; $x = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } else { $x = $class -> _copy($_[0]); $y = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } return $class -> _acmp($x, $y) <= 0; }, '>' => sub { my $class = ref $_[0]; my ($x, $y); if ($_[2]) { # if swapped $y = $_[0]; $x = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } else { $x = $class -> _copy($_[0]); $y = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } return $class -> _acmp($x, $y) > 0; }, '>=' => sub { my $class = ref $_[0]; my ($x, $y); if ($_[2]) { # if swapped $y = $_[0]; $x = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } else { $x = $class -> _copy($_[0]); $y = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } return $class -> _acmp($x, $y) >= 0; }, '==' => sub { my $class = ref $_[0]; my $x = $class -> _copy($_[0]); my $y = ref($_[1]) ? $_[1] : $class -> _new($_[1]); return $class -> _acmp($x, $y) == 0; }, '!=' => sub { my $class = ref $_[0]; my $x = $class -> _copy($_[0]); my $y = ref($_[1]) ? $_[1] : $class -> _new($_[1]); return $class -> _acmp($x, $y) != 0; }, # overload key: 3way_comparison '<=>' => sub { my $class = ref $_[0]; my ($x, $y); if ($_[2]) { # if swapped $y = $_[0]; $x = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } else { $x = $class -> _copy($_[0]); $y = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } return $class -> _acmp($x, $y); }, # overload key: binary '&' => sub { my $class = ref $_[0]; my ($x, $y); if ($_[2]) { # if swapped $y = $_[0]; $x = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } else { $x = $class -> _copy($_[0]); $y = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } return $class -> _and($x, $y); }, '|' => sub { my $class = ref $_[0]; my ($x, $y); if ($_[2]) { # if swapped $y = $_[0]; $x = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } else { $x = $class -> _copy($_[0]); $y = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } return $class -> _or($x, $y); }, '^' => sub { my $class = ref $_[0]; my ($x, $y); if ($_[2]) { # if swapped $y = $_[0]; $x = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } else { $x = $class -> _copy($_[0]); $y = ref($_[1]) ? $_[1] : $class -> _new($_[1]); } return $class -> _xor($x, $y); }, # overload key: func 'abs' => sub { $_[0] }, 'sqrt' => sub { my $class = ref $_[0]; return $class -> _sqrt($class -> _copy($_[0])); }, 'int' => sub { $_[0] }, # overload key: conversion 'bool' => sub { ref($_[0]) -> _is_zero($_[0]) ? '' : 1; }, '""' => sub { ref($_[0]) -> _str($_[0]); }, '0+' => sub { ref($_[0]) -> _num($_[0]); }, '=' => sub { ref($_[0]) -> _copy($_[0]); }, ; # Do we need api_version() at all, now that we have a virtual parent class that # will provide any missing methods? Fixme! sub api_version () { croak "@{[(caller 0)[3]]} method not implemented"; } sub _new { croak "@{[(caller 0)[3]]} method not implemented"; } sub _zero { my $class = shift; return $class -> _new("0"); } sub _one { my $class = shift; return $class -> _new("1"); } sub _two { my $class = shift; return $class -> _new("2"); } sub _ten { my $class = shift; return $class -> _new("10"); } sub _1ex { my ($class, $exp) = @_; $exp = $class -> _num($exp) if ref($exp); return $class -> _new("1" . ("0" x $exp)); } sub _copy { my ($class, $x) = @_; return $class -> _new($class -> _str($x)); } # catch and throw away sub import { } ############################################################################## # convert back to string and number sub _str { # Convert number from internal base 1eN format to string format. Internal # format is always normalized, i.e., no leading zeros. croak "@{[(caller 0)[3]]} method not implemented"; } sub _num { my ($class, $x) = @_; 0 + $class -> _str($x); } ############################################################################## # actual math code sub _add { croak "@{[(caller 0)[3]]} method not implemented"; } sub _sub { croak "@{[(caller 0)[3]]} method not implemented"; } sub _mul { my ($class, $x, $y) = @_; my $sum = $class -> _zero(); my $i = $class -> _zero(); while ($class -> _acmp($i, $y) < 0) { $sum = $class -> _add($sum, $x); $i = $class -> _inc($i); } return $sum; } sub _div { my ($class, $x, $y) = @_; croak "@{[(caller 0)[3]]} requires non-zero divisor" if $class -> _is_zero($y); my $r = $class -> _copy($x); my $q = $class -> _zero(); while ($class -> _acmp($r, $y) >= 0) { $q = $class -> _inc($q); $r = $class -> _sub($r, $y); } return $q, $r if wantarray; return $q; } sub _inc { my ($class, $x) = @_; $class -> _add($x, $class -> _one()); } sub _dec { my ($class, $x) = @_; $class -> _sub($x, $class -> _one()); } ############################################################################## # testing sub _acmp { # Compare two (absolute) values. Return -1, 0, or 1. my ($class, $x, $y) = @_; my $xstr = $class -> _str($x); my $ystr = $class -> _str($y); length($xstr) <=> length($ystr) || $xstr cmp $ystr; } sub _len { my ($class, $x) = @_; CORE::length($class -> _str($x)); } sub _alen { my ($class, $x) = @_; $class -> _len($x); } sub _digit { my ($class, $x, $n) = @_; substr($class ->_str($x), -($n+1), 1); } sub _zeros { my ($class, $x) = @_; my $str = $class -> _str($x); $str =~ /[^0](0*)\z/ ? CORE::length($1) : 0; } ############################################################################## # _is_* routines sub _is_zero { # return true if arg is zero my ($class, $x) = @_; $class -> _str($x) == 0; } sub _is_even { # return true if arg is even my ($class, $x) = @_; substr($class -> _str($x), -1, 1) % 2 == 0; } sub _is_odd { # return true if arg is odd my ($class, $x) = @_; substr($class -> _str($x), -1, 1) % 2 != 0; } sub _is_one { # return true if arg is one my ($class, $x) = @_; $class -> _str($x) == 1; } sub _is_two { # return true if arg is two my ($class, $x) = @_; $class -> _str($x) == 2; } sub _is_ten { # return true if arg is ten my ($class, $x) = @_; $class -> _str($x) == 10; } ############################################################################### # check routine to test internal state for corruptions sub _check { # used by the test suite my ($class, $x) = @_; return "Input is undefined" unless defined $x; return "$x is not a reference" unless ref($x); return 0; } ############################################################################### sub _mod { # modulus my ($class, $x, $y) = @_; croak "@{[(caller 0)[3]]} requires non-zero second operand" if $class -> _is_zero($y); if ($class -> can('_div')) { $x = $class -> _copy($x); my ($q, $r) = $class -> _div($x, $y); return $r; } else { my $r = $class -> _copy($x); while ($class -> _acmp($r, $y) >= 0) { $r = $class -> _sub($r, $y); } return $r; } } ############################################################################## # shifts sub _rsft { my ($class, $x, $n, $b) = @_; $b = $class -> _new($b) unless ref $b; return scalar $class -> _div($x, $class -> _pow($class -> _copy($b), $n)); } sub _lsft { my ($class, $x, $n, $b) = @_; $b = $class -> _new($b) unless ref $b; return $class -> _mul($x, $class -> _pow($class -> _copy($b), $n)); } sub _pow { # power of $x to $y my ($class, $x, $y) = @_; if ($class -> _is_zero($y)) { return $class -> _one(); # y == 0 => x => 1 } if (($class -> _is_one($x)) || # x == 1 ($class -> _is_one($y))) # or y == 1 { return $x; } if ($class -> _is_zero($x)) { return $class -> _zero(); # 0 ** y => 0 (if not y <= 0) } my $pow2 = $class -> _one(); my $y_bin = $class -> _as_bin($y); $y_bin =~ s/^0b//; my $len = length($y_bin); while (--$len > 0) { $pow2 = $class -> _mul($pow2, $x) if substr($y_bin, $len, 1) eq '1'; $x = $class -> _mul($x, $x); } $x = $class -> _mul($x, $pow2); return $x; } sub _nok { # Return binomial coefficient (n over k). my ($class, $n, $k) = @_; # If k > n/2, or, equivalently, 2*k > n, compute nok(n, k) as # nok(n, n-k), to minimize the number if iterations in the loop. { my $twok = $class -> _mul($class -> _two(), $class -> _copy($k)); if ($class -> _acmp($twok, $n) > 0) { $k = $class -> _sub($class -> _copy($n), $k); } } # Example: # # / 7 \ 7! 1*2*3*4 * 5*6*7 5 * 6 * 7 # | | = --------- = --------------- = --------- = ((5 * 6) / 2 * 7) / 3 # \ 3 / (7-3)! 3! 1*2*3*4 * 1*2*3 1 * 2 * 3 # # Equivalently, _nok(11, 5) is computed as # # (((((((7 * 8) / 2) * 9) / 3) * 10) / 4) * 11) / 5 if ($class -> _is_zero($k)) { return $class -> _one(); } # Make a copy of the original n, in case the subclass modifies n in-place. my $n_orig = $class -> _copy($n); # n = 5, f = 6, d = 2 (cf. example above) $n = $class -> _sub($n, $k); $n = $class -> _inc($n); my $f = $class -> _copy($n); $f = $class -> _inc($f); my $d = $class -> _two(); # while f <= n (the original n, that is) ... while ($class -> _acmp($f, $n_orig) <= 0) { $n = $class -> _mul($n, $f); $n = $class -> _div($n, $d); $f = $class -> _inc($f); $d = $class -> _inc($d); } return $n; } sub _fac { # factorial my ($class, $x) = @_; my $two = $class -> _two(); if ($class -> _acmp($x, $two) < 0) { return $class -> _one(); } my $i = $class -> _copy($x); while ($class -> _acmp($i, $two) > 0) { $i = $class -> _dec($i); $x = $class -> _mul($x, $i); } return $x; } sub _dfac { # double factorial my ($class, $x) = @_; my $two = $class -> _two(); if ($class -> _acmp($x, $two) < 0) { return $class -> _one(); } my $i = $class -> _copy($x); while ($class -> _acmp($i, $two) > 0) { $i = $class -> _sub($i, $two); $x = $class -> _mul($x, $i); } return $x; } sub _log_int { # calculate integer log of $x to base $base # calculate integer log of $x to base $base # ref to array, ref to array - return ref to array my ($class, $x, $base) = @_; # X == 0 => NaN return if $class -> _is_zero($x); $base = $class -> _new(2) unless defined($base); $base = $class -> _new($base) unless ref($base); # BASE 0 or 1 => NaN return if $class -> _is_zero($base) || $class -> _is_one($base); # X == 1 => 0 (is exact) if ($class -> _is_one($x)) { return $class -> _zero(), 1; } my $cmp = $class -> _acmp($x, $base); # X == BASE => 1 (is exact) if ($cmp == 0) { return $class -> _one(), 1; } # 1 < X < BASE => 0 (is truncated) if ($cmp < 0) { return $class -> _zero(), 0; } my $y; # log(x) / log(b) = log(xm * 10^xe) / log(bm * 10^be) # = (log(xm) + xe*(log(10))) / (log(bm) + be*log(10)) { my $x_str = $class -> _str($x); my $b_str = $class -> _str($base); my $xm = "." . $x_str; my $bm = "." . $b_str; my $xe = length($x_str); my $be = length($b_str); my $log10 = log(10); my $guess = int((log($xm) + $xe * $log10) / (log($bm) + $be * $log10)); $y = $class -> _new($guess); } my $trial = $class -> _pow($class -> _copy($base), $y); my $acmp = $class -> _acmp($trial, $x); # Did we get the exact result? return $y, 1 if $acmp == 0; # Too small? while ($acmp < 0) { $trial = $class -> _mul($trial, $base); $y = $class -> _inc($y); $acmp = $class -> _acmp($trial, $x); } # Too big? while ($acmp > 0) { $trial = $class -> _div($trial, $base); $y = $class -> _dec($y); $acmp = $class -> _acmp($trial, $x); } return $y, 1 if $acmp == 0; # result is exact return $y, 0; # result is too small } sub _sqrt { # square-root of $y in place my ($class, $y) = @_; return $y if $class -> _is_zero($y); my $y_str = $class -> _str($y); my $y_len = length($y_str); # Compute the guess $x. my $xm; my $xe; if ($y_len % 2 == 0) { $xm = sqrt("." . $y_str); $xe = $y_len / 2; $xm = sprintf "%.0f", int($xm * 1e15); $xe -= 15; } else { $xm = sqrt(".0" . $y_str); $xe = ($y_len + 1) / 2; $xm = sprintf "%.0f", int($xm * 1e16); $xe -= 16; } my $x; if ($xe < 0) { $x = substr $xm, 0, length($xm) + $xe; } else { $x = $xm . ("0" x $xe); } $x = $class -> _new($x); # Newton's method for computing square root of y # # x(i+1) = x(i) - f(x(i)) / f'(x(i)) # = x(i) - (x(i)^2 - y) / (2 * x(i)) # use if x(i)^2 > y # = y(i) + (y - x(i)^2) / (2 * x(i)) # use if x(i)^2 < y # Determine if x, our guess, is too small, correct, or too large. my $xsq = $class -> _mul($class -> _copy($x), $x); # x(i)^2 my $acmp = $class -> _acmp($xsq, $y); # x(i)^2 <=> y # Only assign a value to this variable if we will be using it. my $two; $two = $class -> _two() if $acmp != 0; # If x is too small, do one iteration of Newton's method. Since the # function f(x) = x^2 - y is concave and monotonically increasing, the next # guess for x will either be correct or too large. if ($acmp < 0) { # x(i+1) = x(i) + (y - x(i)^2) / (2 * x(i)) my $numer = $class -> _sub($class -> _copy($y), $xsq); # y - x(i)^2 my $denom = $class -> _mul($class -> _copy($two), $x); # 2 * x(i) my $delta = $class -> _div($numer, $denom); unless ($class -> _is_zero($delta)) { $x = $class -> _add($x, $delta); $xsq = $class -> _mul($class -> _copy($x), $x); # x(i)^2 $acmp = $class -> _acmp($xsq, $y); # x(i)^2 <=> y } } # If our guess for x is too large, apply Newton's method repeatedly until # we either have got the correct value, or the delta is zero. while ($acmp > 0) { # x(i+1) = x(i) - (x(i)^2 - y) / (2 * x(i)) my $numer = $class -> _sub($xsq, $y); # x(i)^2 - y my $denom = $class -> _mul($class -> _copy($two), $x); # 2 * x(i) my $delta = $class -> _div($numer, $denom); last if $class -> _is_zero($delta); $x = $class -> _sub($x, $delta); $xsq = $class -> _mul($class -> _copy($x), $x); # x(i)^2 $acmp = $class -> _acmp($xsq, $y); # x(i)^2 <=> y } # When the delta is zero, our value for x might still be too large. We # require that the outout is either exact or too small (i.e., rounded down # to the nearest integer), so do a final check. while ($acmp > 0) { $x = $class -> _dec($x); $xsq = $class -> _mul($class -> _copy($x), $x); # x(i)^2 $acmp = $class -> _acmp($xsq, $y); # x(i)^2 <=> y } return $x; } sub _root { my ($class, $y, $n) = @_; return $y if $class -> _is_zero($y) || $class -> _is_one($y) || $class -> _is_one($n); # If y <= n, the result is always (truncated to) 1. return $class -> _one() if $class -> _acmp($y, $n) <= 0; # Compute the initial guess x of y^(1/n). When n is large, Newton's method # converges slowly if the "guess" (initial value) is poor, so we need a # good guess. It the guess is too small, the next guess will be too large, # and from then on all guesses are too large. my $DEBUG = 0; # Split y into mantissa and exponent in base 10, so that # # y = xm * 10^xe, where 0 < xm < 1 and xe is an integer my $y_str = $class -> _str($y); my $ym = "." . $y_str; my $ye = length($y_str); # From this compute the approximate base 10 logarithm of y # # log_10(y) = log_10(ym) + log_10(ye^10) # = log(ym)/log(10) + ye my $log10y = log($ym) / log(10) + $ye; # And from this compute the approximate base 10 logarithm of x, where # x = y^(1/n) # # log_10(x) = log_10(y)/n my $log10x = $log10y / $class -> _num($n); # From this compute xm and xe, the mantissa and exponent (in base 10) of x, # where 1 < xm <= 10 and xe is an integer. my $xe = int $log10x; my $xm = 10 ** ($log10x - $xe); # Scale the mantissa and exponent to increase the integer part of ym, which # gives us better accuracy. if ($DEBUG) { print "\n"; print "y_str = $y_str\n"; print "ym = $ym\n"; print "ye = $ye\n"; print "log10y = $log10y\n"; print "log10x = $log10x\n"; print "xm = $xm\n"; print "xe = $xe\n"; } my $d = $xe < 15 ? $xe : 15; $xm *= 10 ** $d; $xe -= $d; if ($DEBUG) { print "\n"; print "xm = $xm\n"; print "xe = $xe\n"; } # If the mantissa is not an integer, round up to nearest integer, and then # convert the number to a string. It is important to always round up due to # how Newton's method behaves in this case. If the initial guess is too # small, the next guess will be too large, after which every succeeding # guess converges the correct value from above. Now, if the initial guess # is too small and n is large, the next guess will be much too large and # require a large number of iterations to get close to the solution. # Because of this, we are likely to find the solution faster if we make # sure the initial guess is not too small. my $xm_int = int($xm); my $x_str = sprintf '%.0f', $xm > $xm_int ? $xm_int + 1 : $xm_int; $x_str .= "0" x $xe; my $x = $class -> _new($x_str); if ($DEBUG) { print "xm = $xm\n"; print "xe = $xe\n"; print "\n"; print "x_str = $x_str (initial guess)\n"; print "\n"; } # Use Newton's method for computing n'th root of y. # # x(i+1) = x(i) - f(x(i)) / f'(x(i)) # = x(i) - (x(i)^n - y) / (n * x(i)^(n-1)) # use if x(i)^n > y # = x(i) + (y - x(i)^n) / (n * x(i)^(n-1)) # use if x(i)^n < y # Determine if x, our guess, is too small, correct, or too large. Rather # than computing x(i)^n and x(i)^(n-1) directly, compute x(i)^(n-1) and # then the same value multiplied by x. my $nm1 = $class -> _dec($class -> _copy($n)); # n-1 my $xpownm1 = $class -> _pow($class -> _copy($x), $nm1); # x(i)^(n-1) my $xpown = $class -> _mul($class -> _copy($xpownm1), $x); # x(i)^n my $acmp = $class -> _acmp($xpown, $y); # x(i)^n <=> y if ($DEBUG) { print "\n"; print "x = ", $class -> _str($x), "\n"; print "x^n = ", $class -> _str($xpown), "\n"; print "y = ", $class -> _str($y), "\n"; print "acmp = $acmp\n"; } # If x is too small, do one iteration of Newton's method. Since the # function f(x) = x^n - y is concave and monotonically increasing, the next # guess for x will either be correct or too large. if ($acmp < 0) { # x(i+1) = x(i) + (y - x(i)^n) / (n * x(i)^(n-1)) my $numer = $class -> _sub($class -> _copy($y), $xpown); # y - x(i)^n my $denom = $class -> _mul($class -> _copy($n), $xpownm1); # n * x(i)^(n-1) my $delta = $class -> _div($numer, $denom); if ($DEBUG) { print "\n"; print "numer = ", $class -> _str($numer), "\n"; print "denom = ", $class -> _str($denom), "\n"; print "delta = ", $class -> _str($delta), "\n"; } unless ($class -> _is_zero($delta)) { $x = $class -> _add($x, $delta); $xpownm1 = $class -> _pow($class -> _copy($x), $nm1); # x(i)^(n-1) $xpown = $class -> _mul($class -> _copy($xpownm1), $x); # x(i)^n $acmp = $class -> _acmp($xpown, $y); # x(i)^n <=> y if ($DEBUG) { print "\n"; print "x = ", $class -> _str($x), "\n"; print "x^n = ", $class -> _str($xpown), "\n"; print "y = ", $class -> _str($y), "\n"; print "acmp = $acmp\n"; } } } # If our guess for x is too large, apply Newton's method repeatedly until # we either have got the correct value, or the delta is zero. while ($acmp > 0) { # x(i+1) = x(i) - (x(i)^n - y) / (n * x(i)^(n-1)) my $numer = $class -> _sub($class -> _copy($xpown), $y); # x(i)^n - y my $denom = $class -> _mul($class -> _copy($n), $xpownm1); # n * x(i)^(n-1) if ($DEBUG) { print "numer = ", $class -> _str($numer), "\n"; print "denom = ", $class -> _str($denom), "\n"; } my $delta = $class -> _div($numer, $denom); if ($DEBUG) { print "delta = ", $class -> _str($delta), "\n"; } last if $class -> _is_zero($delta); $x = $class -> _sub($x, $delta); $xpownm1 = $class -> _pow($class -> _copy($x), $nm1); # x(i)^(n-1) $xpown = $class -> _mul($class -> _copy($xpownm1), $x); # x(i)^n $acmp = $class -> _acmp($xpown, $y); # x(i)^n <=> y if ($DEBUG) { print "\n"; print "x = ", $class -> _str($x), "\n"; print "x^n = ", $class -> _str($xpown), "\n"; print "y = ", $class -> _str($y), "\n"; print "acmp = $acmp\n"; } } # When the delta is zero, our value for x might still be too large. We # require that the outout is either exact or too small (i.e., rounded down # to the nearest integer), so do a final check. while ($acmp > 0) { $x = $class -> _dec($x); $xpown = $class -> _pow($class -> _copy($x), $n); # x(i)^n $acmp = $class -> _acmp($xpown, $y); # x(i)^n <=> y } return $x; } ############################################################################## # binary stuff sub _and { my ($class, $x, $y) = @_; return $x if $class -> _acmp($x, $y) == 0; my $m = $class -> _one(); my $mask = $class -> _new("32768"); my ($xr, $yr); # remainders after division my $xc = $class -> _copy($x); my $yc = $class -> _copy($y); my $z = $class -> _zero(); until ($class -> _is_zero($xc) || $class -> _is_zero($yc)) { ($xc, $xr) = $class -> _div($xc, $mask); ($yc, $yr) = $class -> _div($yc, $mask); my $bits = $class -> _new($class -> _num($xr) & $class -> _num($yr)); $z = $class -> _add($z, $class -> _mul($bits, $m)); $m = $class -> _mul($m, $mask); } return $z; } sub _xor { my ($class, $x, $y) = @_; return $class -> _zero() if $class -> _acmp($x, $y) == 0; my $m = $class -> _one(); my $mask = $class -> _new("32768"); my ($xr, $yr); # remainders after division my $xc = $class -> _copy($x); my $yc = $class -> _copy($y); my $z = $class -> _zero(); until ($class -> _is_zero($xc) || $class -> _is_zero($yc)) { ($xc, $xr) = $class -> _div($xc, $mask); ($yc, $yr) = $class -> _div($yc, $mask); my $bits = $class -> _new($class -> _num($xr) ^ $class -> _num($yr)); $z = $class -> _add($z, $class -> _mul($bits, $m)); $m = $class -> _mul($m, $mask); } # The loop above stops when the smallest of the two numbers is exhausted. # The remainder of the longer one will survive bit-by-bit, so we simple # multiply-add it in. $z = $class -> _add($z, $class -> _mul($xc, $m)) unless $class -> _is_zero($xc); $z = $class -> _add($z, $class -> _mul($yc, $m)) unless $class -> _is_zero($yc); return $z; } sub _or { my ($class, $x, $y) = @_; return $x if $class -> _acmp($x, $y) == 0; # shortcut (see _and) my $m = $class -> _one(); my $mask = $class -> _new("32768"); my ($xr, $yr); # remainders after division my $xc = $class -> _copy($x); my $yc = $class -> _copy($y); my $z = $class -> _zero(); until ($class -> _is_zero($xc) || $class -> _is_zero($yc)) { ($xc, $xr) = $class -> _div($xc, $mask); ($yc, $yr) = $class -> _div($yc, $mask); my $bits = $class -> _new($class -> _num($xr) | $class -> _num($yr)); $z = $class -> _add($z, $class -> _mul($bits, $m)); $m = $class -> _mul($m, $mask); } # The loop above stops when the smallest of the two numbers is exhausted. # The remainder of the longer one will survive bit-by-bit, so we simple # multiply-add it in. $z = $class -> _add($z, $class -> _mul($xc, $m)) unless $class -> _is_zero($xc); $z = $class -> _add($z, $class -> _mul($yc, $m)) unless $class -> _is_zero($yc); return $z; } sub _to_bin { # convert the number to a string of binary digits without prefix my ($class, $x) = @_; my $str = ''; my $tmp = $class -> _copy($x); my $chunk = $class -> _new("16777216"); # 2^24 = 24 binary digits my $rem; until ($class -> _acmp($tmp, $chunk) < 0) { ($tmp, $rem) = $class -> _div($tmp, $chunk); $str = sprintf("%024b", $class -> _num($rem)) . $str; } unless ($class -> _is_zero($tmp)) { $str = sprintf("%b", $class -> _num($tmp)) . $str; } return length($str) ? $str : '0'; } sub _to_oct { # convert the number to a string of octal digits without prefix my ($class, $x) = @_; my $str = ''; my $tmp = $class -> _copy($x); my $chunk = $class -> _new("16777216"); # 2^24 = 8 octal digits my $rem; until ($class -> _acmp($tmp, $chunk) < 0) { ($tmp, $rem) = $class -> _div($tmp, $chunk); $str = sprintf("%08o", $class -> _num($rem)) . $str; } unless ($class -> _is_zero($tmp)) { $str = sprintf("%o", $class -> _num($tmp)) . $str; } return length($str) ? $str : '0'; } sub _to_hex { # convert the number to a string of hexadecimal digits without prefix my ($class, $x) = @_; my $str = ''; my $tmp = $class -> _copy($x); my $chunk = $class -> _new("16777216"); # 2^24 = 6 hexadecimal digits my $rem; until ($class -> _acmp($tmp, $chunk) < 0) { ($tmp, $rem) = $class -> _div($tmp, $chunk); $str = sprintf("%06x", $class -> _num($rem)) . $str; } unless ($class -> _is_zero($tmp)) { $str = sprintf("%x", $class -> _num($tmp)) . $str; } return length($str) ? $str : '0'; } sub _as_bin { # convert the number to a string of binary digits with prefix my ($class, $x) = @_; return '0b' . $class -> _to_bin($x); } sub _as_oct { # convert the number to a string of octal digits with prefix my ($class, $x) = @_; return '0' . $class -> _to_oct($x); # yes, 0 becomes "00" } sub _as_hex { # convert the number to a string of hexadecimal digits with prefix my ($class, $x) = @_; return '0x' . $class -> _to_hex($x); } sub _to_bytes { # convert the number to a string of bytes my ($class, $x) = @_; my $str = ''; my $tmp = $class -> _copy($x); my $chunk = $class -> _new("65536"); my $rem; until ($class -> _is_zero($tmp)) { ($tmp, $rem) = $class -> _div($tmp, $chunk); $str = pack('n', $class -> _num($rem)) . $str; } $str =~ s/^\0+//; return length($str) ? $str : "\x00"; } *_as_bytes = \&_to_bytes; sub _from_hex { # Convert a string of hexadecimal digits to a number. my ($class, $hex) = @_; $hex =~ s/^0[xX]//; # Find the largest number of hexadecimal digits that we can safely use with # 32 bit integers. There are 4 bits pr hexadecimal digit, and we use only # 31 bits to play safe. This gives us int(31 / 4) = 7. my $len = length $hex; my $rem = 1 + ($len - 1) % 7; # Do the first chunk. my $ret = $class -> _new(int hex substr $hex, 0, $rem); return $ret if $rem == $len; # Do the remaining chunks, if any. my $shift = $class -> _new(1 << (4 * 7)); for (my $offset = $rem ; $offset < $len ; $offset += 7) { my $part = int hex substr $hex, $offset, 7; $ret = $class -> _mul($ret, $shift); $ret = $class -> _add($ret, $class -> _new($part)); } return $ret; } sub _from_oct { # Convert a string of octal digits to a number. my ($class, $oct) = @_; # Find the largest number of octal digits that we can safely use with 32 # bit integers. There are 3 bits pr octal digit, and we use only 31 bits to # play safe. This gives us int(31 / 3) = 10. my $len = length $oct; my $rem = 1 + ($len - 1) % 10; # Do the first chunk. my $ret = $class -> _new(int oct substr $oct, 0, $rem); return $ret if $rem == $len; # Do the remaining chunks, if any. my $shift = $class -> _new(1 << (3 * 10)); for (my $offset = $rem ; $offset < $len ; $offset += 10) { my $part = int oct substr $oct, $offset, 10; $ret = $class -> _mul($ret, $shift); $ret = $class -> _add($ret, $class -> _new($part)); } return $ret; } sub _from_bin { # Convert a string of binary digits to a number. my ($class, $bin) = @_; $bin =~ s/^0[bB]//; # The largest number of binary digits that we can safely use with 32 bit # integers is 31. We use only 31 bits to play safe. my $len = length $bin; my $rem = 1 + ($len - 1) % 31; # Do the first chunk. my $ret = $class -> _new(int oct '0b' . substr $bin, 0, $rem); return $ret if $rem == $len; # Do the remaining chunks, if any. my $shift = $class -> _new(1 << 31); for (my $offset = $rem ; $offset < $len ; $offset += 31) { my $part = int oct '0b' . substr $bin, $offset, 31; $ret = $class -> _mul($ret, $shift); $ret = $class -> _add($ret, $class -> _new($part)); } return $ret; } sub _from_bytes { # convert string of bytes to a number my ($class, $str) = @_; my $x = $class -> _zero(); my $base = $class -> _new("256"); my $n = length($str); for (my $i = 0 ; $i < $n ; ++$i) { $x = $class -> _mul($x, $base); my $byteval = $class -> _new(unpack 'C', substr($str, $i, 1)); $x = $class -> _add($x, $byteval); } return $x; } ############################################################################## # special modulus functions sub _modinv { # modular multiplicative inverse my ($class, $x, $y) = @_; # modulo zero if ($class -> _is_zero($y)) { return (undef, undef); } # modulo one if ($class -> _is_one($y)) { return ($class -> _zero(), '+'); } my $u = $class -> _zero(); my $v = $class -> _one(); my $a = $class -> _copy($y); my $b = $class -> _copy($x); # Euclid's Algorithm for bgcd(). my $q; my $sign = 1; { ($a, $q, $b) = ($b, $class -> _div($a, $b)); last if $class -> _is_zero($b); my $vq = $class -> _mul($class -> _copy($v), $q); my $t = $class -> _add($vq, $u); $u = $v; $v = $t; $sign = -$sign; redo; } # if the gcd is not 1, there exists no modular multiplicative inverse return (undef, undef) unless $class -> _is_one($a); ($v, $sign == 1 ? '+' : '-'); } sub _modpow { # modulus of power ($x ** $y) % $z my ($class, $num, $exp, $mod) = @_; # a^b (mod 1) = 0 for all a and b if ($class -> _is_one($mod)) { return $class -> _zero(); } # 0^a (mod m) = 0 if m != 0, a != 0 # 0^0 (mod m) = 1 if m != 0 if ($class -> _is_zero($num)) { return $class -> _is_zero($exp) ? $class -> _one() : $class -> _zero(); } # $num = $class -> _mod($num, $mod); # this does not make it faster my $acc = $class -> _copy($num); my $t = $class -> _one(); my $expbin = $class -> _as_bin($exp); $expbin =~ s/^0b//; my $len = length($expbin); while (--$len >= 0) { if (substr($expbin, $len, 1) eq '1') { $t = $class -> _mul($t, $acc); $t = $class -> _mod($t, $mod); } $acc = $class -> _mul($acc, $acc); $acc = $class -> _mod($acc, $mod); } return $t; } sub _gcd { # Greatest common divisor. my ($class, $x, $y) = @_; # gcd(0, 0) = 0 # gcd(0, a) = a, if a != 0 if ($class -> _acmp($x, $y) == 0) { return $class -> _copy($x); } if ($class -> _is_zero($x)) { if ($class -> _is_zero($y)) { return $class -> _zero(); } else { return $class -> _copy($y); } } else { if ($class -> _is_zero($y)) { return $class -> _copy($x); } else { # Until $y is zero ... $x = $class -> _copy($x); until ($class -> _is_zero($y)) { # Compute remainder. $x = $class -> _mod($x, $y); # Swap $x and $y. my $tmp = $x; $x = $class -> _copy($y); $y = $tmp; } return $x; } } } sub _lcm { # Least common multiple. my ($class, $x, $y) = @_; # lcm(0, x) = 0 for all x return $class -> _zero() if ($class -> _is_zero($x) || $class -> _is_zero($y)); my $gcd = $class -> _gcd($class -> _copy($x), $y); $x = $class -> _div($x, $gcd); $x = $class -> _mul($x, $y); return $x; } sub _lucas { my ($class, $n) = @_; $n = $class -> _num($n) if ref $n; # In list context, use lucas(n) = lucas(n-1) + lucas(n-2) if (wantarray) { my @y; push @y, $class -> _two(); return @y if $n == 0; push @y, $class -> _one(); return @y if $n == 1; for (my $i = 2 ; $i <= $n ; ++ $i) { $y[$i] = $class -> _add($class -> _copy($y[$i - 1]), $y[$i - 2]); } return @y; } require Scalar::Util; # In scalar context use that lucas(n) = fib(n-1) + fib(n+1). # # Remember that _fib() behaves differently in scalar context and list # context, so we must add scalar() to get the desired behaviour. return $class -> _two() if $n == 0; return $class -> _add(scalar $class -> _fib($n - 1), scalar $class -> _fib($n + 1)); } sub _fib { my ($class, $n) = @_; $n = $class -> _num($n) if ref $n; # In list context, use fib(n) = fib(n-1) + fib(n-2) if (wantarray) { my @y; push @y, $class -> _zero(); return @y if $n == 0; push @y, $class -> _one(); return @y if $n == 1; for (my $i = 2 ; $i <= $n ; ++ $i) { $y[$i] = $class -> _add($class -> _copy($y[$i - 1]), $y[$i - 2]); } return @y; } # In scalar context use a fast algorithm that is much faster than the # recursive algorith used in list context. my $cache = {}; my $two = $class -> _two(); my $fib; $fib = sub { my $n = shift; return $class -> _zero() if $n <= 0; return $class -> _one() if $n <= 2; return $cache -> {$n} if exists $cache -> {$n}; my $k = int($n / 2); my $a = $fib -> ($k + 1); my $b = $fib -> ($k); my $y; if ($n % 2 == 1) { # a*a + b*b $y = $class -> _add($class -> _mul($class -> _copy($a), $a), $class -> _mul($class -> _copy($b), $b)); } else { # (2*a - b)*b $y = $class -> _mul($class -> _sub($class -> _mul( $class -> _copy($two), $a), $b), $b); } $cache -> {$n} = $y; return $y; }; return $fib -> ($n); } ############################################################################## ############################################################################## 1; __END__ =pod =head1 NAME Math::BigInt::Lib - virtual parent class for Math::BigInt libraries =head1 SYNOPSIS # In the backend library for Math::BigInt et al. package Math::BigInt::MyBackend; use Math::BigInt::lib; our @ISA = qw< Math::BigInt::lib >; sub _new { ... } sub _str { ... } sub _add { ... } str _sub { ... } ... # In your main program. use Math::BigInt lib => 'MyBackend'; =head1 DESCRIPTION This module provides support for big integer calculations. It is not intended to be used directly, but rather as a parent class for backend libraries used by Math::BigInt, Math::BigFloat, Math::BigRat, and related modules. Other backend libraries include Math::BigInt::Calc, Math::BigInt::FastCalc, Math::BigInt::GMP, and Math::BigInt::Pari. In order to allow for multiple big integer libraries, Math::BigInt was rewritten to use a plug-in library for core math routines. Any module which conforms to the API can be used by Math::BigInt by using this in your program: use Math::BigInt lib => 'libname'; 'libname' is either the long name, like 'Math::BigInt::Pari', or only the short version, like 'Pari'. =head2 General Notes A library only needs to deal with unsigned big integers. Testing of input parameter validity is done by the caller, so there is no need to worry about underflow (e.g., in C<_sub()> and C<_dec()>) or about division by zero (e.g., in C<_div()> and C<_mod()>)) or similar cases. Some libraries use methods that don't modify their argument, and some libraries don't even use objects, but rather unblessed references. Because of this, liberary methods are always called as class methods, not instance methods: $x = Class -> method($x, $y); # like this $x = $x -> method($y); # not like this ... $x -> method($y); # ... or like this And with boolean methods $bool = Class -> method($x, $y); # like this $bool = $x -> method($y); # not like this Return values are always objects, strings, Perl scalars, or true/false for comparison routines. =head3 API version =over 4 =item CLASS-Eapi_version() Return API version as a Perl scalar, 1 for Math::BigInt v1.70, 2 for Math::BigInt v1.83. This method is no longer used. Methods that are not implemented by a subclass will be inherited from this class. =back =head3 Constructors The following methods are mandatory: _new(), _str(), _add(), and _sub(). However, computations will be very slow without _mul() and _div(). =over 4 =item CLASS-E_new(STR) Convert a string representing an unsigned decimal number to an object representing the same number. The input is normalized, i.e., it matches C<^(0|[1-9]\d*)$>. =item CLASS-E_zero() Return an object representing the number zero. =item CLASS-E_one() Return an object representing the number one. =item CLASS-E_two() Return an object representing the number two. =item CLASS-E_ten() Return an object representing the number ten. =item CLASS-E_from_bin(STR) Return an object given a string representing a binary number. The input has a '0b' prefix and matches the regular expression C<^0[bB](0|1[01]*)$>. =item CLASS-E_from_oct(STR) Return an object given a string representing an octal number. The input has a '0' prefix and matches the regular expression C<^0[1-7]*$>. =item CLASS-E_from_hex(STR) Return an object given a string representing a hexadecimal number. The input has a '0x' prefix and matches the regular expression C<^0x(0|[1-9a-fA-F][\da-fA-F]*)$>. =item CLASS-E_from_bytes(STR) Returns an object given a byte string representing the number. The byte string is in big endian byte order, so the two-byte input string "\x01\x00" should give an output value representing the number 256. =back =head3 Mathematical functions =over 4 =item CLASS-E_add(OBJ1, OBJ2) Returns the result of adding OBJ2 to OBJ1. =item CLASS-E_mul(OBJ1, OBJ2) Returns the result of multiplying OBJ2 and OBJ1. =item CLASS-E_div(OBJ1, OBJ2) In scalar context, returns the quotient after dividing OBJ1 by OBJ2 and truncating the result to an integer. In list context, return the quotient and the remainder. =item CLASS-E_sub(OBJ1, OBJ2, FLAG) =item CLASS-E_sub(OBJ1, OBJ2) Returns the result of subtracting OBJ2 by OBJ1. If C is false or omitted, OBJ1 might be modified. If C is true, OBJ2 might be modified. =item CLASS-E_dec(OBJ) Returns the result after decrementing OBJ by one. =item CLASS-E_inc(OBJ) Returns the result after incrementing OBJ by one. =item CLASS-E_mod(OBJ1, OBJ2) Returns OBJ1 modulo OBJ2, i.e., the remainder after dividing OBJ1 by OBJ2. =item CLASS-E_sqrt(OBJ) Returns the square root of OBJ, truncated to an integer. =item CLASS-E_root(OBJ, N) Returns the Nth root of OBJ, truncated to an integer. =item CLASS-E_fac(OBJ) Returns the factorial of OBJ, i.e., the product of all positive integers up to and including OBJ. =item CLASS-E_dfac(OBJ) Returns the double factorial of OBJ. If OBJ is an even integer, returns the product of all positive, even integers up to and including OBJ, i.e., 2*4*6*...*OBJ. If OBJ is an odd integer, returns the product of all positive, odd integers, i.e., 1*3*5*...*OBJ. =item CLASS-E_pow(OBJ1, OBJ2) Returns OBJ1 raised to the power of OBJ2. By convention, 0**0 = 1. =item CLASS-E_modinv(OBJ1, OBJ2) Returns the modular multiplicative inverse, i.e., return OBJ3 so that (OBJ3 * OBJ1) % OBJ2 = 1 % OBJ2 The result is returned as two arguments. If the modular multiplicative inverse does not exist, both arguments are undefined. Otherwise, the arguments are a number (object) and its sign ("+" or "-"). The output value, with its sign, must either be a positive value in the range 1,2,...,OBJ2-1 or the same value subtracted OBJ2. For instance, if the input arguments are objects representing the numbers 7 and 5, the method must either return an object representing the number 3 and a "+" sign, since (3*7) % 5 = 1 % 5, or an object representing the number 2 and a "-" sign, since (-2*7) % 5 = 1 % 5. =item CLASS-E_modpow(OBJ1, OBJ2, OBJ3) Returns the modular exponentiation, i.e., (OBJ1 ** OBJ2) % OBJ3. =item CLASS-E_rsft(OBJ, N, B) Returns the result after shifting OBJ N digits to thee right in base B. This is equivalent to performing integer division by B**N and discarding the remainder, except that it might be much faster. For instance, if the object $obj represents the hexadecimal number 0xabcde, then C<_rsft($obj, 2, 16)> returns an object representing the number 0xabc. The "remainer", 0xde, is discarded and not returned. =item CLASS-E_lsft(OBJ, N, B) Returns the result after shifting OBJ N digits to the left in base B. This is equivalent to multiplying by B**N, except that it might be much faster. =item CLASS-E_log_int(OBJ, B) Returns the logarithm of OBJ to base BASE truncted to an integer. This method has two output arguments, the OBJECT and a STATUS. The STATUS is Perl scalar; it is 1 if OBJ is the exact result, 0 if the result was truncted to give OBJ, and undef if it is unknown whether OBJ is the exact result. =item CLASS-E_gcd(OBJ1, OBJ2) Returns the greatest common divisor of OBJ1 and OBJ2. =item CLASS-E_lcm(OBJ1, OBJ2) Return the least common multiple of OBJ1 and OBJ2. =item CLASS-E_fib(OBJ) In scalar context, returns the nth Fibonacci number: _fib(0) returns 0, _fib(1) returns 1, _fib(2) returns 1, _fib(3) returns 2 etc. In list context, returns the Fibonacci numbers from F(0) to F(n): 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... =item CLASS-E_lucas(OBJ) In scalar context, returns the nth Lucas number: _lucas(0) returns 2, _lucas(1) returns 1, _lucas(2) returns 3, etc. In list context, returns the Lucas numbers from L(0) to L(n): 2, 1, 3, 4, 7, 11, 18, 29,47, 76, ... =back =head3 Bitwise operators =over 4 =item CLASS-E_and(OBJ1, OBJ2) Returns bitwise and. =item CLASS-E_or(OBJ1, OBJ2) Return bitwise or. =item CLASS-E_xor(OBJ1, OBJ2) Return bitwise exclusive or. =back =head3 Boolean operators =over 4 =item CLASS-E_is_zero(OBJ) Returns a true value if OBJ is zero, and false value otherwise. =item CLASS-E_is_one(OBJ) Returns a true value if OBJ is one, and false value otherwise. =item CLASS-E_is_two(OBJ) Returns a true value if OBJ is two, and false value otherwise. =item CLASS-E_is_ten(OBJ) Returns a true value if OBJ is ten, and false value otherwise. =item CLASS-E_is_even(OBJ) Return a true value if OBJ is an even integer, and a false value otherwise. =item CLASS-E_is_odd(OBJ) Return a true value if OBJ is an even integer, and a false value otherwise. =item CLASS-E_acmp(OBJ1, OBJ2) Compare OBJ1 and OBJ2 and return -1, 0, or 1, if OBJ1 is numerically less than, equal to, or larger than OBJ2, respectively. =back =head3 String conversion =over 4 =item CLASS-E_str(OBJ) Returns a string representing OBJ in decimal notation. The returned string should have no leading zeros, i.e., it should match C<^(0|[1-9]\d*)$>. =item CLASS-E_to_bin(OBJ) Returns the binary string representation of OBJ. =item CLASS-E_to_oct(OBJ) Returns the octal string representation of the number. =item CLASS-E_to_hex(OBJ) Returns the hexadecimal string representation of the number. =item CLASS-E_to_bytes(OBJ) Returns a byte string representation of OBJ. The byte string is in big endian byte order, so if OBJ represents the number 256, the output should be the two-byte string "\x01\x00". =item CLASS-E_as_bin(OBJ) Like C<_to_bin()> but with a '0b' prefix. =item CLASS-E_as_oct(OBJ) Like C<_to_oct()> but with a '0' prefix. =item CLASS-E_as_hex(OBJ) Like C<_to_hex()> but with a '0x' prefix. =item CLASS-E_as_bytes(OBJ) This is an alias to C<_to_bytes()>. =back =head3 Numeric conversion =over 4 =item CLASS-E_num(OBJ) Returns a Perl scalar number representing the number OBJ as close as possible. Since Perl scalars have limited precision, the returned value might not be exactly the same as OBJ. =back =head3 Miscellaneous =over 4 =item CLASS-E_copy(OBJ) Returns a true copy OBJ. =item CLASS-E_len(OBJ) Returns the number of the decimal digits in OBJ. The output is a Perl scalar. =item CLASS-E_zeros(OBJ) Returns the number of trailing decimal zeros. The output is a Perl scalar. The number zero has no trailing decimal zeros. =item CLASS-E_digit(OBJ, N) Returns the Nth digit in OBJ as a Perl scalar. N is a Perl scalar, where zero refers to the rightmost (least significant) digit, and negative values count from the left (most significant digit). If $obj represents the number 123, then CLASS->_digit($obj, 0) # returns 3 CLASS->_digit($obj, 1) # returns 2 CLASS->_digit($obj, 2) # returns 1 CLASS->_digit($obj, -1) # returns 1 =item CLASS-E_check(OBJ) Returns true if the object is invalid and false otherwise. Preferably, the true value is a string describing the problem with the object. This is a check routine to test the internal state of the object for corruption. =item CLASS-E_set(OBJ) xxx =back =head2 API version 2 The following methods are required for an API version of 2 or greater. =head3 Constructors =over 4 =item CLASS-E_1ex(N) Return an object representing the number 10**N where N E= 0 is a Perl scalar. =back =head3 Mathematical functions =over 4 =item CLASS-E_nok(OBJ1, OBJ2) Return the binomial coefficient OBJ1 over OBJ1. =back =head3 Miscellaneous =over 4 =item CLASS-E_alen(OBJ) Return the approximate number of decimal digits of the object. The output is a Perl scalar. =back =head2 API optional methods The following methods are optional, and can be defined if the underlying lib has a fast way to do them. If undefined, Math::BigInt will use pure Perl (hence slow) fallback routines to emulate these: =head3 Signed bitwise operators. =over 4 =item CLASS-E_signed_or(OBJ1, OBJ2, SIGN1, SIGN2) Return the signed bitwise or. =item CLASS-E_signed_and(OBJ1, OBJ2, SIGN1, SIGN2) Return the signed bitwise and. =item CLASS-E_signed_xor(OBJ1, OBJ2, SIGN1, SIGN2) Return the signed bitwise exclusive or. =back =head1 WRAP YOUR OWN If you want to port your own favourite C library for big numbers to the Math::BigInt interface, you can take any of the already existing modules as a rough guideline. You should really wrap up the latest Math::BigInt and Math::BigFloat testsuites with your module, and replace in them any of the following: use Math::BigInt; by this: use Math::BigInt lib => 'yourlib'; This way you ensure that your library really works 100% within Math::BigInt. =head1 BUGS Please report any bugs or feature requests to C, or through the web interface at L (requires login). We will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 SUPPORT You can find documentation for this module with the perldoc command. perldoc Math::BigInt::Calc You can also look for information at: =over 4 =item * RT: CPAN's request tracker L =item * AnnoCPAN: Annotated CPAN documentation L =item * CPAN Ratings L =item * Search CPAN L =item * CPAN Testers Matrix L =item * The Bignum mailing list =over 4 =item * Post to mailing list C =item * View mailing list L =item * Subscribe/Unsubscribe L =back =back =head1 LICENSE This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself. =head1 AUTHOR Peter John Acklam, Epjacklam@online.noE Code and documentation based on the Math::BigInt::Calc module by Tels Enospam-abuse@bloodgate.comE =head1 SEE ALSO L, L, L, L and L. =cut BigInt/Calc.pm000064400000226072152530054110007125 0ustar00package Math::BigInt::Calc; use 5.006001; use strict; use warnings; use Carp; use Math::BigInt::Lib; our $VERSION = '1.999811'; our @ISA = ('Math::BigInt::Lib'); # Package to store unsigned big integers in decimal and do math with them # Internally the numbers are stored in an array with at least 1 element, no # leading zero parts (except the first) and in base 1eX where X is determined # automatically at loading time to be the maximum possible value # todo: # - fully remove funky $# stuff in div() (maybe - that code scares me...) # USE_MUL: due to problems on certain os (os390, posix-bc) "* 1e-5" is used # instead of "/ 1e5" at some places, (marked with USE_MUL). Other platforms # BS2000, some Crays need USE_DIV instead. # The BEGIN block is used to determine which of the two variants gives the # correct result. # Beware of things like: # $i = $i * $y + $car; $car = int($i / $BASE); $i = $i % $BASE; # This works on x86, but fails on ARM (SA1100, iPAQ) due to who knows what # reasons. So, use this instead (slower, but correct): # $i = $i * $y + $car; $car = int($i / $BASE); $i -= $BASE * $car; ############################################################################## # global constants, flags and accessory # announce that we are compatible with MBI v1.83 and up sub api_version () { 2; } # constants for easier life my ($BASE, $BASE_LEN, $RBASE, $MAX_VAL); my ($AND_BITS, $XOR_BITS, $OR_BITS); my ($AND_MASK, $XOR_MASK, $OR_MASK); sub _base_len { # Set/get the BASE_LEN and assorted other, related values. # Used only by the testsuite, the set variant is used only by the BEGIN # block below: my ($class, $b, $int) = @_; if (defined $b) { # avoid redefinitions undef &_mul; undef &_div; if ($] >= 5.008 && $int && $b > 7) { $BASE_LEN = $b; *_mul = \&_mul_use_div_64; *_div = \&_div_use_div_64; $BASE = int("1e" . $BASE_LEN); $MAX_VAL = $BASE-1; return $BASE_LEN unless wantarray; return ($BASE_LEN, $BASE, $AND_BITS, $XOR_BITS, $OR_BITS, $BASE_LEN, $MAX_VAL); } # find whether we can use mul or div in mul()/div() $BASE_LEN = $b + 1; my $caught = 0; while (--$BASE_LEN > 5) { $BASE = int("1e" . $BASE_LEN); $RBASE = abs('1e-' . $BASE_LEN); # see USE_MUL $caught = 0; $caught += 1 if (int($BASE * $RBASE) != 1); # should be 1 $caught += 2 if (int($BASE / $BASE) != 1); # should be 1 last if $caught != 3; } $BASE = int("1e" . $BASE_LEN); $RBASE = abs('1e-' . $BASE_LEN); # see USE_MUL $MAX_VAL = $BASE-1; # ($caught & 1) != 0 => cannot use MUL # ($caught & 2) != 0 => cannot use DIV if ($caught == 2) # 2 { # must USE_MUL since we cannot use DIV *_mul = \&_mul_use_mul; *_div = \&_div_use_mul; } else # 0 or 1 { # can USE_DIV instead *_mul = \&_mul_use_div; *_div = \&_div_use_div; } } return $BASE_LEN unless wantarray; return ($BASE_LEN, $BASE, $AND_BITS, $XOR_BITS, $OR_BITS, $BASE_LEN, $MAX_VAL); } sub _new { # Given a string representing an integer, returns a reference to an array # of integers, where each integer represents a chunk of the original input # integer. my ($class, $str) = @_; #unless ($str =~ /^([1-9]\d*|0)\z/) { # require Carp; # Carp::croak("Invalid input string '$str'"); #} my $input_len = length($str) - 1; # Shortcut for small numbers. return bless [ $str ], $class if $input_len < $BASE_LEN; my $format = "a" . (($input_len % $BASE_LEN) + 1); $format .= $] < 5.008 ? "a$BASE_LEN" x int($input_len / $BASE_LEN) : "(a$BASE_LEN)*"; my $self = [ reverse(map { 0 + $_ } unpack($format, $str)) ]; return bless $self, $class; } BEGIN { # from Daniel Pfeiffer: determine largest group of digits that is precisely # multipliable with itself plus carry # Test now changed to expect the proper pattern, not a result off by 1 or 2 my ($e, $num) = 3; # lowest value we will use is 3+1-1 = 3 do { $num = '9' x ++$e; $num *= $num + 1; } while $num =~ /9{$e}0{$e}/; # must be a certain pattern $e--; # last test failed, so retract one step # the limits below brush the problems with the test above under the rug: # the test should be able to find the proper $e automatically $e = 5 if $^O =~ /^uts/; # UTS get's some special treatment $e = 5 if $^O =~ /^unicos/; # unicos is also problematic (6 seems to work # there, but we play safe) my $int = 0; if ($e > 7) { use integer; my $e1 = 7; $num = 7; do { $num = ('9' x ++$e1) + 0; $num *= $num + 1; } while ("$num" =~ /9{$e1}0{$e1}/); # must be a certain pattern $e1--; # last test failed, so retract one step if ($e1 > 7) { $int = 1; $e = $e1; } } __PACKAGE__ -> _base_len($e, $int); # set and store use integer; # find out how many bits _and, _or and _xor can take (old default = 16) # I don't think anybody has yet 128 bit scalars, so let's play safe. local $^W = 0; # don't warn about 'nonportable number' $AND_BITS = 15; $XOR_BITS = 15; $OR_BITS = 15; # find max bits, we will not go higher than numberofbits that fit into $BASE # to make _and etc simpler (and faster for smaller, slower for large numbers) my $max = 16; while (2 ** $max < $BASE) { $max++; } { no integer; $max = 16 if $] < 5.006; # older Perls might not take >16 too well } my ($x, $y, $z); do { $AND_BITS++; $x = CORE::oct('0b' . '1' x $AND_BITS); $y = $x & $x; $z = (2 ** $AND_BITS) - 1; } while ($AND_BITS < $max && $x == $z && $y == $x); $AND_BITS --; # retreat one step do { $XOR_BITS++; $x = CORE::oct('0b' . '1' x $XOR_BITS); $y = $x ^ 0; $z = (2 ** $XOR_BITS) - 1; } while ($XOR_BITS < $max && $x == $z && $y == $x); $XOR_BITS --; # retreat one step do { $OR_BITS++; $x = CORE::oct('0b' . '1' x $OR_BITS); $y = $x | $x; $z = (2 ** $OR_BITS) - 1; } while ($OR_BITS < $max && $x == $z && $y == $x); $OR_BITS--; # retreat one step $AND_MASK = __PACKAGE__->_new(( 2 ** $AND_BITS )); $XOR_MASK = __PACKAGE__->_new(( 2 ** $XOR_BITS )); $OR_MASK = __PACKAGE__->_new(( 2 ** $OR_BITS )); # We can compute the approximate length no faster than the real length: *_alen = \&_len; } ############################################################################### sub _zero { # create a zero my $class = shift; return bless [ 0 ], $class; } sub _one { # create a one my $class = shift; return bless [ 1 ], $class; } sub _two { # create a two my $class = shift; return bless [ 2 ], $class; } sub _ten { # create a 10 my $class = shift; bless [ 10 ], $class; } sub _1ex { # create a 1Ex my $class = shift; my $rem = $_[0] % $BASE_LEN; # remainder my $parts = $_[0] / $BASE_LEN; # parts # 000000, 000000, 100 bless [ (0) x $parts, '1' . ('0' x $rem) ], $class; } sub _copy { # make a true copy my $class = shift; return bless [ @{ $_[0] } ], $class; } # catch and throw away sub import { } ############################################################################## # convert back to string and number sub _str { # Convert number from internal base 1eN format to string format. Internal # format is always normalized, i.e., no leading zeros. my $ary = $_[1]; my $idx = $#$ary; # index of last element if ($idx < 0) { # should not happen require Carp; Carp::croak("$_[1] has no elements"); } # Handle first one differently, since it should not have any leading zeros. my $ret = int($ary->[$idx]); if ($idx > 0) { # Interestingly, the pre-padd method uses more time. # The old grep variant takes longer (14 vs. 10 sec). my $z = '0' x ($BASE_LEN - 1); while (--$idx >= 0) { $ret .= substr($z . $ary->[$idx], -$BASE_LEN); } } $ret; } sub _num { # Make a Perl scalar number (int/float) from a BigInt object. my $x = $_[1]; return $x->[0] if @$x == 1; # below $BASE # Start with the most significant element and work towards the least # significant element. Avoid multiplying "inf" (which happens if the number # overflows) with "0" (if there are zero elements in $x) since this gives # "nan" which propagates to the output. my $num = 0; for (my $i = $#$x ; $i >= 0 ; --$i) { $num *= $BASE; $num += $x -> [$i]; } return $num; } ############################################################################## # actual math code sub _add { # (ref to int_num_array, ref to int_num_array) # # Routine to add two base 1eX numbers stolen from Knuth Vol 2 Algorithm A # pg 231. There are separate routines to add and sub as per Knuth pg 233. # This routine modifies array x, but not y. my ($c, $x, $y) = @_; # $x + 0 => $x return $x if @$y == 1 && $y->[0] == 0; # 0 + $y => $y->copy if (@$x == 1 && $x->[0] == 0) { @$x = @$y; return $x; } # For each in Y, add Y to X and carry. If after that, something is left in # X, foreach in X add carry to X and then return X, carry. Trades one # "$j++" for having to shift arrays. my $i; my $car = 0; my $j = 0; for $i (@$y) { $x->[$j] -= $BASE if $car = (($x->[$j] += $i + $car) >= $BASE) ? 1 : 0; $j++; } while ($car != 0) { $x->[$j] -= $BASE if $car = (($x->[$j] += $car) >= $BASE) ? 1 : 0; $j++; } $x; } sub _inc { # (ref to int_num_array, ref to int_num_array) # Add 1 to $x, modify $x in place my ($c, $x) = @_; for my $i (@$x) { return $x if ($i += 1) < $BASE; # early out $i = 0; # overflow, next } push @$x, 1 if $x->[-1] == 0; # last overflowed, so extend $x; } sub _dec { # (ref to int_num_array, ref to int_num_array) # Sub 1 from $x, modify $x in place my ($c, $x) = @_; my $MAX = $BASE - 1; # since MAX_VAL based on BASE for my $i (@$x) { last if ($i -= 1) >= 0; # early out $i = $MAX; # underflow, next } pop @$x if $x->[-1] == 0 && @$x > 1; # last underflowed (but leave 0) $x; } sub _sub { # (ref to int_num_array, ref to int_num_array, swap) # # Subtract base 1eX numbers -- stolen from Knuth Vol 2 pg 232, $x > $y # subtract Y from X by modifying x in place my ($c, $sx, $sy, $s) = @_; my $car = 0; my $i; my $j = 0; if (!$s) { for $i (@$sx) { last unless defined $sy->[$j] || $car; $i += $BASE if $car = (($i -= ($sy->[$j] || 0) + $car) < 0); $j++; } # might leave leading zeros, so fix that return __strip_zeros($sx); } for $i (@$sx) { # We can't do an early out if $x < $y, since we need to copy the high # chunks from $y. Found by Bob Mathews. #last unless defined $sy->[$j] || $car; $sy->[$j] += $BASE if $car = ($sy->[$j] = $i - ($sy->[$j] || 0) - $car) < 0; $j++; } # might leave leading zeros, so fix that __strip_zeros($sy); } sub _mul_use_mul { # (ref to int_num_array, ref to int_num_array) # multiply two numbers in internal representation # modifies first arg, second need not be different from first my ($c, $xv, $yv) = @_; if (@$yv == 1) { # shortcut for two very short numbers (improved by Nathan Zook) # works also if xv and yv are the same reference, and handles also $x == 0 if (@$xv == 1) { if (($xv->[0] *= $yv->[0]) >= $BASE) { $xv->[0] = $xv->[0] - ($xv->[1] = int($xv->[0] * $RBASE)) * $BASE; } ; return $xv; } # $x * 0 => 0 if ($yv->[0] == 0) { @$xv = (0); return $xv; } # multiply a large number a by a single element one, so speed up my $y = $yv->[0]; my $car = 0; foreach my $i (@$xv) { $i = $i * $y + $car; $car = int($i * $RBASE); $i -= $car * $BASE; } push @$xv, $car if $car != 0; return $xv; } # shortcut for result $x == 0 => result = 0 return $xv if @$xv == 1 && $xv->[0] == 0; # since multiplying $x with $x fails, make copy in this case $yv = [ @$xv ] if $xv == $yv; # same references? my @prod = (); my ($prod, $car, $cty, $xi, $yi); for $xi (@$xv) { $car = 0; $cty = 0; # slow variant # for $yi (@$yv) # { # $prod = $xi * $yi + ($prod[$cty] || 0) + $car; # $prod[$cty++] = # $prod - ($car = int($prod * RBASE)) * $BASE; # see USE_MUL # } # $prod[$cty] += $car if $car; # need really to check for 0? # $xi = shift @prod; # faster variant # looping through this if $xi == 0 is silly - so optimize it away! $xi = (shift @prod || 0), next if $xi == 0; for $yi (@$yv) { $prod = $xi * $yi + ($prod[$cty] || 0) + $car; ## this is actually a tad slower ## $prod = $prod[$cty]; $prod += ($car + $xi * $yi); # no ||0 here $prod[$cty++] = $prod - ($car = int($prod * $RBASE)) * $BASE; # see USE_MUL } $prod[$cty] += $car if $car; # need really to check for 0? $xi = shift @prod || 0; # || 0 makes v5.005_3 happy } push @$xv, @prod; # can't have leading zeros # __strip_zeros($xv); $xv; } sub _mul_use_div_64 { # (ref to int_num_array, ref to int_num_array) # multiply two numbers in internal representation # modifies first arg, second need not be different from first # works for 64 bit integer with "use integer" my ($c, $xv, $yv) = @_; use integer; if (@$yv == 1) { # shortcut for two small numbers, also handles $x == 0 if (@$xv == 1) { # shortcut for two very short numbers (improved by Nathan Zook) # works also if xv and yv are the same reference, and handles also $x == 0 if (($xv->[0] *= $yv->[0]) >= $BASE) { $xv->[0] = $xv->[0] - ($xv->[1] = $xv->[0] / $BASE) * $BASE; } return $xv; } # $x * 0 => 0 if ($yv->[0] == 0) { @$xv = (0); return $xv; } # multiply a large number a by a single element one, so speed up my $y = $yv->[0]; my $car = 0; foreach my $i (@$xv) { #$i = $i * $y + $car; $car = $i / $BASE; $i -= $car * $BASE; $i = $i * $y + $car; $i -= ($car = $i / $BASE) * $BASE; } push @$xv, $car if $car != 0; return $xv; } # shortcut for result $x == 0 => result = 0 return $xv if ( ((@$xv == 1) && ($xv->[0] == 0)) ); # since multiplying $x with $x fails, make copy in this case $yv = $c->_copy($xv) if $xv == $yv; # same references? my @prod = (); my ($prod, $car, $cty, $xi, $yi); for $xi (@$xv) { $car = 0; $cty = 0; # looping through this if $xi == 0 is silly - so optimize it away! $xi = (shift @prod || 0), next if $xi == 0; for $yi (@$yv) { $prod = $xi * $yi + ($prod[$cty] || 0) + $car; $prod[$cty++] = $prod - ($car = $prod / $BASE) * $BASE; } $prod[$cty] += $car if $car; # need really to check for 0? $xi = shift @prod || 0; # || 0 makes v5.005_3 happy } push @$xv, @prod; $xv; } sub _mul_use_div { # (ref to int_num_array, ref to int_num_array) # multiply two numbers in internal representation # modifies first arg, second need not be different from first my ($c, $xv, $yv) = @_; if (@$yv == 1) { # shortcut for two small numbers, also handles $x == 0 if (@$xv == 1) { # shortcut for two very short numbers (improved by Nathan Zook) # works also if xv and yv are the same reference, and handles also $x == 0 if (($xv->[0] *= $yv->[0]) >= $BASE) { $xv->[0] = $xv->[0] - ($xv->[1] = int($xv->[0] / $BASE)) * $BASE; } ; return $xv; } # $x * 0 => 0 if ($yv->[0] == 0) { @$xv = (0); return $xv; } # multiply a large number a by a single element one, so speed up my $y = $yv->[0]; my $car = 0; foreach my $i (@$xv) { $i = $i * $y + $car; $car = int($i / $BASE); $i -= $car * $BASE; # This (together with use integer;) does not work on 32-bit Perls #$i = $i * $y + $car; $i -= ($car = $i / $BASE) * $BASE; } push @$xv, $car if $car != 0; return $xv; } # shortcut for result $x == 0 => result = 0 return $xv if ( ((@$xv == 1) && ($xv->[0] == 0)) ); # since multiplying $x with $x fails, make copy in this case $yv = $c->_copy($xv) if $xv == $yv; # same references? my @prod = (); my ($prod, $car, $cty, $xi, $yi); for $xi (@$xv) { $car = 0; $cty = 0; # looping through this if $xi == 0 is silly - so optimize it away! $xi = (shift @prod || 0), next if $xi == 0; for $yi (@$yv) { $prod = $xi * $yi + ($prod[$cty] || 0) + $car; $prod[$cty++] = $prod - ($car = int($prod / $BASE)) * $BASE; } $prod[$cty] += $car if $car; # need really to check for 0? $xi = shift @prod || 0; # || 0 makes v5.005_3 happy } push @$xv, @prod; # can't have leading zeros # __strip_zeros($xv); $xv; } sub _div_use_mul { # ref to array, ref to array, modify first array and return remainder if # in list context # see comments in _div_use_div() for more explanations my ($c, $x, $yorg) = @_; # the general div algorithm here is about O(N*N) and thus quite slow, so # we first check for some special cases and use shortcuts to handle them. # This works, because we store the numbers in a chunked format where each # element contains 5..7 digits (depending on system). # if both numbers have only one element: if (@$x == 1 && @$yorg == 1) { # shortcut, $yorg and $x are two small numbers if (wantarray) { my $rem = [ $x->[0] % $yorg->[0] ]; bless $rem, $c; $x->[0] = int($x->[0] / $yorg->[0]); return ($x, $rem); } else { $x->[0] = int($x->[0] / $yorg->[0]); return $x; } } # if x has more than one, but y has only one element: if (@$yorg == 1) { my $rem; $rem = $c->_mod($c->_copy($x), $yorg) if wantarray; # shortcut, $y is < $BASE my $j = @$x; my $r = 0; my $y = $yorg->[0]; my $b; while ($j-- > 0) { $b = $r * $BASE + $x->[$j]; $x->[$j] = int($b/$y); $r = $b % $y; } pop @$x if @$x > 1 && $x->[-1] == 0; # splice up a leading zero return ($x, $rem) if wantarray; return $x; } # now x and y have more than one element # check whether y has more elements than x, if yet, the result will be 0 if (@$yorg > @$x) { my $rem; $rem = $c->_copy($x) if wantarray; # make copy @$x = 0; # set to 0 return ($x, $rem) if wantarray; # including remainder? return $x; # only x, which is [0] now } # check whether the numbers have the same number of elements, in that case # the result will fit into one element and can be computed efficiently if (@$yorg == @$x) { # if $yorg has more digits than $x (it's leading element is longer than # the one from $x), the result will also be 0: if (length(int($yorg->[-1])) > length(int($x->[-1]))) { my $rem = $c->_copy($x) if wantarray; # make copy @$x = 0; # set to 0 return ($x, $rem) if wantarray; # including remainder? return $x; } # now calculate $x / $yorg if (length(int($yorg->[-1])) == length(int($x->[-1]))) { # same length, so make full compare my $a = 0; my $j = @$x - 1; # manual way (abort if unequal, good for early ne) while ($j >= 0) { last if ($a = $x->[$j] - $yorg->[$j]); $j--; } # $a contains the result of the compare between X and Y # a < 0: x < y, a == 0: x == y, a > 0: x > y if ($a <= 0) { # a = 0 => x == y => rem 0 # a < 0 => x < y => rem = x my $rem = $a == 0 ? $c->_zero() : $c->_copy($x); @$x = 0; # if $a < 0 $x->[0] = 1 if $a == 0; # $x == $y return ($x, $rem) if wantarray; return $x; } # $x >= $y, so proceed normally } } # all other cases: my $y = $c->_copy($yorg); # always make copy to preserve my ($car, $bar, $prd, $dd, $xi, $yi, @q, $v2, $v1, @d, $tmp, $q, $u2, $u1, $u0); $car = $bar = $prd = 0; if (($dd = int($BASE / ($y->[-1] + 1))) != 1) { for $xi (@$x) { $xi = $xi * $dd + $car; $xi -= ($car = int($xi * $RBASE)) * $BASE; # see USE_MUL } push(@$x, $car); $car = 0; for $yi (@$y) { $yi = $yi * $dd + $car; $yi -= ($car = int($yi * $RBASE)) * $BASE; # see USE_MUL } } else { push(@$x, 0); } @q = (); ($v2, $v1) = @$y[-2, -1]; $v2 = 0 unless $v2; while ($#$x > $#$y) { ($u2, $u1, $u0) = @$x[-3 .. -1]; $u2 = 0 unless $u2; #warn "oups v1 is 0, u0: $u0 $y->[-2] $y->[-1] l ",scalar @$y,"\n" # if $v1 == 0; $q = (($u0 == $v1) ? $MAX_VAL : int(($u0 * $BASE + $u1) / $v1)); --$q while ($v2 * $q > ($u0 * $BASE + $u1 - $q * $v1) * $BASE + $u2); if ($q) { ($car, $bar) = (0, 0); for ($yi = 0, $xi = $#$x - $#$y-1; $yi <= $#$y; ++$yi, ++$xi) { $prd = $q * $y->[$yi] + $car; $prd -= ($car = int($prd * $RBASE)) * $BASE; # see USE_MUL $x->[$xi] += $BASE if ($bar = (($x->[$xi] -= $prd + $bar) < 0)); } if ($x->[-1] < $car + $bar) { $car = 0; --$q; for ($yi = 0, $xi = $#$x - $#$y-1; $yi <= $#$y; ++$yi, ++$xi) { $x->[$xi] -= $BASE if ($car = (($x->[$xi] += $y->[$yi] + $car) >= $BASE)); } } } pop(@$x); unshift(@q, $q); } if (wantarray) { my $d = bless [], $c; if ($dd != 1) { $car = 0; for $xi (reverse @$x) { $prd = $car * $BASE + $xi; $car = $prd - ($tmp = int($prd / $dd)) * $dd; # see USE_MUL unshift(@$d, $tmp); } } else { @$d = @$x; } @$x = @q; __strip_zeros($x); __strip_zeros($d); return ($x, $d); } @$x = @q; __strip_zeros($x); $x; } sub _div_use_div_64 { # ref to array, ref to array, modify first array and return remainder if # in list context # This version works on 64 bit integers my ($c, $x, $yorg) = @_; use integer; # the general div algorithm here is about O(N*N) and thus quite slow, so # we first check for some special cases and use shortcuts to handle them. # This works, because we store the numbers in a chunked format where each # element contains 5..7 digits (depending on system). # if both numbers have only one element: if (@$x == 1 && @$yorg == 1) { # shortcut, $yorg and $x are two small numbers if (wantarray) { my $rem = [ $x->[0] % $yorg->[0] ]; bless $rem, $c; $x->[0] = int($x->[0] / $yorg->[0]); return ($x, $rem); } else { $x->[0] = int($x->[0] / $yorg->[0]); return $x; } } # if x has more than one, but y has only one element: if (@$yorg == 1) { my $rem; $rem = $c->_mod($c->_copy($x), $yorg) if wantarray; # shortcut, $y is < $BASE my $j = @$x; my $r = 0; my $y = $yorg->[0]; my $b; while ($j-- > 0) { $b = $r * $BASE + $x->[$j]; $x->[$j] = int($b/$y); $r = $b % $y; } pop @$x if @$x > 1 && $x->[-1] == 0; # splice up a leading zero return ($x, $rem) if wantarray; return $x; } # now x and y have more than one element # check whether y has more elements than x, if yet, the result will be 0 if (@$yorg > @$x) { my $rem; $rem = $c->_copy($x) if wantarray; # make copy @$x = 0; # set to 0 return ($x, $rem) if wantarray; # including remainder? return $x; # only x, which is [0] now } # check whether the numbers have the same number of elements, in that case # the result will fit into one element and can be computed efficiently if (@$yorg == @$x) { my $rem; # if $yorg has more digits than $x (it's leading element is longer than # the one from $x), the result will also be 0: if (length(int($yorg->[-1])) > length(int($x->[-1]))) { $rem = $c->_copy($x) if wantarray; # make copy @$x = 0; # set to 0 return ($x, $rem) if wantarray; # including remainder? return $x; } # now calculate $x / $yorg if (length(int($yorg->[-1])) == length(int($x->[-1]))) { # same length, so make full compare my $a = 0; my $j = @$x - 1; # manual way (abort if unequal, good for early ne) while ($j >= 0) { last if ($a = $x->[$j] - $yorg->[$j]); $j--; } # $a contains the result of the compare between X and Y # a < 0: x < y, a == 0: x == y, a > 0: x > y if ($a <= 0) { $rem = $c->_zero(); # a = 0 => x == y => rem 0 $rem = $c->_copy($x) if $a != 0; # a < 0 => x < y => rem = x @$x = 0; # if $a < 0 $x->[0] = 1 if $a == 0; # $x == $y return ($x, $rem) if wantarray; # including remainder? return $x; } # $x >= $y, so proceed normally } } # all other cases: my $y = $c->_copy($yorg); # always make copy to preserve my ($car, $bar, $prd, $dd, $xi, $yi, @q, $v2, $v1, @d, $tmp, $q, $u2, $u1, $u0); $car = $bar = $prd = 0; if (($dd = int($BASE / ($y->[-1] + 1))) != 1) { for $xi (@$x) { $xi = $xi * $dd + $car; $xi -= ($car = int($xi / $BASE)) * $BASE; } push(@$x, $car); $car = 0; for $yi (@$y) { $yi = $yi * $dd + $car; $yi -= ($car = int($yi / $BASE)) * $BASE; } } else { push(@$x, 0); } # @q will accumulate the final result, $q contains the current computed # part of the final result @q = (); ($v2, $v1) = @$y[-2, -1]; $v2 = 0 unless $v2; while ($#$x > $#$y) { ($u2, $u1, $u0) = @$x[-3..-1]; $u2 = 0 unless $u2; #warn "oups v1 is 0, u0: $u0 $y->[-2] $y->[-1] l ",scalar @$y,"\n" # if $v1 == 0; $q = (($u0 == $v1) ? $MAX_VAL : int(($u0 * $BASE + $u1) / $v1)); --$q while ($v2 * $q > ($u0 * $BASE +$ u1- $q*$v1) * $BASE + $u2); if ($q) { ($car, $bar) = (0, 0); for ($yi = 0, $xi = $#$x - $#$y - 1; $yi <= $#$y; ++$yi, ++$xi) { $prd = $q * $y->[$yi] + $car; $prd -= ($car = int($prd / $BASE)) * $BASE; $x->[$xi] += $BASE if ($bar = (($x->[$xi] -= $prd + $bar) < 0)); } if ($x->[-1] < $car + $bar) { $car = 0; --$q; for ($yi = 0, $xi = $#$x - $#$y - 1; $yi <= $#$y; ++$yi, ++$xi) { $x->[$xi] -= $BASE if ($car = (($x->[$xi] += $y->[$yi] + $car) >= $BASE)); } } } pop(@$x); unshift(@q, $q); } if (wantarray) { my $d = bless [], $c; if ($dd != 1) { $car = 0; for $xi (reverse @$x) { $prd = $car * $BASE + $xi; $car = $prd - ($tmp = int($prd / $dd)) * $dd; unshift(@$d, $tmp); } } else { @$d = @$x; } @$x = @q; __strip_zeros($x); __strip_zeros($d); return ($x, $d); } @$x = @q; __strip_zeros($x); $x; } sub _div_use_div { # ref to array, ref to array, modify first array and return remainder if # in list context my ($c, $x, $yorg) = @_; # the general div algorithm here is about O(N*N) and thus quite slow, so # we first check for some special cases and use shortcuts to handle them. # This works, because we store the numbers in a chunked format where each # element contains 5..7 digits (depending on system). # if both numbers have only one element: if (@$x == 1 && @$yorg == 1) { # shortcut, $yorg and $x are two small numbers if (wantarray) { my $rem = [ $x->[0] % $yorg->[0] ]; bless $rem, $c; $x->[0] = int($x->[0] / $yorg->[0]); return ($x, $rem); } else { $x->[0] = int($x->[0] / $yorg->[0]); return $x; } } # if x has more than one, but y has only one element: if (@$yorg == 1) { my $rem; $rem = $c->_mod($c->_copy($x), $yorg) if wantarray; # shortcut, $y is < $BASE my $j = @$x; my $r = 0; my $y = $yorg->[0]; my $b; while ($j-- > 0) { $b = $r * $BASE + $x->[$j]; $x->[$j] = int($b/$y); $r = $b % $y; } pop @$x if @$x > 1 && $x->[-1] == 0; # splice up a leading zero return ($x, $rem) if wantarray; return $x; } # now x and y have more than one element # check whether y has more elements than x, if yet, the result will be 0 if (@$yorg > @$x) { my $rem; $rem = $c->_copy($x) if wantarray; # make copy @$x = 0; # set to 0 return ($x, $rem) if wantarray; # including remainder? return $x; # only x, which is [0] now } # check whether the numbers have the same number of elements, in that case # the result will fit into one element and can be computed efficiently if (@$yorg == @$x) { my $rem; # if $yorg has more digits than $x (it's leading element is longer than # the one from $x), the result will also be 0: if (length(int($yorg->[-1])) > length(int($x->[-1]))) { $rem = $c->_copy($x) if wantarray; # make copy @$x = 0; # set to 0 return ($x, $rem) if wantarray; # including remainder? return $x; } # now calculate $x / $yorg if (length(int($yorg->[-1])) == length(int($x->[-1]))) { # same length, so make full compare my $a = 0; my $j = @$x - 1; # manual way (abort if unequal, good for early ne) while ($j >= 0) { last if ($a = $x->[$j] - $yorg->[$j]); $j--; } # $a contains the result of the compare between X and Y # a < 0: x < y, a == 0: x == y, a > 0: x > y if ($a <= 0) { $rem = $c->_zero(); # a = 0 => x == y => rem 0 $rem = $c->_copy($x) if $a != 0; # a < 0 => x < y => rem = x @$x = 0; $x->[0] = 0; # if $a < 0 $x->[0] = 1 if $a == 0; # $x == $y return ($x, $rem) if wantarray; # including remainder? return $x; } # $x >= $y, so proceed normally } } # all other cases: my $y = $c->_copy($yorg); # always make copy to preserve my ($car, $bar, $prd, $dd, $xi, $yi, @q, $v2, $v1, @d, $tmp, $q, $u2, $u1, $u0); $car = $bar = $prd = 0; if (($dd = int($BASE / ($y->[-1] + 1))) != 1) { for $xi (@$x) { $xi = $xi * $dd + $car; $xi -= ($car = int($xi / $BASE)) * $BASE; } push(@$x, $car); $car = 0; for $yi (@$y) { $yi = $yi * $dd + $car; $yi -= ($car = int($yi / $BASE)) * $BASE; } } else { push(@$x, 0); } # @q will accumulate the final result, $q contains the current computed # part of the final result @q = (); ($v2, $v1) = @$y[-2, -1]; $v2 = 0 unless $v2; while ($#$x > $#$y) { ($u2, $u1, $u0) = @$x[-3..-1]; $u2 = 0 unless $u2; #warn "oups v1 is 0, u0: $u0 $y->[-2] $y->[-1] l ",scalar @$y,"\n" # if $v1 == 0; $q = (($u0 == $v1) ? $MAX_VAL : int(($u0 * $BASE + $u1) / $v1)); --$q while ($v2 * $q > ($u0 * $BASE + $u1 - $q * $v1) * $BASE + $u2); if ($q) { ($car, $bar) = (0, 0); for ($yi = 0, $xi = $#$x - $#$y - 1; $yi <= $#$y; ++$yi, ++$xi) { $prd = $q * $y->[$yi] + $car; $prd -= ($car = int($prd / $BASE)) * $BASE; $x->[$xi] += $BASE if ($bar = (($x->[$xi] -= $prd + $bar) < 0)); } if ($x->[-1] < $car + $bar) { $car = 0; --$q; for ($yi = 0, $xi = $#$x - $#$y - 1; $yi <= $#$y; ++$yi, ++$xi) { $x->[$xi] -= $BASE if ($car = (($x->[$xi] += $y->[$yi] + $car) >= $BASE)); } } } pop(@$x); unshift(@q, $q); } if (wantarray) { my $d = bless [], $c; if ($dd != 1) { $car = 0; for $xi (reverse @$x) { $prd = $car * $BASE + $xi; $car = $prd - ($tmp = int($prd / $dd)) * $dd; unshift(@$d, $tmp); } } else { @$d = @$x; } @$x = @q; __strip_zeros($x); __strip_zeros($d); return ($x, $d); } @$x = @q; __strip_zeros($x); $x; } ############################################################################## # testing sub _acmp { # Internal absolute post-normalized compare (ignore signs) # ref to array, ref to array, return <0, 0, >0 # Arrays must have at least one entry; this is not checked for. my ($c, $cx, $cy) = @_; # shortcut for short numbers return (($cx->[0] <=> $cy->[0]) <=> 0) if @$cx == 1 && @$cy == 1; # fast comp based on number of array elements (aka pseudo-length) my $lxy = (@$cx - @$cy) # or length of first element if same number of elements (aka difference 0) || # need int() here because sometimes the last element is '00018' vs '18' (length(int($cx->[-1])) - length(int($cy->[-1]))); return -1 if $lxy < 0; # already differs, ret return 1 if $lxy > 0; # ditto # manual way (abort if unequal, good for early ne) my $a; my $j = @$cx; while (--$j >= 0) { last if $a = $cx->[$j] - $cy->[$j]; } $a <=> 0; } sub _len { # compute number of digits in base 10 # int() because add/sub sometimes leaves strings (like '00005') instead of # '5' in this place, thus causing length() to report wrong length my $cx = $_[1]; (@$cx - 1) * $BASE_LEN + length(int($cx->[-1])); } sub _digit { # Return the nth digit. Zero is rightmost, so _digit(123, 0) gives 3. # Negative values count from the left, so _digit(123, -1) gives 1. my ($c, $x, $n) = @_; my $len = _len('', $x); $n += $len if $n < 0; # -1 last, -2 second-to-last # Math::BigInt::Calc returns 0 if N is out of range, but this is not done # by the other backend libraries. return "0" if $n < 0 || $n >= $len; # return 0 for digits out of range my $elem = int($n / $BASE_LEN); # index of array element my $digit = $n % $BASE_LEN; # index of digit within the element substr("0" x $BASE_LEN . "$x->[$elem]", -1 - $digit, 1); } sub _zeros { # Return number of trailing zeros in decimal. # Check each array element for having 0 at end as long as elem == 0 # Upon finding a elem != 0, stop. my $x = $_[1]; return 0 if @$x == 1 && $x->[0] == 0; my $zeros = 0; foreach my $elem (@$x) { if ($elem != 0) { $elem =~ /[^0](0*)\z/; $zeros += length($1); # count trailing zeros last; # early out } $zeros += $BASE_LEN; } $zeros; } ############################################################################## # _is_* routines sub _is_zero { # return true if arg is zero @{$_[1]} == 1 && $_[1]->[0] == 0 ? 1 : 0; } sub _is_even { # return true if arg is even $_[1]->[0] & 1 ? 0 : 1; } sub _is_odd { # return true if arg is odd $_[1]->[0] & 1 ? 1 : 0; } sub _is_one { # return true if arg is one @{$_[1]} == 1 && $_[1]->[0] == 1 ? 1 : 0; } sub _is_two { # return true if arg is two @{$_[1]} == 1 && $_[1]->[0] == 2 ? 1 : 0; } sub _is_ten { # return true if arg is ten @{$_[1]} == 1 && $_[1]->[0] == 10 ? 1 : 0; } sub __strip_zeros { # Internal normalization function that strips leading zeros from the array. # Args: ref to array my $x = shift; push @$x, 0 if @$x == 0; # div might return empty results, so fix it return $x if @$x == 1; # early out #print "strip: cnt $cnt i $i\n"; # '0', '3', '4', '0', '0', # 0 1 2 3 4 # cnt = 5, i = 4 # i = 4 # i = 3 # => fcnt = cnt - i (5-2 => 3, cnt => 5-1 = 4, throw away from 4th pos) # >= 1: skip first part (this can be zero) my $i = $#$x; while ($i > 0) { last if $x->[$i] != 0; $i--; } $i++; splice(@$x, $i) if $i < @$x; $x; } ############################################################################### # check routine to test internal state for corruptions sub _check { # used by the test suite my ($class, $x) = @_; my $msg = $class -> SUPER::_check($x); return $msg if $msg; my $n; eval { $n = @$x }; return "Not an array reference" unless $@ eq ''; return "Reference to an empty array" unless $n > 0; # The following fails with Math::BigInt::FastCalc because a # Math::BigInt::FastCalc "object" is an unblessed array ref. # #return 0 unless ref($x) eq $class; for (my $i = 0 ; $i <= $#$x ; ++ $i) { my $e = $x -> [$i]; return "Element at index $i is undefined" unless defined $e; return "Element at index $i is a '" . ref($e) . "', which is not a scalar" unless ref($e) eq ""; # It would be better to use the regex /^([1-9]\d*|0)\z/, but that fails # in Math::BigInt::FastCalc, because it sometimes creates array # elements like "000000". return "Element at index $i is '$e', which does not look like an" . " normal integer" unless $e =~ /^\d+\z/; return "Element at index $i is '$e', which is not smaller than" . " the base '$BASE'" if $e >= $BASE; return "Element at index $i (last element) is zero" if $#$x > 0 && $i == $#$x && $e == 0; } return 0; } ############################################################################### sub _mod { # if possible, use mod shortcut my ($c, $x, $yo) = @_; # slow way since $y too big if (@$yo > 1) { my ($xo, $rem) = $c->_div($x, $yo); @$x = @$rem; return $x; } my $y = $yo->[0]; # if both are single element arrays if (@$x == 1) { $x->[0] %= $y; return $x; } # if @$x has more than one element, but @$y is a single element my $b = $BASE % $y; if ($b == 0) { # when BASE % Y == 0 then (B * BASE) % Y == 0 # (B * BASE) % $y + A % Y => A % Y # so need to consider only last element: O(1) $x->[0] %= $y; } elsif ($b == 1) { # else need to go through all elements in @$x: O(N), but loop is a bit # simplified my $r = 0; foreach (@$x) { $r = ($r + $_) % $y; # not much faster, but heh... #$r += $_ % $y; $r %= $y; } $r = 0 if $r == $y; $x->[0] = $r; } else { # else need to go through all elements in @$x: O(N) my $r = 0; my $bm = 1; foreach (@$x) { $r = ($_ * $bm + $r) % $y; $bm = ($bm * $b) % $y; #$r += ($_ % $y) * $bm; #$bm *= $b; #$bm %= $y; #$r %= $y; } $r = 0 if $r == $y; $x->[0] = $r; } @$x = $x->[0]; # keep one element of @$x return $x; } ############################################################################## # shifts sub _rsft { my ($c, $x, $y, $n) = @_; if ($n != 10) { $n = $c->_new($n); return scalar $c->_div($x, $c->_pow($n, $y)); } # shortcut (faster) for shifting by 10) # multiples of $BASE_LEN my $dst = 0; # destination my $src = $c->_num($y); # as normal int my $xlen = (@$x - 1) * $BASE_LEN + length(int($x->[-1])); if ($src >= $xlen or ($src == $xlen and !defined $x->[1])) { # 12345 67890 shifted right by more than 10 digits => 0 splice(@$x, 1); # leave only one element $x->[0] = 0; # set to zero return $x; } my $rem = $src % $BASE_LEN; # remainder to shift $src = int($src / $BASE_LEN); # source if ($rem == 0) { splice(@$x, 0, $src); # even faster, 38.4 => 39.3 } else { my $len = @$x - $src; # elems to go my $vd; my $z = '0' x $BASE_LEN; $x->[ @$x ] = 0; # avoid || 0 test inside loop while ($dst < $len) { $vd = $z . $x->[$src]; $vd = substr($vd, -$BASE_LEN, $BASE_LEN - $rem); $src++; $vd = substr($z . $x->[$src], -$rem, $rem) . $vd; $vd = substr($vd, -$BASE_LEN, $BASE_LEN) if length($vd) > $BASE_LEN; $x->[$dst] = int($vd); $dst++; } splice(@$x, $dst) if $dst > 0; # kill left-over array elems pop @$x if $x->[-1] == 0 && @$x > 1; # kill last element if 0 } # else rem == 0 $x; } sub _lsft { my ($c, $x, $n, $b) = @_; return $x if $c->_is_zero($x); # Handle the special case when the base is a power of 10. Don't check # whether log($b)/log(10) is an integer, because log(1000)/log(10) is not # exactly 3. my $log10 = sprintf "%.0f", log($b) / log(10); if ($b == 10 ** $log10) { $b = 10; $n = $c->_mul($n, $c->_new($log10)); # shortcut (faster) for shifting by 10) since we are in base 10eX # multiples of $BASE_LEN: my $src = @$x; # source my $len = $c->_num($n); # shift-len as normal int my $rem = $len % $BASE_LEN; # remainder to shift my $dst = $src + int($len / $BASE_LEN); # destination my $vd; # further speedup $x->[$src] = 0; # avoid first ||0 for speed my $z = '0' x $BASE_LEN; while ($src >= 0) { $vd = $x->[$src]; $vd = $z . $vd; $vd = substr($vd, -$BASE_LEN + $rem, $BASE_LEN - $rem); $vd .= $src > 0 ? substr($z . $x->[$src - 1], -$BASE_LEN, $rem) : '0' x $rem; $vd = substr($vd, -$BASE_LEN, $BASE_LEN) if length($vd) > $BASE_LEN; $x->[$dst] = int($vd); $dst--; $src--; } # set lowest parts to 0 while ($dst >= 0) { $x->[$dst--] = 0; } # fix spurious last zero element splice @$x, -1 if $x->[-1] == 0; return $x; } else { $b = $c->_new($b); #print $c->_str($b); return $c->_mul($x, $c->_pow($b, $n)); } } sub _pow { # power of $x to $y # ref to array, ref to array, return ref to array my ($c, $cx, $cy) = @_; if (@$cy == 1 && $cy->[0] == 0) { splice(@$cx, 1); $cx->[0] = 1; # y == 0 => x => 1 return $cx; } if ((@$cx == 1 && $cx->[0] == 1) || # x == 1 (@$cy == 1 && $cy->[0] == 1)) # or y == 1 { return $cx; } if (@$cx == 1 && $cx->[0] == 0) { splice (@$cx, 1); $cx->[0] = 0; # 0 ** y => 0 (if not y <= 0) return $cx; } my $pow2 = $c->_one(); my $y_bin = $c->_as_bin($cy); $y_bin =~ s/^0b//; my $len = length($y_bin); while (--$len > 0) { $c->_mul($pow2, $cx) if substr($y_bin, $len, 1) eq '1'; # is odd? $c->_mul($cx, $cx); } $c->_mul($cx, $pow2); $cx; } sub _nok { # Return binomial coefficient (n over k). # Given refs to arrays, return ref to array. # First input argument is modified. my ($c, $n, $k) = @_; # If k > n/2, or, equivalently, 2*k > n, compute nok(n, k) as # nok(n, n-k), to minimize the number if iterations in the loop. { my $twok = $c->_mul($c->_two(), $c->_copy($k)); # 2 * k if ($c->_acmp($twok, $n) > 0) { # if 2*k > n $k = $c->_sub($c->_copy($n), $k); # k = n - k } } # Example: # # / 7 \ 7! 1*2*3*4 * 5*6*7 5 * 6 * 7 6 7 # | | = --------- = --------------- = --------- = 5 * - * - # \ 3 / (7-3)! 3! 1*2*3*4 * 1*2*3 1 * 2 * 3 2 3 if ($c->_is_zero($k)) { @$n = 1; } else { # Make a copy of the original n, since we'll be modifying n in-place. my $n_orig = $c->_copy($n); # n = 5, f = 6, d = 2 (cf. example above) $c->_sub($n, $k); $c->_inc($n); my $f = $c->_copy($n); $c->_inc($f); my $d = $c->_two(); # while f <= n (the original n, that is) ... while ($c->_acmp($f, $n_orig) <= 0) { # n = (n * f / d) == 5 * 6 / 2 (cf. example above) $c->_mul($n, $f); $c->_div($n, $d); # f = 7, d = 3 (cf. example above) $c->_inc($f); $c->_inc($d); } } return $n; } my @factorials = ( 1, 1, 2, 2*3, 2*3*4, 2*3*4*5, 2*3*4*5*6, 2*3*4*5*6*7, ); sub _fac { # factorial of $x # ref to array, return ref to array my ($c, $cx) = @_; if ((@$cx == 1) && ($cx->[0] <= 7)) { $cx->[0] = $factorials[$cx->[0]]; # 0 => 1, 1 => 1, 2 => 2 etc. return $cx; } if ((@$cx == 1) && # we do this only if $x >= 12 and $x <= 7000 ($cx->[0] >= 12 && $cx->[0] < 7000)) { # Calculate (k-j) * (k-j+1) ... k .. (k+j-1) * (k + j) # See http://blogten.blogspot.com/2007/01/calculating-n.html # The above series can be expressed as factors: # k * k - (j - i) * 2 # We cache k*k, and calculate (j * j) as the sum of the first j odd integers # This will not work when N exceeds the storage of a Perl scalar, however, # in this case the algorithm would be way too slow to terminate, anyway. # As soon as the last element of $cx is 0, we split it up and remember # how many zeors we got so far. The reason is that n! will accumulate # zeros at the end rather fast. my $zero_elements = 0; # If n is even, set n = n -1 my $k = $c->_num($cx); my $even = 1; if (($k & 1) == 0) { $even = $k; $k --; } # set k to the center point $k = ($k + 1) / 2; # print "k $k even: $even\n"; # now calculate k * k my $k2 = $k * $k; my $odd = 1; my $sum = 1; my $i = $k - 1; # keep reference to x my $new_x = $c->_new($k * $even); @$cx = @$new_x; if ($cx->[0] == 0) { $zero_elements ++; shift @$cx; } # print STDERR "x = ", $c->_str($cx), "\n"; my $BASE2 = int(sqrt($BASE))-1; my $j = 1; while ($j <= $i) { my $m = ($k2 - $sum); $odd += 2; $sum += $odd; $j++; while ($j <= $i && ($m < $BASE2) && (($k2 - $sum) < $BASE2)) { $m *= ($k2 - $sum); $odd += 2; $sum += $odd; $j++; # print STDERR "\n k2 $k2 m $m sum $sum odd $odd\n"; sleep(1); } if ($m < $BASE) { $c->_mul($cx, [$m]); } else { $c->_mul($cx, $c->_new($m)); } if ($cx->[0] == 0) { $zero_elements ++; shift @$cx; } # print STDERR "Calculate $k2 - $sum = $m (x = ", $c->_str($cx), ")\n"; } # multiply in the zeros again unshift @$cx, (0) x $zero_elements; return $cx; } # go forward until $base is exceeded limit is either $x steps (steps == 100 # means a result always too high) or $base. my $steps = 100; $steps = $cx->[0] if @$cx == 1; my $r = 2; my $cf = 3; my $step = 2; my $last = $r; while ($r * $cf < $BASE && $step < $steps) { $last = $r; $r *= $cf++; $step++; } if ((@$cx == 1) && $step == $cx->[0]) { # completely done, so keep reference to $x and return $cx->[0] = $r; return $cx; } # now we must do the left over steps my $n; # steps still to do if (@$cx == 1) { $n = $cx->[0]; } else { $n = $c->_copy($cx); } # Set $cx to the last result below $BASE (but keep ref to $x) $cx->[0] = $last; splice (@$cx, 1); # As soon as the last element of $cx is 0, we split it up and remember # how many zeors we got so far. The reason is that n! will accumulate # zeros at the end rather fast. my $zero_elements = 0; # do left-over steps fit into a scalar? if (ref $n eq 'ARRAY') { # No, so use slower inc() & cmp() # ($n is at least $BASE here) my $base_2 = int(sqrt($BASE)) - 1; #print STDERR "base_2: $base_2\n"; while ($step < $base_2) { if ($cx->[0] == 0) { $zero_elements ++; shift @$cx; } my $b = $step * ($step + 1); $step += 2; $c->_mul($cx, [$b]); } $step = [$step]; while ($c->_acmp($step, $n) <= 0) { if ($cx->[0] == 0) { $zero_elements ++; shift @$cx; } $c->_mul($cx, $step); $c->_inc($step); } } else { # Yes, so we can speed it up slightly # print "# left over steps $n\n"; my $base_4 = int(sqrt(sqrt($BASE))) - 2; #print STDERR "base_4: $base_4\n"; my $n4 = $n - 4; while ($step < $n4 && $step < $base_4) { if ($cx->[0] == 0) { $zero_elements ++; shift @$cx; } my $b = $step * ($step + 1); $step += 2; $b *= $step * ($step + 1); $step += 2; $c->_mul($cx, [$b]); } my $base_2 = int(sqrt($BASE)) - 1; my $n2 = $n - 2; #print STDERR "base_2: $base_2\n"; while ($step < $n2 && $step < $base_2) { if ($cx->[0] == 0) { $zero_elements ++; shift @$cx; } my $b = $step * ($step + 1); $step += 2; $c->_mul($cx, [$b]); } # do what's left over while ($step <= $n) { $c->_mul($cx, [$step]); $step++; if ($cx->[0] == 0) { $zero_elements ++; shift @$cx; } } } # multiply in the zeros again unshift @$cx, (0) x $zero_elements; $cx; # return result } sub _log_int { # calculate integer log of $x to base $base # ref to array, ref to array - return ref to array my ($c, $x, $base) = @_; # X == 0 => NaN return if @$x == 1 && $x->[0] == 0; # BASE 0 or 1 => NaN return if @$base == 1 && $base->[0] < 2; # X == 1 => 0 (is exact) if (@$x == 1 && $x->[0] == 1) { @$x = 0; return $x, 1; } my $cmp = $c->_acmp($x, $base); # X == BASE => 1 (is exact) if ($cmp == 0) { @$x = 1; return $x, 1; } # 1 < X < BASE => 0 (is truncated) if ($cmp < 0) { @$x = 0; return $x, 0; } my $x_org = $c->_copy($x); # preserve x # Compute a guess for the result based on: # $guess = int ( length_in_base_10(X) / ( log(base) / log(10) ) ) my $len = $c->_len($x_org); my $log = log($base->[-1]) / log(10); # for each additional element in $base, we add $BASE_LEN to the result, # based on the observation that log($BASE, 10) is BASE_LEN and # log(x*y) == log(x) + log(y): $log += (@$base - 1) * $BASE_LEN; # calculate now a guess based on the values obtained above: my $res = int($len / $log); @$x = $res; my $trial = $c->_pow($c->_copy($base), $x); my $acmp = $c->_acmp($trial, $x_org); # Did we get the exact result? return $x, 1 if $acmp == 0; # Too small? while ($acmp < 0) { $c->_mul($trial, $base); $c->_inc($x); $acmp = $c->_acmp($trial, $x_org); } # Too big? while ($acmp > 0) { $c->_div($trial, $base); $c->_dec($x); $acmp = $c->_acmp($trial, $x_org); } return $x, 1 if $acmp == 0; # result is exact return $x, 0; # result is too small } # for debugging: use constant DEBUG => 0; my $steps = 0; sub steps { $steps }; sub _sqrt { # square-root of $x in place # Compute a guess of the result (by rule of thumb), then improve it via # Newton's method. my ($c, $x) = @_; if (@$x == 1) { # fits into one Perl scalar, so result can be computed directly $x->[0] = int(sqrt($x->[0])); return $x; } my $y = $c->_copy($x); # hopefully _len/2 is < $BASE, the -1 is to always undershot the guess # since our guess will "grow" my $l = int(($c->_len($x)-1) / 2); my $lastelem = $x->[-1]; # for guess my $elems = @$x - 1; # not enough digits, but could have more? if ((length($lastelem) <= 3) && ($elems > 1)) { # right-align with zero pad my $len = length($lastelem) & 1; print "$lastelem => " if DEBUG; $lastelem .= substr($x->[-2] . '0' x $BASE_LEN, 0, $BASE_LEN); # former odd => make odd again, or former even to even again $lastelem = $lastelem / 10 if (length($lastelem) & 1) != $len; print "$lastelem\n" if DEBUG; } # construct $x (instead of $c->_lsft($x, $l, 10) my $r = $l % $BASE_LEN; # 10000 00000 00000 00000 ($BASE_LEN=5) $l = int($l / $BASE_LEN); print "l = $l " if DEBUG; splice @$x, $l; # keep ref($x), but modify it # we make the first part of the guess not '1000...0' but int(sqrt($lastelem)) # that gives us: # 14400 00000 => sqrt(14400) => guess first digits to be 120 # 144000 000000 => sqrt(144000) => guess 379 print "$lastelem (elems $elems) => " if DEBUG; $lastelem = $lastelem / 10 if ($elems & 1 == 1); # odd or even? my $g = sqrt($lastelem); $g =~ s/\.//; # 2.345 => 2345 $r -= 1 if $elems & 1 == 0; # 70 => 7 # padd with zeros if result is too short $x->[$l--] = int(substr($g . '0' x $r, 0, $r+1)); print "now ", $x->[-1] if DEBUG; print " would have been ", int('1' . '0' x $r), "\n" if DEBUG; # If @$x > 1, we could compute the second elem of the guess, too, to create # an even better guess. Not implemented yet. Does it improve performance? $x->[$l--] = 0 while ($l >= 0); # all other digits of guess are zero print "start x= ", $c->_str($x), "\n" if DEBUG; my $two = $c->_two(); my $last = $c->_zero(); my $lastlast = $c->_zero(); $steps = 0 if DEBUG; while ($c->_acmp($last, $x) != 0 && $c->_acmp($lastlast, $x) != 0) { $steps++ if DEBUG; $lastlast = $c->_copy($last); $last = $c->_copy($x); $c->_add($x, $c->_div($c->_copy($y), $x)); $c->_div($x, $two ); print " x= ", $c->_str($x), "\n" if DEBUG; } print "\nsteps in sqrt: $steps, " if DEBUG; $c->_dec($x) if $c->_acmp($y, $c->_mul($c->_copy($x), $x)) < 0; # overshot? print " final ", $x->[-1], "\n" if DEBUG; $x; } sub _root { # Take n'th root of $x in place. my ($c, $x, $n) = @_; # Small numbers. if (@$x == 1 && @$n == 1) { # Result can be computed directly. Adjust initial result for numerical # errors, e.g., int(1000**(1/3)) is 2, not 3. my $y = int($x->[0] ** (1 / $n->[0])); my $yp1 = $y + 1; $y = $yp1 if $yp1 ** $n->[0] == $x->[0]; $x->[0] = $y; return $x; } # If x <= n, the result is always (truncated to) 1. if ((@$x > 1 || $x -> [0] > 0) && # if x is non-zero ... $c -> _acmp($x, $n) <= 0) # ... and x <= n { my $one = $x -> _one(); @$x = @$one; return $x; } # If $n is a power of two, take sqrt($x) repeatedly, e.g., root($x, 4) = # sqrt(sqrt($x)), root($x, 8) = sqrt(sqrt(sqrt($x))). my $b = $c -> _as_bin($n); if ($b =~ /0b1(0+)$/) { my $count = length($1); # 0b100 => len('00') => 2 my $cnt = $count; # counter for loop unshift @$x, 0; # add one element, together with one # more below in the loop this makes 2 while ($cnt-- > 0) { # 'Inflate' $x by adding one element, basically computing # $x * $BASE * $BASE. This gives us more $BASE_LEN digits for # result since len(sqrt($X)) approx == len($x) / 2. unshift @$x, 0; # Calculate sqrt($x), $x is now one element to big, again. In the # next round we make that two, again. $c -> _sqrt($x); } # $x is now one element too big, so truncate result by removing it. shift @$x; return $x; } my $DEBUG = 0; # Now the general case. This works by finding an initial guess. If this # guess is incorrect, a relatively small delta is chosen. This delta is # used to find a lower and upper limit for the correct value. The delta is # doubled in each iteration. When a lower and upper limit is found, # bisection is applied to narrow down the region until we have the correct # value. # Split x into mantissa and exponent in base 10, so that # # x = xm * 10^xe, where 0 < xm < 1 and xe is an integer my $x_str = $c -> _str($x); my $xm = "." . $x_str; my $xe = length($x_str); # From this we compute the base 10 logarithm of x # # log_10(x) = log_10(xm) + log_10(xe^10) # = log(xm)/log(10) + xe # # and then the base 10 logarithm of y, where y = x^(1/n) # # log_10(y) = log_10(x)/n my $log10x = log($xm) / log(10) + $xe; my $log10y = $log10x / $c -> _num($n); # And from this we compute ym and ye, the mantissa and exponent (in # base 10) of y, where 1 < ym <= 10 and ye is an integer. my $ye = int $log10y; my $ym = 10 ** ($log10y - $ye); # Finally, we scale the mantissa and exponent to incraese the integer # part of ym, before building the string representing our guess of y. if ($DEBUG) { print "\n"; print "xm = $xm\n"; print "xe = $xe\n"; print "log10x = $log10x\n"; print "log10y = $log10y\n"; print "ym = $ym\n"; print "ye = $ye\n"; print "\n"; } my $d = $ye < 15 ? $ye : 15; $ym *= 10 ** $d; $ye -= $d; my $y_str = sprintf('%.0f', $ym) . "0" x $ye; my $y = $c -> _new($y_str); if ($DEBUG) { print "ym = $ym\n"; print "ye = $ye\n"; print "\n"; print "y_str = $y_str (initial guess)\n"; print "\n"; } # See if our guess y is correct. my $trial = $c -> _pow($c -> _copy($y), $n); my $acmp = $c -> _acmp($trial, $x); if ($acmp == 0) { @$x = @$y; return $x; } # Find a lower and upper limit for the correct value of y. Start off with a # delta value that is approximately the size of the accuracy of the guess. my $lower; my $upper; my $delta = $c -> _new("1" . ("0" x $ye)); my $two = $c -> _two(); if ($acmp < 0) { $lower = $y; while ($acmp < 0) { $upper = $c -> _add($c -> _copy($lower), $delta); if ($DEBUG) { print "lower = $lower\n"; print "upper = $upper\n"; print "delta = $delta\n"; print "\n"; } $acmp = $c -> _acmp($c -> _pow($c -> _copy($upper), $n), $x); if ($acmp == 0) { @$x = @$upper; return $x; } $delta = $c -> _mul($delta, $two); } } elsif ($acmp > 0) { $upper = $y; my $zero = $c -> _zero(); while ($acmp > 0) { if ($c -> _acmp($upper, $delta) <= 0) { $lower = $c -> _zero(); last; } $lower = $c -> _sub($c -> _copy($upper), $delta); if ($DEBUG) { print "lower = $lower\n"; print "upper = $upper\n"; print "delta = $delta\n"; print "\n"; } $acmp = $c -> _acmp($c -> _pow($c -> _copy($lower), $n), $x); if ($acmp == 0) { @$x = @$lower; return $x; } $delta = $c -> _mul($delta, $two); } } # Use bisection to narrow down the interval. my $one = $c -> _one(); { $delta = $c -> _sub($c -> _copy($upper), $lower); if ($c -> _acmp($delta, $one) <= 0) { @$x = @$lower; return $x; } if ($DEBUG) { print "lower = $lower\n"; print "upper = $upper\n"; print "delta = $delta\n"; print "\n"; } $delta = $c -> _div($delta, $two); my $middle = $c -> _add($c -> _copy($lower), $delta); $acmp = $c -> _acmp($c -> _pow($c -> _copy($middle), $n), $x); if ($acmp < 0) { $lower = $middle; } elsif ($acmp > 0) { $upper = $middle; } else { @$x = @$middle; return $x; } redo; } $x; } ############################################################################## # binary stuff sub _and { my ($c, $x, $y) = @_; # the shortcut makes equal, large numbers _really_ fast, and makes only a # very small performance drop for small numbers (e.g. something with less # than 32 bit) Since we optimize for large numbers, this is enabled. return $x if $c->_acmp($x, $y) == 0; # shortcut my $m = $c->_one(); my ($xr, $yr); my $mask = $AND_MASK; my $x1 = $c->_copy($x); my $y1 = $c->_copy($y); my $z = $c->_zero(); use integer; until ($c->_is_zero($x1) || $c->_is_zero($y1)) { ($x1, $xr) = $c->_div($x1, $mask); ($y1, $yr) = $c->_div($y1, $mask); $c->_add($z, $c->_mul([ 0 + $xr->[0] & 0 + $yr->[0] ], $m)); $c->_mul($m, $mask); } @$x = @$z; return $x; } sub _xor { my ($c, $x, $y) = @_; return $c->_zero() if $c->_acmp($x, $y) == 0; # shortcut (see -and) my $m = $c->_one(); my ($xr, $yr); my $mask = $XOR_MASK; my $x1 = $c->_copy($x); my $y1 = $c->_copy($y); # make copy my $z = $c->_zero(); use integer; until ($c->_is_zero($x1) || $c->_is_zero($y1)) { ($x1, $xr) = $c->_div($x1, $mask); ($y1, $yr) = $c->_div($y1, $mask); # make ints() from $xr, $yr (see _and()) #$b = 1; $xrr = 0; foreach (@$xr) { $xrr += $_ * $b; $b *= $BASE; } #$b = 1; $yrr = 0; foreach (@$yr) { $yrr += $_ * $b; $b *= $BASE; } #$c->_add($x, $c->_mul($c->_new($xrr ^ $yrr)), $m) ); $c->_add($z, $c->_mul([ 0 + $xr->[0] ^ 0 + $yr->[0] ], $m)); $c->_mul($m, $mask); } # the loop stops when the shorter of the two numbers is exhausted # the remainder of the longer one will survive bit-by-bit, so we simple # multiply-add it in $c->_add($z, $c->_mul($x1, $m) ) if !$c->_is_zero($x1); $c->_add($z, $c->_mul($y1, $m) ) if !$c->_is_zero($y1); @$x = @$z; return $x; } sub _or { my ($c, $x, $y) = @_; return $x if $c->_acmp($x, $y) == 0; # shortcut (see _and) my $m = $c->_one(); my ($xr, $yr); my $mask = $OR_MASK; my $x1 = $c->_copy($x); my $y1 = $c->_copy($y); # make copy my $z = $c->_zero(); use integer; until ($c->_is_zero($x1) || $c->_is_zero($y1)) { ($x1, $xr) = $c->_div($x1, $mask); ($y1, $yr) = $c->_div($y1, $mask); # make ints() from $xr, $yr (see _and()) # $b = 1; $xrr = 0; foreach (@$xr) { $xrr += $_ * $b; $b *= $BASE; } # $b = 1; $yrr = 0; foreach (@$yr) { $yrr += $_ * $b; $b *= $BASE; } # $c->_add($x, $c->_mul(_new( $c, ($xrr | $yrr) ), $m) ); $c->_add($z, $c->_mul([ 0 + $xr->[0] | 0 + $yr->[0] ], $m)); $c->_mul($m, $mask); } # the loop stops when the shorter of the two numbers is exhausted # the remainder of the longer one will survive bit-by-bit, so we simple # multiply-add it in $c->_add($z, $c->_mul($x1, $m) ) if !$c->_is_zero($x1); $c->_add($z, $c->_mul($y1, $m) ) if !$c->_is_zero($y1); @$x = @$z; return $x; } sub _as_hex { # convert a decimal number to hex (ref to array, return ref to string) my ($c, $x) = @_; # fits into one element (handle also 0x0 case) return sprintf("0x%x", $x->[0]) if @$x == 1; my $x1 = $c->_copy($x); my $es = ''; my ($xr, $h, $x10000); if ($] >= 5.006) { $x10000 = [ 0x10000 ]; $h = 'h4'; } else { $x10000 = [ 0x1000 ]; $h = 'h3'; } while (@$x1 != 1 || $x1->[0] != 0) # _is_zero() { ($x1, $xr) = $c->_div($x1, $x10000); $es .= unpack($h, pack('V', $xr->[0])); } $es = reverse $es; $es =~ s/^[0]+//; # strip leading zeros '0x' . $es; # return result prepended with 0x } sub _as_bin { # convert a decimal number to bin (ref to array, return ref to string) my ($c, $x) = @_; # fits into one element (and Perl recent enough), handle also 0b0 case # handle zero case for older Perls if ($] <= 5.005 && @$x == 1 && $x->[0] == 0) { my $t = '0b0'; return $t; } if (@$x == 1 && $] >= 5.006) { my $t = sprintf("0b%b", $x->[0]); return $t; } my $x1 = $c->_copy($x); my $es = ''; my ($xr, $b, $x10000); if ($] >= 5.006) { $x10000 = [ 0x10000 ]; $b = 'b16'; } else { $x10000 = [ 0x1000 ]; $b = 'b12'; } while (!(@$x1 == 1 && $x1->[0] == 0)) # _is_zero() { ($x1, $xr) = $c->_div($x1, $x10000); $es .= unpack($b, pack('v', $xr->[0])); } $es = reverse $es; $es =~ s/^[0]+//; # strip leading zeros '0b' . $es; # return result prepended with 0b } sub _as_oct { # convert a decimal number to octal (ref to array, return ref to string) my ($c, $x) = @_; # fits into one element (handle also 0 case) return sprintf("0%o", $x->[0]) if @$x == 1; my $x1 = $c->_copy($x); my $es = ''; my $xr; my $x1000 = [ 0100000 ]; while (@$x1 != 1 || $x1->[0] != 0) # _is_zero() { ($x1, $xr) = $c->_div($x1, $x1000); $es .= reverse sprintf("%05o", $xr->[0]); } $es = reverse $es; $es =~ s/^0+//; # strip leading zeros '0' . $es; # return result prepended with 0 } sub _from_oct { # convert a octal number to decimal (string, return ref to array) my ($c, $os) = @_; # for older Perls, play safe my $m = [ 0100000 ]; my $d = 5; # 5 digits at a time my $mul = $c->_one(); my $x = $c->_zero(); my $len = int((length($os) - 1) / $d); # $d digit parts, w/o the '0' my $val; my $i = -$d; while ($len >= 0) { $val = substr($os, $i, $d); # get oct digits $val = CORE::oct($val); $i -= $d; $len --; my $adder = [ $val ]; $c->_add($x, $c->_mul($adder, $mul)) if $val != 0; $c->_mul($mul, $m) if $len >= 0; # skip last mul } $x; } sub _from_hex { # convert a hex number to decimal (string, return ref to array) my ($c, $hs) = @_; my $m = $c->_new(0x10000000); # 28 bit at a time (<32 bit!) my $d = 7; # 7 digits at a time my $mul = $c->_one(); my $x = $c->_zero(); my $len = int((length($hs) - 2) / $d); # $d digit parts, w/o the '0x' my $val; my $i = -$d; while ($len >= 0) { $val = substr($hs, $i, $d); # get hex digits $val =~ s/^0x// if $len == 0; # for last part only because $val = CORE::hex($val); # hex does not like wrong chars $i -= $d; $len --; my $adder = [ $val ]; # if the resulting number was to big to fit into one element, create a # two-element version (bug found by Mark Lakata - Thanx!) if (CORE::length($val) > $BASE_LEN) { $adder = $c->_new($val); } $c->_add($x, $c->_mul($adder, $mul)) if $val != 0; $c->_mul($mul, $m) if $len >= 0; # skip last mul } $x; } sub _from_bin { # convert a hex number to decimal (string, return ref to array) my ($c, $bs) = @_; # instead of converting X (8) bit at a time, it is faster to "convert" the # number to hex, and then call _from_hex. my $hs = $bs; $hs =~ s/^[+-]?0b//; # remove sign and 0b my $l = length($hs); # bits $hs = '0' x (8 - ($l % 8)) . $hs if ($l % 8) != 0; # padd left side w/ 0 my $h = '0x' . unpack('H*', pack ('B*', $hs)); # repack as hex $c->_from_hex($h); } ############################################################################## # special modulus functions sub _modinv { # modular multiplicative inverse my ($c, $x, $y) = @_; # modulo zero if ($c->_is_zero($y)) { return undef, undef; } # modulo one if ($c->_is_one($y)) { return $c->_zero(), '+'; } my $u = $c->_zero(); my $v = $c->_one(); my $a = $c->_copy($y); my $b = $c->_copy($x); # Euclid's Algorithm for bgcd(), only that we calc bgcd() ($a) and the result # ($u) at the same time. See comments in BigInt for why this works. my $q; my $sign = 1; { ($a, $q, $b) = ($b, $c->_div($a, $b)); # step 1 last if $c->_is_zero($b); my $t = $c->_add( # step 2: $c->_mul($c->_copy($v), $q), # t = v * q $u); # + u $u = $v; # u = v $v = $t; # v = t $sign = -$sign; redo; } # if the gcd is not 1, then return NaN return (undef, undef) unless $c->_is_one($a); ($v, $sign == 1 ? '+' : '-'); } sub _modpow { # modulus of power ($x ** $y) % $z my ($c, $num, $exp, $mod) = @_; # a^b (mod 1) = 0 for all a and b if ($c->_is_one($mod)) { @$num = 0; return $num; } # 0^a (mod m) = 0 if m != 0, a != 0 # 0^0 (mod m) = 1 if m != 0 if ($c->_is_zero($num)) { if ($c->_is_zero($exp)) { @$num = 1; } else { @$num = 0; } return $num; } # $num = $c->_mod($num, $mod); # this does not make it faster my $acc = $c->_copy($num); my $t = $c->_one(); my $expbin = $c->_as_bin($exp); $expbin =~ s/^0b//; my $len = length($expbin); while (--$len >= 0) { if (substr($expbin, $len, 1) eq '1') { # is_odd $t = $c->_mul($t, $acc); $t = $c->_mod($t, $mod); } $acc = $c->_mul($acc, $acc); $acc = $c->_mod($acc, $mod); } @$num = @$t; $num; } sub _gcd { # Greatest common divisor. my ($c, $x, $y) = @_; # gcd(0, 0) = 0 # gcd(0, a) = a, if a != 0 if (@$x == 1 && $x->[0] == 0) { if (@$y == 1 && $y->[0] == 0) { @$x = 0; } else { @$x = @$y; } return $x; } # Until $y is zero ... until (@$y == 1 && $y->[0] == 0) { # Compute remainder. $c->_mod($x, $y); # Swap $x and $y. my $tmp = $c->_copy($x); @$x = @$y; $y = $tmp; # no deref here; that would modify input $y } return $x; } 1; =pod =head1 NAME Math::BigInt::Calc - Pure Perl module to support Math::BigInt =head1 SYNOPSIS # to use it with Math::BigInt use Math::BigInt lib => 'Calc'; # to use it with Math::BigFloat use Math::BigFloat lib => 'Calc'; # to use it with Math::BigRat use Math::BigRat lib => 'Calc'; =head1 DESCRIPTION Math::BigInt::Calc inherits from Math::BigInt::Lib. In this library, the numbers are represented in base B = 10**N, where N is the largest possible value that does not cause overflow in the intermediate computations. The base B elements are stored in an array, with the least significant element stored in array element zero. There are no leading zero elements, except a single zero element when the number is zero. For instance, if B = 10000, the number 1234567890 is represented internally as [7890, 3456, 12]. =head1 SEE ALSO L for a description of the API. Alternative libraries L, L, and L. Some of the modules that use these libraries L, L, and L. =cut BigInt/Trace.pm000064400000001737152530054110007320 0ustar00#!perl package Math::BigInt::Trace; require 5.010; use strict; use warnings; use Exporter; use Math::BigInt; our ($accuracy, $precision, $round_mode, $div_scale); our @ISA = qw(Exporter Math::BigInt); our $VERSION = '0.49'; use overload; # inherit overload from Math::BigInt # Globals $accuracy = $precision = undef; $round_mode = 'even'; $div_scale = 40; sub new { my $proto = shift; my $class = ref($proto) || $proto; my $value = shift; my $a = $accuracy; $a = $_[0] if defined $_[0]; my $p = $precision; $p = $_[1] if defined $_[1]; my $self = Math::BigInt->new($value, $a, $p, $round_mode); bless $self, $class; print "MBI new '$value' => '$self' (", ref($self), ")"; return $self; } sub import { print "MBI import ", join(' ', @_); my $self = shift; Math::BigInt::import($self, @_); # need it for subclasses # $self->export_to_level(1, $self, @_); # need this ? @_ = (); } 1; BigInt/CalcEmu.pm000064400000023412152530054110007565 0ustar00package Math::BigInt::CalcEmu; use 5.006001; use strict; use warnings; our $VERSION = '1.999811'; package Math::BigInt; # See SYNOPSIS below. my $CALC_EMU; BEGIN { $CALC_EMU = Math::BigInt->config('lib'); # register us with MBI to get notified of future lib changes Math::BigInt::_register_callback( __PACKAGE__, sub { $CALC_EMU = $_[0]; } ); } sub __emu_band { my ($self,$x,$y,$sx,$sy,@r) = @_; return $x->bzero(@r) if $y->is_zero() || $x->is_zero(); my $sign = 0; # sign of result $sign = 1 if $sx == -1 && $sy == -1; my ($bx,$by); if ($sx == -1) # if x is negative { # two's complement: inc and flip all "bits" in $bx $bx = $x->binc()->as_hex(); # -1 => 0, -2 => 1, -3 => 2 etc $bx =~ s/-?0x//; $bx =~ tr/0123456789abcdef/\x0f\x0e\x0d\x0c\x0b\x0a\x09\x08\x07\x06\x05\x04\x03\x02\x01\x00/; } else { $bx = $x->as_hex(); # get binary representation $bx =~ s/-?0x//; $bx =~ tr/fedcba9876543210/\x0f\x0e\x0d\x0c\x0b\x0a\x09\x08\x07\x06\x05\x04\x03\x02\x01\x00/; } if ($sy == -1) # if y is negative { # two's complement: inc and flip all "bits" in $by $by = $y->copy()->binc()->as_hex(); # -1 => 0, -2 => 1, -3 => 2 etc $by =~ s/-?0x//; $by =~ tr/0123456789abcdef/\x0f\x0e\x0d\x0c\x0b\x0a\x09\x08\x07\x06\x05\x04\x03\x02\x01\x00/; } else { $by = $y->as_hex(); # get binary representation $by =~ s/-?0x//; $by =~ tr/fedcba9876543210/\x0f\x0e\x0d\x0c\x0b\x0a\x09\x08\x07\x06\x05\x04\x03\x02\x01\x00/; } # now we have bit-strings from X and Y, reverse them for padding $bx = reverse $bx; $by = reverse $by; # padd the shorter string my $xx = "\x00"; $xx = "\x0f" if $sx == -1; my $yy = "\x00"; $yy = "\x0f" if $sy == -1; my $diff = CORE::length($bx) - CORE::length($by); if ($diff > 0) { # if $yy eq "\x00", we can cut $bx, otherwise we need to padd $by $by .= $yy x $diff; } elsif ($diff < 0) { # if $xx eq "\x00", we can cut $by, otherwise we need to padd $bx $bx .= $xx x abs($diff); } # and the strings together my $r = $bx & $by; # and reverse the result again $bx = reverse $r; # One of $x or $y was negative, so need to flip bits in the result. # In both cases (one or two of them negative, or both positive) we need # to get the characters back. if ($sign == 1) { $bx =~ tr/\x0f\x0e\x0d\x0c\x0b\x0a\x09\x08\x07\x06\x05\x04\x03\x02\x01\x00/0123456789abcdef/; } else { $bx =~ tr/\x0f\x0e\x0d\x0c\x0b\x0a\x09\x08\x07\x06\x05\x04\x03\x02\x01\x00/fedcba9876543210/; } # leading zeros will be stripped by _from_hex() $bx = '0x' . $bx; $x->{value} = $CALC_EMU->_from_hex( $bx ); # calculate sign of result $x->{sign} = '+'; $x->{sign} = '-' if $sign == 1 && !$x->is_zero(); $x->bdec() if $sign == 1; $x->round(@r); } sub __emu_bior { my ($self,$x,$y,$sx,$sy,@r) = @_; return $x->round(@r) if $y->is_zero(); my $sign = 0; # sign of result $sign = 1 if ($sx == -1) || ($sy == -1); my ($bx,$by); if ($sx == -1) # if x is negative { # two's complement: inc and flip all "bits" in $bx $bx = $x->binc()->as_hex(); # -1 => 0, -2 => 1, -3 => 2 etc $bx =~ s/-?0x//; $bx =~ tr/0123456789abcdef/\x0f\x0e\x0d\x0c\x0b\x0a\x09\x08\x07\x06\x05\x04\x03\x02\x01\x00/; } else { $bx = $x->as_hex(); # get binary representation $bx =~ s/-?0x//; $bx =~ tr/fedcba9876543210/\x0f\x0e\x0d\x0c\x0b\x0a\x09\x08\x07\x06\x05\x04\x03\x02\x01\x00/; } if ($sy == -1) # if y is negative { # two's complement: inc and flip all "bits" in $by $by = $y->copy()->binc()->as_hex(); # -1 => 0, -2 => 1, -3 => 2 etc $by =~ s/-?0x//; $by =~ tr/0123456789abcdef/\x0f\x0e\x0d\x0c\x0b\x0a\x09\x08\x07\x06\x05\x04\x03\x02\x01\x00/; } else { $by = $y->as_hex(); # get binary representation $by =~ s/-?0x//; $by =~ tr/fedcba9876543210/\x0f\x0e\x0d\x0c\x0b\x0a\x09\x08\x07\x06\x05\x04\x03\x02\x01\x00/; } # now we have bit-strings from X and Y, reverse them for padding $bx = reverse $bx; $by = reverse $by; # padd the shorter string my $xx = "\x00"; $xx = "\x0f" if $sx == -1; my $yy = "\x00"; $yy = "\x0f" if $sy == -1; my $diff = CORE::length($bx) - CORE::length($by); if ($diff > 0) { $by .= $yy x $diff; } elsif ($diff < 0) { $bx .= $xx x abs($diff); } # or the strings together my $r = $bx | $by; # and reverse the result again $bx = reverse $r; # one of $x or $y was negative, so need to flip bits in the result # in both cases (one or two of them negative, or both positive) we need # to get the characters back. if ($sign == 1) { $bx =~ tr/\x0f\x0e\x0d\x0c\x0b\x0a\x09\x08\x07\x06\x05\x04\x03\x02\x01\x00/0123456789abcdef/; } else { $bx =~ tr/\x0f\x0e\x0d\x0c\x0b\x0a\x09\x08\x07\x06\x05\x04\x03\x02\x01\x00/fedcba9876543210/; } # leading zeros will be stripped by _from_hex() $bx = '0x' . $bx; $x->{value} = $CALC_EMU->_from_hex( $bx ); # calculate sign of result $x->{sign} = '+'; $x->{sign} = '-' if $sign == 1 && !$x->is_zero(); # if one of X or Y was negative, we need to decrement result $x->bdec() if $sign == 1; $x->round(@r); } sub __emu_bxor { my ($self,$x,$y,$sx,$sy,@r) = @_; return $x->round(@r) if $y->is_zero(); my $sign = 0; # sign of result $sign = 1 if $x->{sign} ne $y->{sign}; my ($bx,$by); if ($sx == -1) # if x is negative { # two's complement: inc and flip all "bits" in $bx $bx = $x->binc()->as_hex(); # -1 => 0, -2 => 1, -3 => 2 etc $bx =~ s/-?0x//; $bx =~ tr/0123456789abcdef/\x0f\x0e\x0d\x0c\x0b\x0a\x09\x08\x07\x06\x05\x04\x03\x02\x01\x00/; } else { $bx = $x->as_hex(); # get binary representation $bx =~ s/-?0x//; $bx =~ tr/fedcba9876543210/\x0f\x0e\x0d\x0c\x0b\x0a\x09\x08\x07\x06\x05\x04\x03\x02\x01\x00/; } if ($sy == -1) # if y is negative { # two's complement: inc and flip all "bits" in $by $by = $y->copy()->binc()->as_hex(); # -1 => 0, -2 => 1, -3 => 2 etc $by =~ s/-?0x//; $by =~ tr/0123456789abcdef/\x0f\x0e\x0d\x0c\x0b\x0a\x09\x08\x07\x06\x05\x04\x03\x02\x01\x00/; } else { $by = $y->as_hex(); # get binary representation $by =~ s/-?0x//; $by =~ tr/fedcba9876543210/\x0f\x0e\x0d\x0c\x0b\x0a\x09\x08\x07\x06\x05\x04\x03\x02\x01\x00/; } # now we have bit-strings from X and Y, reverse them for padding $bx = reverse $bx; $by = reverse $by; # padd the shorter string my $xx = "\x00"; $xx = "\x0f" if $sx == -1; my $yy = "\x00"; $yy = "\x0f" if $sy == -1; my $diff = CORE::length($bx) - CORE::length($by); if ($diff > 0) { $by .= $yy x $diff; } elsif ($diff < 0) { $bx .= $xx x abs($diff); } # xor the strings together my $r = $bx ^ $by; # and reverse the result again $bx = reverse $r; # one of $x or $y was negative, so need to flip bits in the result # in both cases (one or two of them negative, or both positive) we need # to get the characters back. if ($sign == 1) { $bx =~ tr/\x0f\x0e\x0d\x0c\x0b\x0a\x09\x08\x07\x06\x05\x04\x03\x02\x01\x00/0123456789abcdef/; } else { $bx =~ tr/\x0f\x0e\x0d\x0c\x0b\x0a\x09\x08\x07\x06\x05\x04\x03\x02\x01\x00/fedcba9876543210/; } # leading zeros will be stripped by _from_hex() $bx = '0x' . $bx; $x->{value} = $CALC_EMU->_from_hex( $bx ); # calculate sign of result $x->{sign} = '+'; $x->{sign} = '-' if $sx != $sy && !$x->is_zero(); $x->bdec() if $sign == 1; $x->round(@r); } ############################################################################## ############################################################################## 1; __END__ =pod =head1 NAME Math::BigInt::CalcEmu - Emulate low-level math with BigInt code =head1 SYNOPSIS use Math::BigInt; use Math::BigInt::CalcEmu; =head1 DESCRIPTION Contains routines that emulate low-level math functions in BigInt, e.g. optional routines the low-level math package does not provide on its own. Will be loaded on demand and called automatically by BigInt. Stuff here is really low-priority to optimize, since it is far better to implement the operation in the low-level math library directly, possible even using a call to the native lib. =head1 METHODS =over =item __emu_bxor =item __emu_band =item __emu_bior =back =head1 BUGS Please report any bugs or feature requests to C, or through the web interface at L (requires login). We will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 SUPPORT You can find documentation for this module with the perldoc command. perldoc Math::BigInt::CalcEmu You can also look for information at: =over 4 =item * RT: CPAN's request tracker L =item * AnnoCPAN: Annotated CPAN documentation L =item * CPAN Ratings L =item * Search CPAN L =item * CPAN Testers Matrix L =item * The Bignum mailing list =over 4 =item * Post to mailing list C =item * View mailing list L =item * Subscribe/Unsubscribe L =back =back =head1 LICENSE This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself. =head1 AUTHORS (c) Tels http://bloodgate.com 2003, 2004 - based on BigInt code by Tels from 2001-2003. =head1 SEE ALSO L, L, L and L. =cut BigFloat/Trace.pm000064400000002365152530054110007631 0ustar00#!perl package Math::BigFloat::Trace; require 5.010; use strict; use warnings; use Exporter; use Math::BigFloat; our ($accuracy, $precision, $round_mode, $div_scale); our @ISA = qw(Exporter Math::BigFloat); our $VERSION = '0.49'; use overload; # inherit overload from Math::BigFloat # Globals $accuracy = $precision = undef; $round_mode = 'even'; $div_scale = 40; sub new { my $proto = shift; my $class = ref($proto) || $proto; my $value = shift; my $a = $accuracy; $a = $_[0] if defined $_[0]; my $p = $precision; $p = $_[1] if defined $_[1]; my $self = Math::BigFloat->new($value, $a, $p, $round_mode); # remember, downgrading may return a BigInt, so don't meddle with class # bless $self, $class; print "MBF new '$value' => '$self' (", ref($self), ")"; return $self; } sub import { print "MBF import ", join(' ', @_); my $self = shift; # we catch the constants, the rest goes go BigFloat my @a = (); foreach (@_) { push @a, $_ if $_ ne ':constant'; } overload::constant float => sub { $self->new(shift); }; Math::BigFloat->import(@a); # need it for subclasses # $self->export_to_level(1,$self,@_); # need this ? } 1;