CINXE.COM
Math::BigInt - Arbitrary size integer/float math package - Perldoc Browser
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Math::BigInt - Arbitrary size integer/float math package - Perldoc Browser</title> <link rel="search" href="/opensearch.xml" type="application/opensearchdescription+xml" title="Perldoc Browser"> <link rel="canonical" href="https://perldoc.perl.org/Math::BigInt"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.5.0/styles/stackoverflow-light.min.css" integrity="sha512-cG1IdFxqipi3gqLmksLtuk13C+hBa57a6zpWxMeoY3Q9O6ooFxq50DayCdm0QrDgZjMUn23z/0PMZlgft7Yp5Q==" crossorigin="anonymous" /> <style> body { background: #f4f4f5; color: #020202; } .navbar-dark { background-image: -webkit-linear-gradient(top, #005f85 0, #002e49 100%); background-image: -o-linear-gradient(top, #005f85 0, #002e49 100%); background-image: linear-gradient(to bottom, #005f85 0, #002e49 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff005f85', endColorstr='#ff002e49', GradientType=0); background-repeat: repeat-x; } .navbar-dark .navbar-nav .nav-link, .navbar-dark .navbar-nav .nav-link:focus { color: #fff } .navbar-dark .navbar-nav .nav-link:hover { color: #ffef68 } #wrapperlicious { margin: 0 auto; font: 0.9em 'Helvetica Neue', Helvetica, sans-serif; font-weight: normal; line-height: 1.5em; margin: 0; padding: 0; } #wrapperlicious h1 { font-size: 1.5em } #wrapperlicious h2 { font-size: 1.3em } #wrapperlicious h3 { font-size: 1.1em } #wrapperlicious h4 { font-size: 0.9em } #wrapperlicious h1, #wrapperlicious h2, #wrapperlicious h3, #wrapperlicious h4, #wrapperlicious dt { color: #020202; margin-top: 1em; margin-bottom: 1em; position: relative; font-weight: bold; } #wrapperlicious a { color: inherit; text-decoration: underline } #wrapperlicious #toc { text-decoration: none } #wrapperlicious a:hover { color: #2a2a2a } #wrapperlicious a img { border: 0 } #wrapperlicious :not(pre) > code { color: inherit; background-color: rgba(0, 0, 0, 0.04); border-radius: 3px; font: 0.9em Consolas, Menlo, Monaco, monospace; padding: 0.3em; } #wrapperlicious dd { margin: 0; margin-left: 2em; } #wrapperlicious dt { color: #2a2a2a; font-weight: bold; margin-left: 0.9em; } #wrapperlicious p { margin-bottom: 1em; margin-top: 1em; } #wrapperlicious li > p { margin-bottom: 0; margin-top: 0; } #wrapperlicious pre { border: 1px solid #c1c1c1; border-radius: 3px; font: 100% Consolas, Menlo, Monaco, monospace; margin-bottom: 1em; margin-top: 1em; } #wrapperlicious pre > code { display: block; background-color: #f6f6f6; font: 0.9em Consolas, Menlo, Monaco, monospace; line-height: 1.5em; text-align: left; white-space: pre; padding: 1em; } #wrapperlicious dl, #wrapperlicious ol, #wrapperlicious ul { margin-bottom: 1em; margin-top: 1em; } #wrapperlicious ul { list-style-type: square; } #wrapperlicious ul ul { margin-bottom: 0px; margin-top: 0px; } #footer { font-size: 0.8em; padding-top: 0.5em; text-align: center; } #more { display: inline; font-size: 0.8em; } #perldocdiv { background-color: #fff; border: 1px solid #c1c1c1; border-bottom-left-radius: 5px; border-bottom-right-radius: 5px; margin-left: auto; margin-right: auto; padding: 3em; padding-top: 1em; max-width: 960px; } #moduleversion { float: right } #wrapperlicious .leading-notice { font-style: italic; padding-left: 1em; margin-top: 1em; margin-bottom: 1em; } #wrapperlicious .permalink { display: none; left: -0.75em; position: absolute; padding-right: 0.25em; text-decoration: none; } #wrapperlicious h1:hover .permalink, #wrapperlicious h2:hover .permalink, #wrapperlicious h3:hover .permalink, #wrapperlicious h4:hover .permalink, #wrapperlicious dt:hover .permalink { display: block; } </style> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-KVNWBNT5FB"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-KVNWBNT5FB'); gtag('config', 'UA-50555-3'); </script> </head> <body> <nav class="navbar navbar-expand-md navbar-dark bg-dark justify-content-between"> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <a class="navbar-brand" href="/">Perldoc Browser</a> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav mr-auto"> <li class="nav-item dropdown text-nowrap"> <a class="nav-link dropdown-toggle" href="#" id="dropdownlink-stable" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">5.12.2</a> <div class="dropdown-menu" aria-labelledby="dropdownlink-stable"> <a class="dropdown-item" href="/Math::BigInt">Latest</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.40.0/Math::BigInt">5.40.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.38.2/Math::BigInt">5.38.2</a> <a class="dropdown-item" href="/5.38.1/Math::BigInt">5.38.1</a> <a class="dropdown-item" href="/5.38.0/Math::BigInt">5.38.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.36.3/Math::BigInt">5.36.3</a> <a class="dropdown-item" href="/5.36.2/Math::BigInt">5.36.2</a> <a class="dropdown-item" href="/5.36.1/Math::BigInt">5.36.1</a> <a class="dropdown-item" href="/5.36.0/Math::BigInt">5.36.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.34.3/Math::BigInt">5.34.3</a> <a class="dropdown-item" href="/5.34.2/Math::BigInt">5.34.2</a> <a class="dropdown-item" href="/5.34.1/Math::BigInt">5.34.1</a> <a class="dropdown-item" href="/5.34.0/Math::BigInt">5.34.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.32.1/Math::BigInt">5.32.1</a> <a class="dropdown-item" href="/5.32.0/Math::BigInt">5.32.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.30.3/Math::BigInt">5.30.3</a> <a class="dropdown-item" href="/5.30.2/Math::BigInt">5.30.2</a> <a class="dropdown-item" href="/5.30.1/Math::BigInt">5.30.1</a> <a class="dropdown-item" href="/5.30.0/Math::BigInt">5.30.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.28.3/Math::BigInt">5.28.3</a> <a class="dropdown-item" href="/5.28.2/Math::BigInt">5.28.2</a> <a class="dropdown-item" href="/5.28.1/Math::BigInt">5.28.1</a> <a class="dropdown-item" href="/5.28.0/Math::BigInt">5.28.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.26.3/Math::BigInt">5.26.3</a> <a class="dropdown-item" href="/5.26.2/Math::BigInt">5.26.2</a> <a class="dropdown-item" href="/5.26.1/Math::BigInt">5.26.1</a> <a class="dropdown-item" href="/5.26.0/Math::BigInt">5.26.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.24.4/Math::BigInt">5.24.4</a> <a class="dropdown-item" href="/5.24.3/Math::BigInt">5.24.3</a> <a class="dropdown-item" href="/5.24.2/Math::BigInt">5.24.2</a> <a class="dropdown-item" href="/5.24.1/Math::BigInt">5.24.1</a> <a class="dropdown-item" href="/5.24.0/Math::BigInt">5.24.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.22.4/Math::BigInt">5.22.4</a> <a class="dropdown-item" href="/5.22.3/Math::BigInt">5.22.3</a> <a class="dropdown-item" href="/5.22.2/Math::BigInt">5.22.2</a> <a class="dropdown-item" href="/5.22.1/Math::BigInt">5.22.1</a> <a class="dropdown-item" href="/5.22.0/Math::BigInt">5.22.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.20.3/Math::BigInt">5.20.3</a> <a class="dropdown-item" href="/5.20.2/Math::BigInt">5.20.2</a> <a class="dropdown-item" href="/5.20.1/Math::BigInt">5.20.1</a> <a class="dropdown-item" href="/5.20.0/Math::BigInt">5.20.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.18.4/Math::BigInt">5.18.4</a> <a class="dropdown-item" href="/5.18.3/Math::BigInt">5.18.3</a> <a class="dropdown-item" href="/5.18.2/Math::BigInt">5.18.2</a> <a class="dropdown-item" href="/5.18.1/Math::BigInt">5.18.1</a> <a class="dropdown-item" href="/5.18.0/Math::BigInt">5.18.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.16.3/Math::BigInt">5.16.3</a> <a class="dropdown-item" href="/5.16.2/Math::BigInt">5.16.2</a> <a class="dropdown-item" href="/5.16.1/Math::BigInt">5.16.1</a> <a class="dropdown-item" href="/5.16.0/Math::BigInt">5.16.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.14.4/Math::BigInt">5.14.4</a> <a class="dropdown-item" href="/5.14.3/Math::BigInt">5.14.3</a> <a class="dropdown-item" href="/5.14.2/Math::BigInt">5.14.2</a> <a class="dropdown-item" href="/5.14.1/Math::BigInt">5.14.1</a> <a class="dropdown-item" href="/5.14.0/Math::BigInt">5.14.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.12.5/Math::BigInt">5.12.5</a> <a class="dropdown-item" href="/5.12.4/Math::BigInt">5.12.4</a> <a class="dropdown-item" href="/5.12.3/Math::BigInt">5.12.3</a> <a class="dropdown-item active" href="/5.12.2/Math::BigInt">5.12.2</a> <a class="dropdown-item" href="/5.12.1/Math::BigInt">5.12.1</a> <a class="dropdown-item" href="/5.12.0/Math::BigInt">5.12.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.10.1/Math::BigInt">5.10.1</a> <a class="dropdown-item" href="/5.10.0/Math::BigInt">5.10.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.8.9/Math::BigInt">5.8.9</a> <a class="dropdown-item" href="/5.8.8/Math::BigInt">5.8.8</a> <a class="dropdown-item" href="/5.8.7/Math::BigInt">5.8.7</a> <a class="dropdown-item" href="/5.8.6/Math::BigInt">5.8.6</a> <a class="dropdown-item" href="/5.8.5/Math::BigInt">5.8.5</a> <a class="dropdown-item" href="/5.8.4/Math::BigInt">5.8.4</a> <a class="dropdown-item" href="/5.8.3/Math::BigInt">5.8.3</a> <a class="dropdown-item" href="/5.8.2/Math::BigInt">5.8.2</a> <a class="dropdown-item" href="/5.8.1/Math::BigInt">5.8.1</a> <a class="dropdown-item" href="/5.8.0/Math::BigInt">5.8.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.6.2/Math::BigInt">5.6.2</a> <a class="dropdown-item" href="/5.6.1/Math::BigInt">5.6.1</a> <a class="dropdown-item" href="/5.6.0/Math::BigInt">5.6.0</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.005_04/Math::BigInt">5.005_04</a> <a class="dropdown-item" href="/5.005_03/Math::BigInt">5.005_03</a> <a class="dropdown-item" href="/5.005_02/Math::BigInt">5.005_02</a> <a class="dropdown-item" href="/5.005_01/Math::BigInt">5.005_01</a> <a class="dropdown-item" href="/5.005/Math::BigInt">5.005</a> </div> </li> <li class="nav-item dropdown text-nowrap"> <a class="nav-link dropdown-toggle" href="#" id="dropdownlink-dev" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dev</a> <div class="dropdown-menu" aria-labelledby="dropdownlink-dev"> <a class="dropdown-item" href="/blead/Math::BigInt">blead</a> <a class="dropdown-item" href="/5.41.6/Math::BigInt">5.41.6</a> <a class="dropdown-item" href="/5.41.5/Math::BigInt">5.41.5</a> <a class="dropdown-item" href="/5.41.4/Math::BigInt">5.41.4</a> <a class="dropdown-item" href="/5.41.3/Math::BigInt">5.41.3</a> <a class="dropdown-item" href="/5.41.2/Math::BigInt">5.41.2</a> <a class="dropdown-item" href="/5.41.1/Math::BigInt">5.41.1</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.40.0-RC2/Math::BigInt">5.40.0-RC2</a> <a class="dropdown-item" href="/5.40.0-RC1/Math::BigInt">5.40.0-RC1</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.39.10/Math::BigInt">5.39.10</a> <a class="dropdown-item" href="/5.39.9/Math::BigInt">5.39.9</a> <a class="dropdown-item" href="/5.39.8/Math::BigInt">5.39.8</a> <a class="dropdown-item" href="/5.39.7/Math::BigInt">5.39.7</a> <a class="dropdown-item" href="/5.39.6/Math::BigInt">5.39.6</a> <a class="dropdown-item" href="/5.39.5/Math::BigInt">5.39.5</a> <a class="dropdown-item" href="/5.39.4/Math::BigInt">5.39.4</a> <a class="dropdown-item" href="/5.39.3/Math::BigInt">5.39.3</a> <a class="dropdown-item" href="/5.39.2/Math::BigInt">5.39.2</a> <a class="dropdown-item" href="/5.39.1/Math::BigInt">5.39.1</a> </div> </li> <li class="nav-item dropdown text-nowrap"> <a class="nav-link dropdown-toggle" href="#" id="dropdownlink-nav" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Documentation</a> <div class="dropdown-menu" aria-labelledby="dropdownlink-nav"> <a class="dropdown-item" href="/5.12.2/perl">Perl</a> <a class="dropdown-item" href="/5.12.2/perlintro">Intro</a> <a class="dropdown-item" href="/5.12.2/perl#Tutorials">Tutorials</a> <a class="dropdown-item" href="/5.12.2/perlfaq">FAQs</a> <a class="dropdown-item" href="/5.12.2/perl#Reference-Manual">Reference</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.12.2/perlop">Operators</a> <a class="dropdown-item" href="/5.12.2/functions">Functions</a> <a class="dropdown-item" href="/5.12.2/variables">Variables</a> <a class="dropdown-item" href="/5.12.2/modules">Modules</a> <a class="dropdown-item" href="/5.12.2/perlutil">Utilities</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="/5.12.2/perldelta">Release Notes</a> <a class="dropdown-item" href="/5.12.2/perlcommunity">Community</a> <a class="dropdown-item" href="/5.12.2/perlhist">History</a> </div> </li> </ul> <ul class="navbar-nav"> <script> function set_expand (expand) { var perldocdiv = document.getElementById('perldocdiv'); var width = window.getComputedStyle(perldocdiv).getPropertyValue('max-width'); var expanded = (width == '' || width == 'none') ? true : false; if (expand === null) { expand = !expanded; } if ((expand && !expanded) || (!expand && expanded)) { perldocdiv.style.setProperty('max-width', expand ? 'none' : '960px'); var button_classlist = document.getElementById('content-expand-button').classList; if (expand) { button_classlist.add('btn-light'); button_classlist.remove('btn-outline-light'); } else { button_classlist.add('btn-outline-light'); button_classlist.remove('btn-light'); } } return expand; } function toggle_expand () { var expand = set_expand(null); document.cookie = 'perldoc_expand=' + (expand ? 1 : 0) + '; path=/; expires=Tue, 19 Jan 2038 03:14:07 UTC'; } function read_expand () { return document.cookie.split(';').some(function (item) { return item.indexOf('perldoc_expand=1') >= 0 }); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', function () { if (read_expand()) { set_expand(true); } }); } else if (read_expand()) { set_expand(true); } </script> <button id="content-expand-button" type="button" class="btn btn-outline-light d-none d-lg-inline-block mr-4" onclick="toggle_expand()">Expand</button> </ul> <form class="form-inline" method="get" action="/5.12.2/search"> <input class="form-control mr-3" type="search" name="q" placeholder="Search" aria-label="Search" value=""> </form> </div> </nav> <div id="wrapperlicious" class="container-fluid"> <div id="perldocdiv"> <div id="links"> <a href="/5.12.2/Math::BigInt">Math::BigInt</a> <div id="more"> (<a href="/5.12.2/Math::BigInt.txt">source</a>, <a href="https://metacpan.org/pod/Math::BigInt">CPAN</a>) </div> <div id="moduleversion">version 1.89_01</div> </div> <div class="leading-notice"> You are viewing the version of this documentation from Perl 5.12.2. <a href="/Math::BigInt">View the latest version</a> </div> <h1><a id="toc">CONTENTS</a></h1> <ul> <li> <a class="text-decoration-none" href="#NAME">NAME</a> </li> <li> <a class="text-decoration-none" href="#SYNOPSIS">SYNOPSIS</a> </li> <li> <a class="text-decoration-none" href="#DESCRIPTION">DESCRIPTION</a> </li> <li> <a class="text-decoration-none" href="#METHODS">METHODS</a> <ul> <li> <a class="text-decoration-none" href="#config()">config()</a> </li> <li> <a class="text-decoration-none" href="#accuracy()">accuracy()</a> </li> <li> <a class="text-decoration-none" href="#precision()">precision()</a> </li> <li> <a class="text-decoration-none" href="#brsft()">brsft()</a> </li> <li> <a class="text-decoration-none" href="#new()">new()</a> </li> <li> <a class="text-decoration-none" href="#from_oct()">from_oct()</a> </li> <li> <a class="text-decoration-none" href="#from_hex()">from_hex()</a> </li> <li> <a class="text-decoration-none" href="#from_bin()">from_bin()</a> </li> <li> <a class="text-decoration-none" href="#bnan()">bnan()</a> </li> <li> <a class="text-decoration-none" href="#bzero()">bzero()</a> </li> <li> <a class="text-decoration-none" href="#binf()">binf()</a> </li> <li> <a class="text-decoration-none" href="#bone()">bone()</a> </li> <li> <a class="text-decoration-none" href="#is_one()/is_zero()/is_nan()/is_inf()">is_one()/is_zero()/is_nan()/is_inf()</a> </li> <li> <a class="text-decoration-none" href="#is_pos()/is_neg()/is_positive()/is_negative()">is_pos()/is_neg()/is_positive()/is_negative()</a> </li> <li> <a class="text-decoration-none" href="#is_odd()/is_even()/is_int()">is_odd()/is_even()/is_int()</a> </li> <li> <a class="text-decoration-none" href="#bcmp()">bcmp()</a> </li> <li> <a class="text-decoration-none" href="#bacmp()">bacmp()</a> </li> <li> <a class="text-decoration-none" href="#sign()">sign()</a> </li> <li> <a class="text-decoration-none" href="#digit()">digit()</a> </li> <li> <a class="text-decoration-none" href="#bneg()">bneg()</a> </li> <li> <a class="text-decoration-none" href="#babs()">babs()</a> </li> <li> <a class="text-decoration-none" href="#bnorm()">bnorm()</a> </li> <li> <a class="text-decoration-none" href="#bnot()">bnot()</a> </li> <li> <a class="text-decoration-none" href="#binc()">binc()</a> </li> <li> <a class="text-decoration-none" href="#bdec()">bdec()</a> </li> <li> <a class="text-decoration-none" href="#badd()">badd()</a> </li> <li> <a class="text-decoration-none" href="#bsub()">bsub()</a> </li> <li> <a class="text-decoration-none" href="#bmul()">bmul()</a> </li> <li> <a class="text-decoration-none" href="#bmuladd()">bmuladd()</a> </li> <li> <a class="text-decoration-none" href="#bdiv()">bdiv()</a> </li> <li> <a class="text-decoration-none" href="#bmod()">bmod()</a> </li> <li> <a class="text-decoration-none" href="#bmodinv()">bmodinv()</a> </li> <li> <a class="text-decoration-none" href="#bmodpow()">bmodpow()</a> </li> <li> <a class="text-decoration-none" href="#bpow()">bpow()</a> </li> <li> <a class="text-decoration-none" href="#blog()">blog()</a> </li> <li> <a class="text-decoration-none" href="#bexp()">bexp()</a> </li> <li> <a class="text-decoration-none" href="#bnok()">bnok()</a> </li> <li> <a class="text-decoration-none" href="#bpi()">bpi()</a> </li> <li> <a class="text-decoration-none" href="#bcos()">bcos()</a> </li> <li> <a class="text-decoration-none" href="#bsin()">bsin()</a> </li> <li> <a class="text-decoration-none" href="#batan2()">batan2()</a> </li> <li> <a class="text-decoration-none" href="#batan()">batan()</a> </li> <li> <a class="text-decoration-none" href="#blsft()">blsft()</a> </li> <li> <a class="text-decoration-none" href="#brsft()1">brsft()</a> </li> <li> <a class="text-decoration-none" href="#band()">band()</a> </li> <li> <a class="text-decoration-none" href="#bior()">bior()</a> </li> <li> <a class="text-decoration-none" href="#bxor()">bxor()</a> </li> <li> <a class="text-decoration-none" href="#bnot()1">bnot()</a> </li> <li> <a class="text-decoration-none" href="#bsqrt()">bsqrt()</a> </li> <li> <a class="text-decoration-none" href="#broot()">broot()</a> </li> <li> <a class="text-decoration-none" href="#bfac()">bfac()</a> </li> <li> <a class="text-decoration-none" href="#round()">round()</a> </li> <li> <a class="text-decoration-none" href="#bround()">bround()</a> </li> <li> <a class="text-decoration-none" href="#bfround()">bfround()</a> </li> <li> <a class="text-decoration-none" href="#bfloor()">bfloor()</a> </li> <li> <a class="text-decoration-none" href="#bceil()">bceil()</a> </li> <li> <a class="text-decoration-none" href="#bgcd()">bgcd()</a> </li> <li> <a class="text-decoration-none" href="#blcm()">blcm()</a> </li> <li> <a class="text-decoration-none" href="#exponent()">exponent()</a> </li> <li> <a class="text-decoration-none" href="#mantissa()">mantissa()</a> </li> <li> <a class="text-decoration-none" href="#parts()">parts()</a> </li> <li> <a class="text-decoration-none" href="#copy()">copy()</a> </li> <li> <a class="text-decoration-none" href="#as_int()/as_number()">as_int()/as_number()</a> </li> <li> <a class="text-decoration-none" href="#bstr()">bstr()</a> </li> <li> <a class="text-decoration-none" href="#bsstr()">bsstr()</a> </li> <li> <a class="text-decoration-none" href="#as_hex()">as_hex()</a> </li> <li> <a class="text-decoration-none" href="#as_bin()">as_bin()</a> </li> <li> <a class="text-decoration-none" href="#as_oct()">as_oct()</a> </li> <li> <a class="text-decoration-none" href="#numify()">numify()</a> </li> <li> <a class="text-decoration-none" href="#modify()">modify()</a> </li> <li> <a class="text-decoration-none" href="#upgrade()/downgrade()">upgrade()/downgrade()</a> </li> <li> <a class="text-decoration-none" href="#div_scale()">div_scale()</a> </li> <li> <a class="text-decoration-none" href="#round_mode()">round_mode()</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#ACCURACY-and-PRECISION">ACCURACY and PRECISION</a> <ul> <li> <a class="text-decoration-none" href="#Precision-P">Precision P</a> </li> <li> <a class="text-decoration-none" href="#Accuracy-A">Accuracy A</a> </li> <li> <a class="text-decoration-none" href="#Fallback-F">Fallback F</a> </li> <li> <a class="text-decoration-none" href="#Rounding-mode-R">Rounding mode R</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#Infinity-and-Not-a-Number">Infinity and Not a Number</a> </li> <li> <a class="text-decoration-none" href="#INTERNALS">INTERNALS</a> <ul> <li> <a class="text-decoration-none" href="#MATH-LIBRARY">MATH LIBRARY</a> <ul> <li> <a class="text-decoration-none" href="#What-library-to-use?">What library to use?</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#SIGN">SIGN</a> </li> <li> <a class="text-decoration-none" href="#mantissa(),-exponent()-and-parts()">mantissa(), exponent() and parts()</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#EXAMPLES">EXAMPLES</a> </li> <li> <a class="text-decoration-none" href="#Autocreating-constants">Autocreating constants</a> </li> <li> <a class="text-decoration-none" href="#PERFORMANCE">PERFORMANCE</a> <ul> <li> <a class="text-decoration-none" href="#Alternative-math-libraries">Alternative math libraries</a> </li> <li> <a class="text-decoration-none" href="#SUBCLASSING">SUBCLASSING</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#Subclassing-Math::BigInt">Subclassing Math::BigInt</a> </li> <li> <a class="text-decoration-none" href="#UPGRADING">UPGRADING</a> <ul> <li> <a class="text-decoration-none" href="#Auto-upgrade">Auto-upgrade</a> </li> </ul> </li> <li> <a class="text-decoration-none" href="#EXPORTS">EXPORTS</a> </li> <li> <a class="text-decoration-none" href="#CAVEATS">CAVEATS</a> </li> <li> <a class="text-decoration-none" href="#LICENSE">LICENSE</a> </li> <li> <a class="text-decoration-none" href="#SEE-ALSO">SEE ALSO</a> </li> <li> <a class="text-decoration-none" href="#AUTHORS">AUTHORS</a> </li> </ul> <h1 id="NAME"><a class="permalink" href="#NAME">#</a>NAME</h1> <p>Math::BigInt - Arbitrary size integer/float math package</p> <h1 id="SYNOPSIS"><a class="permalink" href="#SYNOPSIS">#</a>SYNOPSIS</h1> <pre><code class="nohighlight"> use Math::BigInt; # or make it faster with huge numbers: install (optional) # Math::BigInt::GMP and always use (it will fall back to # pure Perl if the GMP library is not installed): # (See also the L<MATH LIBRARY> section!) # will warn if Math::BigInt::GMP cannot be found use Math::BigInt lib => 'GMP'; # to supress 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 = '-'; # Number creation my $x = Math::BigInt->new($str); # defaults to 0 my $y = $x->copy(); # make a true copy my $nan = Math::BigInt->bnan(); # create a NotANumber my $zero = Math::BigInt->bzero(); # create a +0 my $inf = Math::BigInt->binf(); # create a +inf my $inf = Math::BigInt->binf('-'); # create a -inf my $one = Math::BigInt->bone(); # create a +1 my $mone = Math::BigInt->bone('-'); # create a -1 my $pi = Math::BigInt->bpi(); # returns '3' # see Math::BigFloat::bpi() $h = Math::BigInt->new('0x123'); # from hexadecimal $b = Math::BigInt->new('0b101'); # from binary $o = Math::BigInt->from_oct('0101'); # from octal # Testing (don't modify their arguments) # (return true if the condition is met, otherwise false) $x->is_zero(); # if $x is +0 $x->is_nan(); # if $x is NaN $x->is_one(); # if $x is +1 $x->is_one('-'); # if $x is -1 $x->is_odd(); # if $x is odd $x->is_even(); # if $x is even $x->is_pos(); # if $x >= 0 $x->is_neg(); # if $x < 0 $x->is_inf($sign); # if $x is +inf, or -inf (sign is default '+') $x->is_int(); # if $x is an integer (not a float) # comparing and digit/sign extraction $x->bcmp($y); # compare numbers (undef,<0,=0,>0) $x->bacmp($y); # compare absolutely (undef,<0,=0,>0) $x->sign(); # return the sign, either +,- or NaN $x->digit($n); # return the nth digit, counting from right $x->digit(-$n); # return the nth digit, counting from left # The following all modify their first argument. If you want to preserve # $x, use $z = $x->copy()->bXXX($y); See under L<CAVEATS> for why this is # necessary when mixing $a = $b assignments with non-overloaded math. $x->bzero(); # set $x to 0 $x->bnan(); # set $x to NaN $x->bone(); # set $x to +1 $x->bone('-'); # set $x to -1 $x->binf(); # set $x to inf $x->binf('-'); # set $x to -inf $x->bneg(); # negation $x->babs(); # absolute value $x->bnorm(); # normalize (no-op in BigInt) $x->bnot(); # two's complement (bit wise not) $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->bdiv($y); # divide, set $x to quotient # return (quo,rem) or quo if scalar $x->bmuladd($y,$z); # $x = $x * $y + $z $x->bmod($y); # modulus (x % y) $x->bmodpow($exp,$mod); # modular exponentation (($num**$exp) % $mod)) $x->bmodinv($mod); # the inverse of $x in the given modulus $mod $x->bpow($y); # power of arguments (x ** y) $x->blsft($y); # left shift in base 2 $x->brsft($y); # right shift in base 2 # returns (quo,rem) or quo if in scalar context $x->blsft($y,$n); # left shift by $y places in base $n $x->brsft($y,$n); # right shift by $y places in base $n # returns (quo,rem) or quo if in scalar context $x->band($y); # bitwise and $x->bior($y); # bitwise inclusive or $x->bxor($y); # bitwise exclusive or $x->bnot(); # bitwise not (two's complement) $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->bnok($y); # x over y (binomial coefficient n over k) $x->blog(); # logarithm of $x to base e (Euler's number) $x->blog($base); # logarithm of $x to base $base (f.i. 2) $x->bexp(); # calculate e ** $x where e is Euler's number $x->round($A,$P,$mode); # round to accuracy or precision using mode $mode $x->bround($n); # accuracy: preserve $n digits $x->bfround($n); # $n > 0: round $nth digits, # $n < 0: round to the $nth digit after the # dot, no-op for BigInts # The following do not modify their arguments in BigInt (are no-ops), # but do so in BigFloat: $x->bfloor(); # return integer less or equal than $x $x->bceil(); # return integer greater or equal than $x # The following do not modify their arguments: # greatest common divisor (no OO style) my $gcd = Math::BigInt::bgcd(@values); # lowest common multiplicator (no OO style) my $lcm = Math::BigInt::blcm(@values); $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 BigInts $x->exponent(); # return exponent as BigInt $x->mantissa(); # return (signed) mantissa as BigInt $x->parts(); # return (mantissa,exponent) as BigInt $x->copy(); # make a true copy of $x (unlike $y = $x;) $x->as_int(); # return as BigInt (in BigInt: same as copy()) $x->numify(); # return as scalar (might overflow!) # conversation to string (do not modify their argument) $x->bstr(); # normalized string (e.g. '3') $x->bsstr(); # norm. string in scientific notation (e.g. '3E0') $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 # precision and accuracy (see section about rounding for more) $x->precision(); # return P of $x (or global, if P of $x undef) $x->precision($n); # set P of $x to $n $x->accuracy(); # return A of $x (or global, if A of $x undef) $x->accuracy($n); # set A $x to $n # Global methods Math::BigInt->precision(); # get/set global P for all BigInt objects Math::BigInt->accuracy(); # get/set global A for all BigInt objects Math::BigInt->round_mode(); # get/set global round mode, one of # 'even', 'odd', '+inf', '-inf', 'zero', 'trunc' or 'common' Math::BigInt->config(); # return hash containing configuration</code></pre> <h1 id="DESCRIPTION"><a class="permalink" href="#DESCRIPTION">#</a>DESCRIPTION</h1> <p>All operators (including basic math operations) are overloaded if you declare your big integers as</p> <pre><code>$i = new Math::BigInt '123_456_789_123_456_789';</code></pre> <p>Operations with overloaded operators preserve the arguments which is exactly what you expect.</p> <dl> <dt id="Input"><a class="permalink" href="#Input">#</a>Input</dt> <dd> <p>Input values to these routines may be any string, that looks like a number and results in an integer, including hexadecimal and binary numbers.</p> <p>Scalars holding numbers may also be passed, but note that non-integer numbers may already have lost precision due to the conversation to float. Quote your input if you want BigInt to see all the digits:</p> <pre><code>$x = Math::BigInt->new(12345678890123456789); # bad $x = Math::BigInt->new('12345678901234567890'); # good</code></pre> <p>You can include one underscore between any two digits.</p> <p>This means integer values like 1.01E2 or even 1000E-2 are also accepted. Non-integer values result in NaN.</p> <p>Hexadecimal (prefixed with "0x") and binary numbers (prefixed with "0b") are accepted, too. Please note that octal numbers are not recognized by new(), so the following will print "123":</p> <pre><code>perl -MMath::BigInt -le 'print Math::BigInt->new("0123")'</code></pre> <p>To convert an octal number, use from_oct();</p> <pre><code>perl -MMath::BigInt -le 'print Math::BigInt->from_oct("0123")'</code></pre> <p>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:</p> <pre><code>$zero = Math::BigInt->bzero(); $nan = Math::BigInt->bnan(); </code></pre> <p><code>bnorm()</code> on a BigInt object is now effectively a no-op, since the numbers are always stored in normalized form. If passed a string, creates a BigInt object from the input.</p> </dd> <dt id="Output"><a class="permalink" href="#Output">#</a>Output</dt> <dd> <p>Output values are BigInt objects (normalized), except for the methods which return a string (see <a href="/5.12.2/SYNOPSIS">SYNOPSIS</a>).</p> <p>Some routines (<code>is_odd()</code>, <code>is_even()</code>, <code>is_zero()</code>, <code>is_one()</code>, <code>is_nan()</code>, etc.) return true or false, while others (<code>bcmp()</code>, <code>bacmp()</code>) return either undef (if NaN is involved), <0, 0 or >0 and are suited for sort.</p> </dd> </dl> <h1 id="METHODS"><a class="permalink" href="#METHODS">#</a>METHODS</h1> <p>Each of the methods below (except config(), accuracy() and precision()) accepts three additional parameters. These arguments <code>$A</code>, <code>$P</code> and <code>$R</code> are <code>accuracy</code>, <code>precision</code> and <code>round_mode</code>. Please see the section about <a href="#ACCURACY-and-PRECISION">"ACCURACY and PRECISION"</a> for more information.</p> <h2 id="config()"><a class="permalink" href="#config()">#</a><a id="config"></a>config()</h2> <pre><code>use Data::Dumper; print Dumper ( Math::BigInt->config() ); print Math::BigInt->config()->{lib},"\n";</code></pre> <p>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.</p> <pre><code class="plaintext">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</code></pre> <p>The following values can be set by passing <code>config()</code> a reference to a hash:</p> <pre><code class="plaintext"> trap_inf trap_nan upgrade downgrade precision accuracy round_mode div_scale</code></pre> <p>Example:</p> <pre><code>$new_cfg = Math::BigInt->config( { trap_inf => 1, precision => 5 } );</code></pre> <h2 id="accuracy()"><a class="permalink" href="#accuracy()">#</a><a id="accuracy"></a>accuracy()</h2> <pre><code>$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</code></pre> <p>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()!</p> <p>Warning! The accuracy <i>sticks</i>, e.g. once you created a number under the influence of <code>CLASS->accuracy($A)</code>, all results from math operations with that number will also be rounded.</p> <p>In most cases, you should probably round the results explicitly using one of <a href="/5.12.2/round()">round()</a>, <a href="/5.12.2/bround()">bround()</a> or <a href="/5.12.2/bfround()">bfround()</a> or by passing the desired accuracy to the math operation as additional parameter:</p> <pre><code>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</code></pre> <p>Please see the section about <a href="#ACCURACY-AND-PRECISION">"ACCURACY AND PRECISION"</a> for further details.</p> <p>Value must be greater than zero. Pass an undef value to disable it:</p> <pre><code>$x->accuracy(undef); Math::BigInt->accuracy(undef);</code></pre> <p>Returns the current accuracy. For <code>$x-</code>accuracy()> it will return either the local accuracy, or if not defined, the global. This means the return value represents the accuracy that will be in effect for $x:</p> <pre><code>$y = Math::BigInt->new(1234567); # unrounded print Math::BigInt->accuracy(4),"\n"; # set 4, print 4 $x = Math::BigInt->new(123456); # $x will be automatically rounded! print "$x $y\n"; # '123500 1234567' print $x->accuracy(),"\n"; # will be 4 print $y->accuracy(),"\n"; # also 4, since global is 4 print Math::BigInt->accuracy(5),"\n"; # set to 5, print 5 print $x->accuracy(),"\n"; # still 4 print $y->accuracy(),"\n"; # 5, since global is 5</code></pre> <p>Note: Works also for subclasses like Math::BigFloat. 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.</p> <h2 id="precision()"><a class="permalink" href="#precision()">#</a><a id="precision"></a>precision()</h2> <pre><code>$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</code></pre> <p>Note: You probably want to use <a href="/5.12.2/accuracy()">accuracy()</a> instead. With <a href="/5.12.2/accuracy">accuracy</a> you set the number of digits each result should have, with <a href="/5.12.2/precision">precision</a> you set the place where to round!</p> <p><code>precision()</code> sets or gets the global or local precision, aka at which digit before or after the dot to round all results. A set global precision also applies to all newly created numbers!</p> <p>In Math::BigInt, passing a negative number precision has no effect since no numbers have digits after the dot. In <a href="/5.12.2/Math::BigFloat">Math::BigFloat</a>, it will round all results to P digits after the dot.</p> <p>Please see the section about <a href="#ACCURACY-AND-PRECISION">"ACCURACY AND PRECISION"</a> for further details.</p> <p>Pass an undef value to disable it:</p> <pre><code>$x->precision(undef); Math::BigInt->precision(undef);</code></pre> <p>Returns the current precision. For <code>$x-</code>precision()> it will return either the local precision of $x, or if not defined, the global. This means the return value represents the prevision that will be in effect for $x:</p> <pre><code>$y = Math::BigInt->new(1234567); # unrounded print Math::BigInt->precision(4),"\n"; # set 4, print 4 $x = Math::BigInt->new(123456); # will be automatically rounded print $x; # print "120000"!</code></pre> <p>Note: Works also for subclasses like <a href="/5.12.2/Math::BigFloat">Math::BigFloat</a>. 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.</p> <h2 id="brsft()"><a class="permalink" href="#brsft()">#</a><a id="brsft"></a>brsft()</h2> <pre><code>$x->brsft($y,$n); </code></pre> <p>Shifts $x right by $y in base $n. Default is base 2, used are usually 10 and 2, but others work, too.</p> <p>Right shifting usually amounts to dividing $x by $n ** $y and truncating the result:</p> <pre><code>$x = Math::BigInt->new(10); $x->brsft(1); # same as $x >> 1: 5 $x = Math::BigInt->new(1234); $x->brsft(2,10); # result 12</code></pre> <p>There is one exception, and that is base 2 with negative $x:</p> <pre><code>$x = Math::BigInt->new(-5); print $x->brsft(1);</code></pre> <p>This will print -3, not -2 (as it would if you divide -5 by 2 and truncate the result).</p> <h2 id="new()"><a class="permalink" href="#new()">#</a><a id="new"></a>new()</h2> <pre><code>$x = Math::BigInt->new($str,$A,$P,$R);</code></pre> <p>Creates a new BigInt object from a scalar or another BigInt object. The input is accepted as decimal, hex (with leading '0x') or binary (with leading '0b').</p> <p>See <a href="/5.12.2/Input">Input</a> for more info on accepted input formats.</p> <h2 id="from_oct()"><a class="permalink" href="#from_oct()">#</a><a id="from_oct"></a>from_oct()</h2> <pre><code>$x = Math::BigInt->from_oct("0775"); # input is octal</code></pre> <h2 id="from_hex()"><a class="permalink" href="#from_hex()">#</a><a id="from_hex"></a>from_hex()</h2> <pre><code>$x = Math::BigInt->from_hex("0xcafe"); # input is hexadecimal</code></pre> <h2 id="from_bin()"><a class="permalink" href="#from_bin()">#</a><a id="from_bin"></a>from_bin()</h2> <pre><code>$x = Math::BigInt->from_oct("0x10011"); # input is binary</code></pre> <h2 id="bnan()"><a class="permalink" href="#bnan()">#</a><a id="bnan"></a>bnan()</h2> <pre><code>$x = Math::BigInt->bnan();</code></pre> <p>Creates a new BigInt object representing NaN (Not A Number). If used on an object, it will set it to NaN:</p> <pre><code>$x->bnan();</code></pre> <h2 id="bzero()"><a class="permalink" href="#bzero()">#</a><a id="bzero"></a>bzero()</h2> <pre><code>$x = Math::BigInt->bzero();</code></pre> <p>Creates a new BigInt object representing zero. If used on an object, it will set it to zero:</p> <pre><code>$x->bzero();</code></pre> <h2 id="binf()"><a class="permalink" href="#binf()">#</a><a id="binf"></a>binf()</h2> <pre><code>$x = Math::BigInt->binf($sign);</code></pre> <p>Creates a new BigInt 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:</p> <pre><code>$x->binf(); $x->binf('-');</code></pre> <h2 id="bone()"><a class="permalink" href="#bone()">#</a><a id="bone"></a>bone()</h2> <pre><code>$x = Math::BigInt->binf($sign);</code></pre> <p>Creates a new BigInt 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:</p> <pre><code>$x->bone(); # +1 $x->bone('-'); # -1</code></pre> <h2 id="is_one()/is_zero()/is_nan()/is_inf()"><a class="permalink" href="#is_one()/is_zero()/is_nan()/is_inf()">#</a><a id="is_one"></a><a id="is_one-is_zero-is_nan-is_inf"></a>is_one()/is_zero()/is_nan()/is_inf()</h2> <pre><code>$x->is_zero(); # true if arg is +0 $x->is_nan(); # true if arg is NaN $x->is_one(); # true if arg is +1 $x->is_one('-'); # true if arg is -1 $x->is_inf(); # true if +inf $x->is_inf('-'); # true if -inf (sign is default '+')</code></pre> <p>These methods all test the BigInt for being one specific value and return true or false depending on the input. These are faster than doing something like:</p> <pre><code>if ($x == 0)</code></pre> <h2 id="is_pos()/is_neg()/is_positive()/is_negative()"><a class="permalink" href="#is_pos()/is_neg()/is_positive()/is_negative()">#</a><a id="is_pos"></a><a id="is_pos-is_neg-is_positive-is_negative"></a>is_pos()/is_neg()/is_positive()/is_negative()</h2> <pre><code>$x->is_pos(); # true if > 0 $x->is_neg(); # true if < 0</code></pre> <p>The methods return true if the argument is positive or negative, respectively. <code>NaN</code> is neither positive nor negative, while <code>+inf</code> counts as positive, and <code>-inf</code> is negative. A <code>zero</code> is neither positive nor negative.</p> <p>These methods are only testing the sign, and not the value.</p> <p><code>is_positive()</code> and <code>is_negative()</code> are aliases to <code>is_pos()</code> and <code>is_neg()</code>, respectively. <code>is_positive()</code> and <code>is_negative()</code> were introduced in v1.36, while <code>is_pos()</code> and <code>is_neg()</code> were only introduced in v1.68.</p> <h2 id="is_odd()/is_even()/is_int()"><a class="permalink" href="#is_odd()/is_even()/is_int()">#</a><a id="is_odd"></a><a id="is_odd-is_even-is_int"></a>is_odd()/is_even()/is_int()</h2> <pre><code>$x->is_odd(); # true if odd, false for even $x->is_even(); # true if even, false for odd $x->is_int(); # true if $x is an integer</code></pre> <p>The return true when the argument satisfies the condition. <code>NaN</code>, <code>+inf</code>, <code>-inf</code> are not integers and are neither odd nor even.</p> <p>In BigInt, all numbers except <code>NaN</code>, <code>+inf</code> and <code>-inf</code> are integers.</p> <h2 id="bcmp()"><a class="permalink" href="#bcmp()">#</a><a id="bcmp"></a>bcmp()</h2> <pre><code>$x->bcmp($y);</code></pre> <p>Compares $x with $y and takes the sign into account. Returns -1, 0, 1 or undef.</p> <h2 id="bacmp()"><a class="permalink" href="#bacmp()">#</a><a id="bacmp"></a>bacmp()</h2> <pre><code>$x->bacmp($y);</code></pre> <p>Compares $x with $y while ignoring their. Returns -1, 0, 1 or undef.</p> <h2 id="sign()"><a class="permalink" href="#sign()">#</a><a id="sign"></a>sign()</h2> <pre><code>$x->sign();</code></pre> <p>Return the sign, of $x, meaning either <code>+</code>, <code>-</code>, <code>-inf</code>, <code>+inf</code> or NaN.</p> <p>If you want $x to have a certain sign, use one of the following methods:</p> <pre><code>$x->babs(); # '+' $x->babs()->bneg(); # '-' $x->bnan(); # 'NaN' $x->binf(); # '+inf' $x->binf('-'); # '-inf'</code></pre> <h2 id="digit()"><a class="permalink" href="#digit()">#</a><a id="digit"></a>digit()</h2> <pre><code>$x->digit($n); # return the nth digit, counting from right</code></pre> <p>If <code>$n</code> is negative, returns the digit counting from left.</p> <h2 id="bneg()"><a class="permalink" href="#bneg()">#</a><a id="bneg"></a>bneg()</h2> <pre><code>$x->bneg();</code></pre> <p>Negate the number, e.g. change the sign between '+' and '-', or between '+inf' and '-inf', respectively. Does nothing for NaN or zero.</p> <h2 id="babs()"><a class="permalink" href="#babs()">#</a><a id="babs"></a>babs()</h2> <pre><code>$x->babs();</code></pre> <p>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.</p> <h2 id="bnorm()"><a class="permalink" href="#bnorm()">#</a><a id="bnorm"></a>bnorm()</h2> <pre><code>$x->bnorm(); # normalize (no-op)</code></pre> <h2 id="bnot()"><a class="permalink" href="#bnot()">#</a><a id="bnot"></a>bnot()</h2> <pre><code>$x->bnot(); </code></pre> <p>Two's complement (bitwise not). This is equivalent to</p> <pre><code>$x->binc()->bneg();</code></pre> <p>but faster.</p> <h2 id="binc()"><a class="permalink" href="#binc()">#</a><a id="binc"></a>binc()</h2> <pre><code>$x->binc(); # increment x by 1</code></pre> <h2 id="bdec()"><a class="permalink" href="#bdec()">#</a><a id="bdec"></a>bdec()</h2> <pre><code>$x->bdec(); # decrement x by 1</code></pre> <h2 id="badd()"><a class="permalink" href="#badd()">#</a><a id="badd"></a>badd()</h2> <pre><code>$x->badd($y); # addition (add $y to $x)</code></pre> <h2 id="bsub()"><a class="permalink" href="#bsub()">#</a><a id="bsub"></a>bsub()</h2> <pre><code>$x->bsub($y); # subtraction (subtract $y from $x)</code></pre> <h2 id="bmul()"><a class="permalink" href="#bmul()">#</a><a id="bmul"></a>bmul()</h2> <pre><code>$x->bmul($y); # multiplication (multiply $x by $y)</code></pre> <h2 id="bmuladd()"><a class="permalink" href="#bmuladd()">#</a><a id="bmuladd"></a>bmuladd()</h2> <pre><code>$x->bmuladd($y,$z);</code></pre> <p>Multiply $x by $y, and then add $z to the result,</p> <p>This method was added in v1.87 of Math::BigInt (June 2007).</p> <h2 id="bdiv()"><a class="permalink" href="#bdiv()">#</a><a id="bdiv1"></a>bdiv()</h2> <pre><code>$x->bdiv($y); # divide, set $x to quotient # return (quo,rem) or quo if scalar</code></pre> <h2 id="bmod()"><a class="permalink" href="#bmod()">#</a><a id="bmod"></a>bmod()</h2> <pre><code>$x->bmod($y); # modulus (x % y)</code></pre> <h2 id="bmodinv()"><a class="permalink" href="#bmodinv()">#</a><a id="bmodinv"></a>bmodinv()</h2> <pre><code>num->bmodinv($mod); # modular inverse</code></pre> <p>Returns the inverse of <code>$num</code> in the given modulus <code>$mod</code>. '<code>NaN</code>' is returned unless <code>$num</code> is relatively prime to <code>$mod</code>, i.e. unless <code>bgcd($num, $mod)==1</code>.</p> <h2 id="bmodpow()"><a class="permalink" href="#bmodpow()">#</a><a id="bmodpow"></a>bmodpow()</h2> <pre><code>$num->bmodpow($exp,$mod); # modular exponentation # ($num**$exp % $mod)</code></pre> <p>Returns the value of <code>$num</code> taken to the power <code>$exp</code> in the modulus <code>$mod</code> using binary exponentation. <code>bmodpow</code> is far superior to writing</p> <pre><code>$num ** $exp % $mod</code></pre> <p>because it is much faster - it reduces internal variables into the modulus whenever possible, so it operates on smaller numbers.</p> <p><code>bmodpow</code> also supports negative exponents.</p> <pre><code>bmodpow($num, -1, $mod)</code></pre> <p>is exactly equivalent to</p> <pre><code>bmodinv($num, $mod)</code></pre> <h2 id="bpow()"><a class="permalink" href="#bpow()">#</a><a id="bpow1"></a>bpow()</h2> <pre><code>$x->bpow($y); # power of arguments (x ** y)</code></pre> <h2 id="blog()"><a class="permalink" href="#blog()">#</a><a id="blog"></a>blog()</h2> <pre><code>$x->blog($base, $accuracy); # logarithm of x to the base $base</code></pre> <p>If <code>$base</code> is not defined, Euler's number (e) is used:</p> <pre><code>print $x->blog(undef, 100); # log(x) to 100 digits</code></pre> <h2 id="bexp()"><a class="permalink" href="#bexp()">#</a><a id="bexp"></a>bexp()</h2> <pre><code>$x->bexp($accuracy); # calculate e ** X</code></pre> <p>Calculates the expression <code>e ** $x</code> where <code>e</code> is Euler's number.</p> <p>This method was added in v1.82 of Math::BigInt (April 2007).</p> <p>See also <a href="/5.12.2/blog()">blog()</a>.</p> <h2 id="bnok()"><a class="permalink" href="#bnok()">#</a><a id="bnok"></a>bnok()</h2> <pre><code>$x->bnok($y); # x over y (binomial coefficient n over k)</code></pre> <p>Calculates the binomial coefficient n over k, also called the "choose" function. The result is equivalent to:</p> <pre><code class="plaintext">( n ) n! | - | = ------- ( k ) k!(n-k)!</code></pre> <p>This method was added in v1.84 of Math::BigInt (April 2007).</p> <h2 id="bpi()"><a class="permalink" href="#bpi()">#</a><a id="bpi"></a>bpi()</h2> <pre><code>print Math::BigInt->bpi(100), "\n"; # 3</code></pre> <p>Returns PI truncated to an integer, with the argument being ignored. This means under BigInt this always returns <code>3</code>.</p> <p>If upgrading is in effect, returns PI, rounded to N digits with the current rounding mode:</p> <pre><code>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....</code></pre> <p>This method was added in v1.87 of Math::BigInt (June 2007).</p> <h2 id="bcos()"><a class="permalink" href="#bcos()">#</a><a id="bcos"></a>bcos()</h2> <pre><code>my $x = Math::BigInt->new(1); print $x->bcos(100), "\n";</code></pre> <p>Calculate the cosinus of $x, modifying $x in place.</p> <p>In BigInt, unless upgrading is in effect, the result is truncated to an integer.</p> <p>This method was added in v1.87 of Math::BigInt (June 2007).</p> <h2 id="bsin()"><a class="permalink" href="#bsin()">#</a><a id="bsin"></a>bsin()</h2> <pre><code>my $x = Math::BigInt->new(1); print $x->bsin(100), "\n";</code></pre> <p>Calculate the sinus of $x, modifying $x in place.</p> <p>In BigInt, unless upgrading is in effect, the result is truncated to an integer.</p> <p>This method was added in v1.87 of Math::BigInt (June 2007).</p> <h2 id="batan2()"><a class="permalink" href="#batan2()">#</a><a id="batan2"></a>batan2()</h2> <pre><code>my $x = Math::BigInt->new(1); my $y = Math::BigInt->new(1); print $y->batan2($x), "\n";</code></pre> <p>Calculate the arcus tangens of <code>$y</code> divided by <code>$x</code>, modifying $y in place.</p> <p>In BigInt, unless upgrading is in effect, the result is truncated to an integer.</p> <p>This method was added in v1.87 of Math::BigInt (June 2007).</p> <h2 id="batan()"><a class="permalink" href="#batan()">#</a><a id="batan"></a>batan()</h2> <pre><code>my $x = Math::BigFloat->new(0.5); print $x->batan(100), "\n";</code></pre> <p>Calculate the arcus tangens of $x, modifying $x in place.</p> <p>In BigInt, unless upgrading is in effect, the result is truncated to an integer.</p> <p>This method was added in v1.87 of Math::BigInt (June 2007).</p> <h2 id="blsft()"><a class="permalink" href="#blsft()">#</a><a id="blsft"></a>blsft()</h2> <pre><code>$x->blsft($y); # left shift in base 2 $x->blsft($y,$n); # left shift, in base $n (like 10)</code></pre> <h2 id="brsft()1"><a class="permalink" href="#brsft()1">#</a><a id="brsft1"></a>brsft()</h2> <pre><code>$x->brsft($y); # right shift in base 2 $x->brsft($y,$n); # right shift, in base $n (like 10)</code></pre> <h2 id="band()"><a class="permalink" href="#band()">#</a><a id="band"></a>band()</h2> <pre><code>$x->band($y); # bitwise and</code></pre> <h2 id="bior()"><a class="permalink" href="#bior()">#</a><a id="bior"></a>bior()</h2> <pre><code>$x->bior($y); # bitwise inclusive or</code></pre> <h2 id="bxor()"><a class="permalink" href="#bxor()">#</a><a id="bxor"></a>bxor()</h2> <pre><code>$x->bxor($y); # bitwise exclusive or</code></pre> <h2 id="bnot()1"><a class="permalink" href="#bnot()1">#</a><a id="bnot1"></a>bnot()</h2> <pre><code>$x->bnot(); # bitwise not (two's complement)</code></pre> <h2 id="bsqrt()"><a class="permalink" href="#bsqrt()">#</a><a id="bsqrt"></a>bsqrt()</h2> <pre><code>$x->bsqrt(); # calculate square-root</code></pre> <h2 id="broot()"><a class="permalink" href="#broot()">#</a><a id="broot"></a>broot()</h2> <pre><code>$x->broot($N);</code></pre> <p>Calculates the N'th root of <code>$x</code>.</p> <h2 id="bfac()"><a class="permalink" href="#bfac()">#</a><a id="bfac"></a>bfac()</h2> <pre><code>$x->bfac(); # factorial of $x (1*2*3*4*..$x)</code></pre> <h2 id="round()"><a class="permalink" href="#round()">#</a><a id="round"></a>round()</h2> <pre><code>$x->round($A,$P,$round_mode);</code></pre> <p>Round $x to accuracy <code>$A</code> or precision <code>$P</code> using the round mode <code>$round_mode</code>.</p> <h2 id="bround()"><a class="permalink" href="#bround()">#</a><a id="bround"></a>bround()</h2> <pre><code>$x->bround($N); # accuracy: preserve $N digits</code></pre> <h2 id="bfround()"><a class="permalink" href="#bfround()">#</a><a id="bfround"></a>bfround()</h2> <pre><code>$x->bfround($N);</code></pre> <p>If N is > 0, rounds to the Nth digit from the left. If N < 0, rounds to the Nth digit after the dot. Since BigInts are integers, the case N < 0 is a no-op for them.</p> <p>Examples:</p> <pre><code class="plaintext">Input N Result =================================================== 123456.123456 3 123500 123456.123456 2 123450 123456.123456 -2 123456.12 123456.123456 -3 123456.123</code></pre> <h2 id="bfloor()"><a class="permalink" href="#bfloor()">#</a><a id="bfloor"></a>bfloor()</h2> <pre><code>$x->bfloor(); </code></pre> <p>Set $x to the integer less or equal than $x. This is a no-op in BigInt, but does change $x in BigFloat.</p> <h2 id="bceil()"><a class="permalink" href="#bceil()">#</a><a id="bceil"></a>bceil()</h2> <pre><code>$x->bceil();</code></pre> <p>Set $x to the integer greater or equal than $x. This is a no-op in BigInt, but does change $x in BigFloat.</p> <h2 id="bgcd()"><a class="permalink" href="#bgcd()">#</a><a id="bgcd"></a>bgcd()</h2> <pre><code>bgcd(@values); # greatest common divisor (no OO style)</code></pre> <h2 id="blcm()"><a class="permalink" href="#blcm()">#</a><a id="blcm"></a>blcm()</h2> <pre><code> blcm(@values); # lowest common multiplicator (no OO style) </code></pre> <p>head2 length()</p> <pre><code> $x->length(); ($xl,$fl) = $x->length();</code></pre> <p>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 BigInt's, the length of the fraction part will always be 0.</p> <h2 id="exponent()"><a class="permalink" href="#exponent()">#</a><a id="exponent"></a>exponent()</h2> <pre><code>$x->exponent();</code></pre> <p>Return the exponent of $x as BigInt.</p> <h2 id="mantissa()"><a class="permalink" href="#mantissa()">#</a><a id="mantissa"></a>mantissa()</h2> <pre><code>$x->mantissa();</code></pre> <p>Return the signed mantissa of $x as BigInt.</p> <h2 id="parts()"><a class="permalink" href="#parts()">#</a><a id="parts"></a>parts()</h2> <pre><code>$x->parts(); # return (mantissa,exponent) as BigInt</code></pre> <h2 id="copy()"><a class="permalink" href="#copy()">#</a><a id="copy"></a>copy()</h2> <pre><code>$x->copy(); # make a true copy of $x (unlike $y = $x;)</code></pre> <h2 id="as_int()/as_number()"><a class="permalink" href="#as_int()/as_number()">#</a><a id="as_int"></a><a id="as_int-as_number"></a>as_int()/as_number()</h2> <pre><code>$x->as_int(); </code></pre> <p>Returns $x as a BigInt (truncated towards zero). In BigInt this is the same as <code>copy()</code>.</p> <p><code>as_number()</code> is an alias to this method. <code>as_number</code> was introduced in v1.22, while <code>as_int()</code> was only introduced in v1.68.</p> <h2 id="bstr()"><a class="permalink" href="#bstr()">#</a><a id="bstr"></a>bstr()</h2> <pre><code>$x->bstr();</code></pre> <p>Returns a normalized string representation of <code>$x</code>.</p> <h2 id="bsstr()"><a class="permalink" href="#bsstr()">#</a><a id="bsstr"></a>bsstr()</h2> <pre><code>$x->bsstr(); # normalized string in scientific notation</code></pre> <h2 id="as_hex()"><a class="permalink" href="#as_hex()">#</a><a id="as_hex"></a>as_hex()</h2> <pre><code>$x->as_hex(); # as signed hexadecimal string with prefixed 0x</code></pre> <h2 id="as_bin()"><a class="permalink" href="#as_bin()">#</a><a id="as_bin"></a>as_bin()</h2> <pre><code>$x->as_bin(); # as signed binary string with prefixed 0b</code></pre> <h2 id="as_oct()"><a class="permalink" href="#as_oct()">#</a><a id="as_oct"></a>as_oct()</h2> <pre><code>$x->as_oct(); # as signed octal string with prefixed 0</code></pre> <h2 id="numify()"><a class="permalink" href="#numify()">#</a><a id="numify"></a>numify()</h2> <pre><code>print $x->numify();</code></pre> <p>This returns a normal Perl scalar from $x. It is used automatically whenever a scalar is needed, for instance in array index operations.</p> <p>This loses precision, to avoid this use <a href="/5.12.2/as_int()">as_int()</a> instead.</p> <h2 id="modify()"><a class="permalink" href="#modify()">#</a><a id="modify"></a>modify()</h2> <pre><code>$x->modify('bpowd');</code></pre> <p>This method returns 0 if the object can be modified with the given peration, or 1 if not.</p> <p>This is used for instance by <a href="/5.12.2/Math::BigInt::Constant">Math::BigInt::Constant</a>.</p> <h2 id="upgrade()/downgrade()"><a class="permalink" href="#upgrade()/downgrade()">#</a><a id="upgrade"></a><a id="upgrade-downgrade"></a>upgrade()/downgrade()</h2> <p>Set/get the class for downgrade/upgrade operations. Thuis is used for instance by <a href="/5.12.2/bignum">bignum</a>. The defaults are '', thus the following operation will create a BigInt, not a BigFloat:</p> <pre><code>my $i = Math::BigInt->new(123); my $f = Math::BigFloat->new('123.1'); print $i + $f,"\n"; # print 246</code></pre> <h2 id="div_scale()"><a class="permalink" href="#div_scale()">#</a><a id="div_scale"></a>div_scale()</h2> <p>Set/get the number of digits for the default precision in divide operations.</p> <h2 id="round_mode()"><a class="permalink" href="#round_mode()">#</a><a id="round_mode"></a>round_mode()</h2> <p>Set/get the current round mode.</p> <h1 id="ACCURACY-and-PRECISION"><a class="permalink" href="#ACCURACY-and-PRECISION">#</a><a id="ACCURACY"></a>ACCURACY and PRECISION</h1> <p>Since version v1.33, Math::BigInt and Math::BigFloat have full support for accuracy and precision based rounding, both automatically after every operation, as well as manually.</p> <p>This section describes the accuracy/precision handling in Math::Big* as it used to be and as it is now, complete with an explanation of all terms and abbreviations.</p> <p>Not yet implemented things (but with correct description) are marked with '!', things that need to be answered are marked with '?'.</p> <p>In the next paragraph follows a short description of terms used here (because these may differ from terms used by others people or documentation).</p> <p>During the rest of this document, the shortcuts A (for accuracy), P (for precision), F (fallback) and R (rounding mode) will be used.</p> <h2 id="Precision-P"><a class="permalink" href="#Precision-P">#</a><a id="Precision1"></a>Precision P</h2> <p>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 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 inital value was). It could also have p < 0, when the digits after the decimal point are zero.</p> <p>The string output (of floating point numbers) will be padded with zeros:</p> <pre><code class="plaintext">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</code></pre> <p>For BigInts, no padding occurs.</p> <h2 id="Accuracy-A"><a class="permalink" href="#Accuracy-A">#</a><a id="Accuracy"></a>Accuracy A</h2> <p>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.450000 has 8 and 0.000123 has 3.</p> <p>The string output (of floating point numbers) will be padded with zeros:</p> <pre><code class="plaintext">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</code></pre> <p>For BigInts, no padding occurs.</p> <h2 id="Fallback-F"><a class="permalink" href="#Fallback-F">#</a><a id="Fallback"></a>Fallback F</h2> <p>When both A and P are undefined, this is used as a fallback accuracy when dividing numbers.</p> <h2 id="Rounding-mode-R"><a class="permalink" href="#Rounding-mode-R">#</a><a id="Rounding1"></a>Rounding mode R</h2> <p>When rounding a number, different 'styles' or 'kinds' of rounding are possible. (Note that random rounding, as in Math::Round, is not implemented.)</p> <dl> <dt id="'trunc'"><a class="permalink" href="#'trunc'">#</a><a id="trunc"></a>'trunc'</dt> <dd> <p>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.</p> <p>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.</p> <p>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:</p> </dd> <dt id="'even'"><a class="permalink" href="#'even'">#</a><a id="even"></a>'even'</dt> <dd> <p>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.</p> </dd> <dt id="'odd'"><a class="permalink" href="#'odd'">#</a><a id="odd"></a>'odd'</dt> <dd> <p>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.</p> </dd> <dt id="'+inf'"><a class="permalink" href="#'+inf'">#</a><a id="inf"></a>'+inf'</dt> <dd> <p>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.</p> </dd> <dt id="'-inf'"><a class="permalink" href="#'-inf'">#</a><a id="inf1"></a>'-inf'</dt> <dd> <p>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.</p> </dd> <dt id="'zero'"><a class="permalink" href="#'zero'">#</a><a id="zero"></a>'zero'</dt> <dd> <p>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.</p> </dd> <dt id="'common'"><a class="permalink" href="#'common'">#</a><a id="common"></a>'common'</dt> <dd> <p>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.</p> </dd> </dl> <p>The handling of A & P in MBI/MBF (the old core code shipped with Perl versions <= 5.7.2) is like this:</p> <dl> <dt id="Precision"><a class="permalink" href="#Precision">#</a>Precision</dt> <dd> <pre><code>* ffround($p) is able to round to $p number of digits after the decimal point * otherwise P is unused</code></pre> </dd> <dt id="Accuracy-(significant-digits)"><a class="permalink" href="#Accuracy-(significant-digits)">#</a><a id="Accuracy1"></a><a id="Accuracy-significant-digits"></a>Accuracy (significant digits)</dt> <dd> <pre><code> * fround($a) rounds to $a significant digits * only fdiv() and fsqrt() take A as (optional) paramater + other operations simply create the same number (fneg etc), or more (fmul) of digits + rounding/truncating is only done when explicitly calling one of fround or ffround, and never for BigInt (not implemented) * fsqrt() simply hands its accuracy argument over to fdiv. * the documentation and the comment in the code indicate two different ways on how fdiv() 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+9-3). Actually, the 'difference' added to the scale is calculated from the number of "significant digits" in dividend and divisor, which is derived by looking at the length of the mantissa. 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 significant digits. The rounding after the division then uses the remainder and $y to determine wether 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.</code></pre> </dd> </dl> <p>This is how it works now:</p> <dl> <dt id="Setting/Accessing"><a class="permalink" href="#Setting/Accessing">#</a><a id="Setting"></a><a id="Setting-Accessing"></a>Setting/Accessing</dt> <dd> <pre><code>* You can set the A global via C<< Math::BigInt->accuracy() >> or C<< Math::BigFloat->accuracy() >> or whatever class you are using. * You can also set P globally by using C<< Math::SomeClass->precision() >> likewise. * Globals are classwide, and not inherited by subclasses. * to undefine A, use C<< Math::SomeCLass->accuracy(undef); >> * to undefine P, use C<< Math::SomeClass->precision(undef); >> * Setting C<< Math::SomeClass->accuracy() >> clears automatically C<< 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 C<< Math::SomeClass->accuracy() >> * to find out the current global P, use C<< Math::SomeClass->precision() >> * use C<< $x->accuracy() >> respective C<< $x->precision() >> for the local setting of C<< $x >>. * Please note that C<< $x->accuracy() >> respective C<< $x->precision() >> return eventually defined global A or P, when C<< $x >>'s A or P is not set.</code></pre> </dd> <dt id="Creating-numbers"><a class="permalink" href="#Creating-numbers">#</a><a id="Creating"></a>Creating numbers</dt> <dd> <pre><code> * 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, B<no> rounding will occur, and the globals will B<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 C<< $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.</code></pre> </dd> <dt id="Usage"><a class="permalink" href="#Usage">#</a>Usage</dt> <dd> <pre><code class="plaintext">* 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 BigInts 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 BigFloat. A flag is used to mark all Math::BigFloat numbers as 'never round'.</code></pre> </dd> <dt id="Precedence"><a class="permalink" href="#Precedence">#</a>Precedence</dt> <dd> <pre><code> * 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 fdiv/fsqrt) and will not be rounded. * There is another setting for fdiv() (and thus for fsqrt()). If neither of A or P is defined, fdiv() 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 :-) * fdiv 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 fdiv() and fsqrt() 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()->fround(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? </code></pre> </dd> <dt id="Overriding-globals"><a class="permalink" href="#Overriding-globals">#</a><a id="Overriding"></a>Overriding globals</dt> <dd> <pre><code class="plaintext">* 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 * fsqrt() will hand its arguments to fdiv(), as it used to, only now for two arguments (A and P) instead of one</code></pre> </dd> <dt id="Local-settings"><a class="permalink" href="#Local-settings">#</a><a id="Local"></a>Local settings</dt> <dd> <pre><code>* You can set A or P locally by using C<< $x->accuracy() >> or C<< $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. * C<< $x->accuracy() >> clears C<< $x->precision() >>, and vice versa.</code></pre> </dd> <dt id="Rounding"><a class="permalink" href="#Rounding">#</a>Rounding</dt> <dd> <pre><code>* the rounding routines will use the respective global or local settings. fround()/bround() is for accuracy rounding, while ffround()/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 C<< Math::SomeClass->round_mode() >> or by setting C<< $Math::SomeClass::round_mode >> * after each operation, C<< $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 C<< $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.</code></pre> </dd> <dt id="Default-values"><a class="permalink" href="#Default-values">#</a><a id="Default"></a>Default values</dt> <dd> <pre><code class="plaintext">* R: 'even' * F: 40 * A: undef * P: undef</code></pre> </dd> <dt id="Remarks"><a class="permalink" href="#Remarks">#</a>Remarks</dt> <dd> <pre><code class="plaintext">* The defaults are set up so that the new code gives the same results as the old code (except in a few cases on fdiv): + 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</code></pre> </dd> </dl> <h1 id="Infinity-and-Not-a-Number"><a class="permalink" href="#Infinity-and-Not-a-Number">#</a><a id="Infinity"></a>Infinity and Not a Number</h1> <p>While BigInt has extensive handling of inf and NaN, certain quirks remain.</p> <dl> <dt id="oct()/hex()"><a class="permalink" href="#oct()/hex()">#</a><a id="oct"></a><a id="oct-hex"></a>oct()/hex()</dt> <dd> <p>These perl routines currently (as of Perl v.5.8.6) cannot handle passed inf.</p> <pre><code>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</code></pre> <p>The same problems occur if you pass them Math::BigInt->binf() objects. Since overloading these routines is not possible, this cannot be fixed from BigInt.</p> </dd> <dt id="==,-!=,-<,->,-<=,->=-with-NaNs"><a class="permalink" href="#==,-!=,-%3C,-%3E,-%3C=,-%3E=-with-NaNs">#</a><a id="with-NaNs"></a>==, !=, <, >, <=, >= with NaNs</dt> <dd> <p>BigInt's bcmp() routine currently returns undef to signal that a NaN was involved in a comparison. However, the overload code turns that into either 1 or '' and thus operations like <code>NaN != NaN</code> might return wrong values.</p> </dd> <dt id="log(-inf)"><a class="permalink" href="#log(-inf)">#</a><a id="log"></a><a id="log--inf"></a>log(-inf)</dt> <dd> <p><code>log(-inf)</code> is highly weird. Since log(-x)=pi*i+log(x), then log(-inf)=pi*i+inf. However, since the imaginary part is finite, the real infinity "overshadows" it, so the number might as well just be infinity. However, the result is a complex number, and since BigInt/BigFloat can only have real numbers as results, the result is NaN.</p> </dd> <dt id="exp(),-cos(),-sin(),-atan2()"><a class="permalink" href="#exp(),-cos(),-sin(),-atan2()">#</a><a id="exp"></a><a id="exp-cos-sin-atan2"></a>exp(), cos(), sin(), atan2()</dt> <dd> <p>These all might have problems handling infinity right.</p> </dd> </dl> <h1 id="INTERNALS"><a class="permalink" href="#INTERNALS">#</a>INTERNALS</h1> <p>The actual numbers are stored as unsigned big integers (with seperate sign).</p> <p>You should neither care about nor depend on the internal representation; it might change without notice. Use <b>ONLY</b> method calls like <code>$x->sign();</code> instead relying on the internal representation.</p> <h2 id="MATH-LIBRARY"><a class="permalink" href="#MATH-LIBRARY">#</a><a id="MATH"></a>MATH LIBRARY</h2> <p>Math with the numbers is done (by default) by a module called <code>Math::BigInt::Calc</code>. This is equivalent to saying:</p> <pre><code>use Math::BigInt try => 'Calc';</code></pre> <p>You can change this backend library by using:</p> <pre><code>use Math::BigInt try => 'GMP';</code></pre> <p><b>Note</b>: General purpose packages should not be explicit about the library to use; let the script author decide which is best.</p> <p>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:</p> <pre><code>use Math::BigInt only => 'GMP,Pari';</code></pre> <p>The following would first try to find Math::BigInt::Foo, then Math::BigInt::Bar, and when this also fails, revert to Math::BigInt::Calc:</p> <pre><code>use Math::BigInt try => 'Foo,Math::BigInt::Bar';</code></pre> <p>The library that is loaded last will be 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.</p> <h3 id="What-library-to-use?"><a class="permalink" href="#What-library-to-use?">#</a><a id="What"></a><a id="What-library-to-use"></a>What library to use?</h3> <p><b>Note</b>: General purpose packages should not be explicit about the library to use; let the script author decide which is best.</p> <p><a href="/5.12.2/Math::BigInt::GMP">Math::BigInt::GMP</a> and <a href="/5.12.2/Math::BigInt::Pari">Math::BigInt::Pari</a> 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).</p> <p>So please select carefully what libary you want to use.</p> <p>Different low-level libraries use different formats to store the numbers. However, you should <b>NOT</b> depend on the number having a specific format internally.</p> <p>See the respective math library module documentation for further details.</p> <h2 id="SIGN"><a class="permalink" href="#SIGN">#</a>SIGN</h2> <p>The sign is either '+', '-', 'NaN', '+inf' or '-inf'.</p> <p>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 will get '+inf' when dividing a positive number by 0, and '-inf' when dividing any negative number by 0.</p> <h2 id="mantissa(),-exponent()-and-parts()"><a class="permalink" href="#mantissa(),-exponent()-and-parts()">#</a><a id="mantissa1"></a><a id="mantissa-exponent-and-parts"></a>mantissa(), exponent() and parts()</h2> <p><code>mantissa()</code> and <code>exponent()</code> return the said parts of the BigInt such that:</p> <pre><code>$m = $x->mantissa(); $e = $x->exponent(); $y = $m * ( 10 ** $e ); print "ok\n" if $x == $y;</code></pre> <p><code>($m,$e) = $x->parts()</code> is just a shortcut that gives you both of them in one go. Both the returned mantissa and exponent have a sign.</p> <p>Currently, for BigInts <code>$e</code> is always 0, except +inf and -inf, where it is <code>+inf</code>; and for NaN, where it is <code>NaN</code>; and for <code>$x == 0</code>, where it is <code>1</code> (to be compatible with Math::BigFloat's internal representation of a zero as <code>0E1</code>).</p> <p><code>$m</code> is currently just a copy of the original number. The relation between <code>$e</code> and <code>$m</code> will stay always the same, though their real values might change.</p> <h1 id="EXAMPLES"><a class="permalink" href="#EXAMPLES">#</a>EXAMPLES</h1> <pre><code>use Math::BigInt; sub bint { Math::BigInt->new(shift); } $x = Math::BigInt->bstr("1234") # string "1234" $x = "$x"; # same as bstr() $x = Math::BigInt->bneg("1234"); # BigInt "-1234" $x = Math::BigInt->babs("-12345"); # BigInt "12345" $x = Math::BigInt->bnorm("-0.00"); # BigInt "0" $x = bint(1) + bint(2); # BigInt "3" $x = bint(1) + "2"; # ditto (auto-BigIntify of "2") $x = bint(1); # BigInt "1" $x = $x + 5 / 2; # BigInt "3" $x = $x ** 3; # BigInt "27" $x *= 2; # BigInt "54" $x = Math::BigInt->new(0); # BigInt "0" $x--; # BigInt "-1" $x = Math::BigInt->badd(4,5) # BigInt "9" print $x->bsstr(); # 9e+0</code></pre> <p>Examples for rounding:</p> <pre><code>use Math::BigFloat; use Test; $x = Math::BigFloat->new(123.4567); $y = Math::BigFloat->new(123.456789); Math::BigFloat->accuracy(4); # no more A than 4 ok ($x->copy()->fround(),123.4); # even rounding print $x->copy()->fround(),"\n"; # 123.4 Math::BigFloat->round_mode('odd'); # round to odd print $x->copy()->fround(),"\n"; # 123.5 Math::BigFloat->accuracy(5); # no more A than 5 Math::BigFloat->round_mode('odd'); # round to odd print $x->copy()->fround(),"\n"; # 123.46 $y = $x->copy()->fround(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()->fround(),"\n"; # 123.46</code></pre> <p>Examples for converting:</p> <pre><code>my $x = Math::BigInt->new('0b1'.'01' x 123); print "bin: ",$x->as_bin()," hex:",$x->as_hex()," dec: ",$x,"\n";</code></pre> <h1 id="Autocreating-constants"><a class="permalink" href="#Autocreating-constants">#</a><a id="Autocreating"></a>Autocreating constants</h1> <p>After <code>use Math::BigInt ':constant'</code> all the <b>integer</b> decimal, hexadecimal and binary constants in the given scope are converted to <code>Math::BigInt</code>. This conversion happens at compile time.</p> <p>In particular,</p> <pre><code class="plaintext">perl -MMath::BigInt=:constant -e 'print 2**100,"\n"'</code></pre> <p>prints the integer value of <code>2**100</code>. Note that without conversion of constants the expression 2**100 will be calculated as perl scalar.</p> <p>Please note that strings and floating point constants are not affected, so that</p> <pre><code> use Math::BigInt qw/:constant/; $x = 1234567890123456789012345678901234567890 + 123456789123456789; $y = '1234567890123456789012345678901234567890' + '123456789123456789';</code></pre> <p>do not work. You need an explicit Math::BigInt->new() around one of the operands. You should also quote large constants to protect loss of precision:</p> <pre><code>use Math::BigInt; $x = Math::BigInt->new('1234567889123456789123456789123456789');</code></pre> <p>Without the quotes Perl would convert the large number to a floating point constant at compile time and then hand the result to BigInt, which results in an truncated result or a NaN.</p> <p>This also applies to integers that look like floating point constants:</p> <pre><code>use Math::BigInt ':constant'; print ref(123e2),"\n"; print ref(123.2e2),"\n";</code></pre> <p>will print nothing but newlines. Use either <a href="/5.12.2/bignum">bignum</a> or <a href="/5.12.2/Math::BigFloat">Math::BigFloat</a> to get this to work.</p> <h1 id="PERFORMANCE"><a class="permalink" href="#PERFORMANCE">#</a>PERFORMANCE</h1> <p>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.</p> <p>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.</p> <p>The rewritten version of this module (vs. v0.01) is slower on certain operations, like <code>new()</code>, <code>bstr()</code> and <code>numify()</code>. 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.</p> <p>Some operations may be slower for small numbers, but are significantly faster for big numbers. Other operations are now constant (O(1), like <code>bneg()</code>, <code>babs()</code> etc), instead of O(N) and thus nearly always take much less time. These optimizations were done on purpose.</p> <p>If you find the Calc module to slow, try to install any of the replacement modules and see if they help you.</p> <h2 id="Alternative-math-libraries"><a class="permalink" href="#Alternative-math-libraries">#</a><a id="Alternative"></a>Alternative math libraries</h2> <p>You can use an alternative library to drive Math::BigInt. See the section <a href="#MATH-LIBRARY">"MATH LIBRARY"</a> for more information.</p> <p>For more benchmark results see <a href="http://bloodgate.com/perl/benchmarks.html">http://bloodgate.com/perl/benchmarks.html</a>.</p> <h2 id="SUBCLASSING"><a class="permalink" href="#SUBCLASSING">#</a>SUBCLASSING</h2> <h1 id="Subclassing-Math::BigInt"><a class="permalink" href="#Subclassing-Math::BigInt">#</a><a id="Subclassing"></a>Subclassing Math::BigInt</h1> <p>The basic design of Math::BigInt allows simple subclasses with very little work, as long as a few simple rules are followed:</p> <ul> <li><p>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.</p> </li> <li><p>The private object hash keys like <code>$x-</code>{sign}> may not be changed, but additional keys can be added, like <code>$x-</code>{_custom}>.</p> </li> <li><p>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.</p> </li> </ul> <p>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 <code>bstr()</code>.</p> <p>All other object methods and overloaded functions can be directly inherited from the parent class.</p> <p>At the very minimum, any subclass will need to provide its own <code>new()</code> and can store additional hash keys in the object. There are also some package globals that must be defined, e.g.:</p> <pre><code># Globals $accuracy = undef; $precision = -2; # round to 2 decimal places $round_mode = 'even'; $div_scale = 40;</code></pre> <p>Additionally, you might want to provide the following two globals to allow auto-upgrading and auto-downgrading to work correctly:</p> <pre><code>$upgrade = undef; $downgrade = undef;</code></pre> <p>This allows Math::BigInt to correctly retrieve package globals from the subclass, like <code>$SubClass::precision</code>. See t/Math/BigInt/Subclass.pm or t/Math/BigFloat/SubClass.pm completely functional subclass examples.</p> <p>Don't forget to</p> <pre><code>use overload;</code></pre> <p>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.</p> <h1 id="UPGRADING"><a class="permalink" href="#UPGRADING">#</a>UPGRADING</h1> <p>When used like this:</p> <pre><code>use Math::BigInt upgrade => 'Foo::Bar';</code></pre> <p>certain operations will 'upgrade' their calculation and thus the result to the class Foo::Bar. Usually this is used in conjunction with Math::BigFloat:</p> <pre><code>use Math::BigInt upgrade => 'Math::BigFloat';</code></pre> <p>As a shortcut, you can use the module <code>bignum</code>:</p> <pre><code>use bignum;</code></pre> <p>Also good for oneliners:</p> <pre><code class="plaintext">perl -Mbignum -le 'print 2 ** 255'</code></pre> <p>This makes it possible to mix arguments of different classes (as in 2.5 + 2) as well es preserve accuracy (as in sqrt(3)).</p> <p>Beware: This feature is not fully implemented yet.</p> <h2 id="Auto-upgrade"><a class="permalink" href="#Auto-upgrade">#</a><a id="Auto"></a>Auto-upgrade</h2> <p>The following methods upgrade themselves unconditionally; that is if upgrade is in effect, they will always hand up their work:</p> <dl> <dt id="bsqrt()1"><a class="permalink" href="#bsqrt()1">#</a><a id="bsqrt1"></a>bsqrt()</dt> <dd> </dd> <dt id="div()"><a class="permalink" href="#div()">#</a><a id="div"></a>div()</dt> <dd> </dd> <dt id="blog()1"><a class="permalink" href="#blog()1">#</a><a id="blog1"></a>blog()</dt> <dd> </dd> <dt id="bexp()1"><a class="permalink" href="#bexp()1">#</a><a id="bexp1"></a>bexp()</dt> <dd> </dd> </dl> <p>Beware: This list is not complete.</p> <p>All other methods upgrade themselves only when one (or all) of their arguments are of the class mentioned in $upgrade (This might change in later versions to a more sophisticated scheme):</p> <h1 id="EXPORTS"><a class="permalink" href="#EXPORTS">#</a>EXPORTS</h1> <p><code>Math::BigInt</code> exports nothing by default, but can export the following methods:</p> <pre><code class="plaintext">bgcd blcm</code></pre> <h1 id="CAVEATS"><a class="permalink" href="#CAVEATS">#</a>CAVEATS</h1> <p>Some things might not work as you expect them. Below is documented what is known to be troublesome:</p> <dl> <dt id="bstr(),-bsstr()-and-'cmp'"><a class="permalink" href="#bstr(),-bsstr()-and-'cmp'">#</a><a id="bstr1"></a><a id="bstr-bsstr-and-cmp"></a>bstr(), bsstr() and 'cmp'</dt> <dd> <p>Both <code>bstr()</code> and <code>bsstr()</code> as well as automated stringify via overload now drop the leading '+'. The old code would return '+3', the new returns '3'. This is to be consistent with Perl and to make <code>cmp</code> (especially with overloading) to work as you expect. It also solves problems with <code>Test.pm</code>, because its <code>ok()</code> uses 'eq' internally.</p> <p>Mark Biggar said, when asked about to drop the '+' altogether, or make only <code>cmp</code> work:</p> <pre><code class="plaintext">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.</code></pre> <p>So, the following examples will now work all as expected:</p> <pre><code> use Test; BEGIN { plan tests => 1 } use Math::BigInt; my $x = new Math::BigInt 3*3; my $y = new Math::BigInt 3*3; ok ($x,3*3); 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;</code></pre> <p>Additionally, the following still works:</p> <pre><code>print "$x == 9" if $x == $y; print "$x == 9" if $x == 9; print "$x == 9" if $x == 3*3;</code></pre> <p>There is now a <code>bsstr()</code> method to get the string in scientific notation aka <code>1e+2</code> instead of <code>100</code>. Be advised that overloaded 'eq' always uses bstr() for comparison, but Perl will represent some numbers as 100 and others as 1e+308. If in doubt, convert both arguments to Math::BigInt before comparing them as strings:</p> <pre><code> use Test; BEGIN { plan tests => 3 } use Math::BigInt; $x = Math::BigInt->new('1e56'); $y = 1e56; ok ($x,$y); # will fail ok ($x->bsstr(),$y); # okay $y = Math::BigInt->new($y); ok ($x,$y); # okay</code></pre> <p>Alternatively, simple use <code><=></code> for comparisons, this will get it always right. There is not yet a way to get a number automatically represented as a string that matches exactly the way Perl represents it.</p> <p>See also the section about <a href="#Infinity-and-Not-a-Number">"Infinity and Not a Number"</a> for problems in comparing NaNs.</p> </dd> <dt id="int()"><a class="permalink" href="#int()">#</a><a id="int"></a>int()</dt> <dd> <p><code>int()</code> will return (at least for Perl v5.7.1 and up) another BigInt, not a Perl scalar:</p> <pre><code>$x = Math::BigInt->new(123); $y = int($x); # BigInt 123 $x = Math::BigFloat->new(123.45); $y = int($x); # BigInt 123</code></pre> <p>In all Perl versions you can use <code>as_number()</code> or <code>as_int</code> for the same effect:</p> <pre><code>$x = Math::BigFloat->new(123.45); $y = $x->as_number(); # BigInt 123 $y = $x->as_int(); # ditto</code></pre> <p>This also works for other subclasses, like Math::String.</p> <p>If you want a real Perl scalar, use <code>numify()</code>:</p> <pre><code>$y = $x->numify(); # 123 as scalar</code></pre> <p>This is seldom necessary, though, because this is done automatically, like when you access an array:</p> <pre><code>$z = $array[$x]; # does work automatically</code></pre> </dd> <dt id="length"><a class="permalink" href="#length">#</a>length</dt> <dd> <p>The following will probably not do what you expect:</p> <pre><code>$c = Math::BigInt->new(123); print $c->length(),"\n"; # prints 30</code></pre> <p>It prints both the number of digits in the number and in the fraction part since print calls <code>length()</code> in list context. Use something like:</p> <pre><code>print scalar $c->length(),"\n"; # prints 3 </code></pre> </dd> <dt id="bdiv"><a class="permalink" href="#bdiv">#</a>bdiv</dt> <dd> <p>The following will probably not do what you expect:</p> <pre><code>print $c->bdiv(10000),"\n";</code></pre> <p>It prints both quotient and remainder since print calls <code>bdiv()</code> in list context. Also, <code>bdiv()</code> will modify $c, so be careful. You probably want to use</p> <pre><code>print $c / 10000,"\n"; print scalar $c->bdiv(10000),"\n"; # or if you want to modify $c</code></pre> <p>instead.</p> <p>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 nonzero) always has the same sign as the second operand; so, for example,</p> <pre><code class="plaintext"> 1 / 4 => ( 0, 1) 1 / -4 => (-1,-3) -3 / 4 => (-1, 1) -3 / -4 => ( 0,-3) -11 / 2 => (-5,1) 11 /-2 => (-5,-1)</code></pre> <p>As a consequence, the behavior of the operator % agrees with the behavior of Perl's built-in % operator (as documented in the perlop manpage), and the equation</p> <pre><code>$x == ($x / $y) * $y + ($x % $y)</code></pre> <p>holds true for any $x and $y, which justifies calling the two return values of bdiv() the quotient and remainder. The only exception to this rule are when $y == 0 and $x is negative, then the remainder will also be negative. See below under "infinity handling" for the reasoning behind this.</p> <p>Perl's 'use integer;' changes the behaviour of % and / for scalars, but will not change BigInt's way to do things. This is because under 'use integer' Perl will do what the underlying C thinks is right and this is different for each system. If you need BigInt's behaving exactly like Perl's 'use integer', bug the author to implement it ;)</p> </dd> <dt id="infinity-handling"><a class="permalink" href="#infinity-handling">#</a><a id="infinity"></a>infinity handling</dt> <dd> <p>Here are some examples that explain the reasons why certain results occur while handling infinity:</p> <p>The following table shows the result of the division and the remainder, so that the equation above holds true. Some "ordinary" cases are strewn in to show more clearly the reasoning:</p> <pre><code class="plaintext"> A / B = C, R so that C * B + R = A ========================================================= 5 / 8 = 0, 5 0 * 8 + 5 = 5 0 / 8 = 0, 0 0 * 8 + 0 = 0 0 / inf = 0, 0 0 * inf + 0 = 0 0 /-inf = 0, 0 0 * -inf + 0 = 0 5 / inf = 0, 5 0 * inf + 5 = 5 5 /-inf = 0, 5 0 * -inf + 5 = 5 -5/ inf = 0, -5 0 * inf + -5 = -5 -5/-inf = 0, -5 0 * -inf + -5 = -5 inf/ 5 = inf, 0 inf * 5 + 0 = inf -inf/ 5 = -inf, 0 -inf * 5 + 0 = -inf inf/ -5 = -inf, 0 -inf * -5 + 0 = inf -inf/ -5 = inf, 0 inf * -5 + 0 = -inf 5/ 5 = 1, 0 1 * 5 + 0 = 5 -5/ -5 = 1, 0 1 * -5 + 0 = -5 inf/ inf = 1, 0 1 * inf + 0 = inf -inf/-inf = 1, 0 1 * -inf + 0 = -inf inf/-inf = -1, 0 -1 * -inf + 0 = inf -inf/ inf = -1, 0 1 * -inf + 0 = -inf 8/ 0 = inf, 8 inf * 0 + 8 = 8 inf/ 0 = inf, inf inf * 0 + inf = inf 0/ 0 = NaN</code></pre> <p>These cases below violate the "remainder has the sign of the second of the two arguments", since they wouldn't match up otherwise.</p> <pre><code class="plaintext"> A / B = C, R so that C * B + R = A ======================================================== -inf/ 0 = -inf, -inf -inf * 0 + inf = -inf -8/ 0 = -inf, -8 -inf * 0 + 8 = -8 </code></pre> </dd> <dt id="Modifying-and-="><a class="permalink" href="#Modifying-and-=">#</a><a id="Modifying"></a><a id="Modifying-and"></a>Modifying and =</dt> <dd> <p>Beware of:</p> <pre><code>$x = Math::BigFloat->new(5); $y = $x;</code></pre> <p>It will not do what you think, e.g. making a copy of $x. Instead it just makes a second reference to the <b>same</b> object and stores it in $y. Thus anything that modifies $x (except overloaded operators) will modify $y, and vice versa. Or in other words, <code>=</code> is only safe if you modify your BigInts only via overloaded math. As soon as you use a method call it breaks:</p> <pre><code>$x->bmul(2); print "$x, $y\n"; # prints '10, 10'</code></pre> <p>If you want a true copy of $x, use:</p> <pre><code>$y = $x->copy();</code></pre> <p>You can also chain the calls like this, this will make first a copy and then multiply it by 2:</p> <pre><code>$y = $x->copy()->bmul(2);</code></pre> <p>See also the documentation for overload.pm regarding <code>=</code>.</p> </dd> <dt id="bpow"><a class="permalink" href="#bpow">#</a>bpow</dt> <dd> <p><code>bpow()</code> (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 <code>badd()</code> etc. The first three will modify $x, the last one won't:</p> <pre><code>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 </code></pre> <p>The form <code>$x **= $y</code> is faster than <code>$x = $x ** $y;</code>, though.</p> </dd> <dt id="Overloading-$x"><a class="permalink" href="#Overloading-$x">#</a><a id="Overloading"></a><a id="Overloading---x"></a>Overloading -$x</dt> <dd> <p>The following:</p> <pre><code>$x = -$x;</code></pre> <p>is slower than</p> <pre><code>$x->bneg();</code></pre> <p>since overload calls <code>sub($x,0,1);</code> instead of <code>neg($x)</code>. The first variant needs to preserve $x since it does not know that it later will get overwritten. This makes a copy of $x and takes O(N), but $x->bneg() is O(1).</p> </dd> <dt id="Mixing-different-object-types"><a class="permalink" href="#Mixing-different-object-types">#</a><a id="Mixing"></a>Mixing different object types</dt> <dd> <p>In Perl you will get a floating point value if you do one of the following:</p> <pre><code>$float = 5.0 + 2; $float = 2 + 5.0; $float = 5 / 2;</code></pre> <p>With overloaded math, only the first two variants will result in a BigFloat:</p> <pre><code>use Math::BigInt; use Math::BigFloat; $mbf = Math::BigFloat->new(5); $mbi2 = Math::BigInteger->new(5); $mbi = Math::BigInteger->new(2); # what actually gets called: $float = $mbf + $mbi; # $mbf->badd() $float = $mbf / $mbi; # $mbf->bdiv() $integer = $mbi + $mbf; # $mbi->badd() $integer = $mbi2 / $mbi; # $mbi2->bdiv() $integer = $mbi2 / $mbf; # $mbi2->bdiv()</code></pre> <p>This is because math with overloaded operators follows the first (dominating) operand, and the operation of that is called and returns thus the result. So, Math::BigInt::bdiv() will always return a Math::BigInt, regardless whether the result should be a Math::BigFloat or the second operant is one.</p> <p>To get a Math::BigFloat you either need to call the operation manually, make sure the operands are already of the proper type or casted to that type via Math::BigFloat->new():</p> <pre><code>$float = Math::BigFloat->new($mbi2) / $mbi; # = 2.5</code></pre> <p>Beware of simple "casting" the entire expression, this would only convert the already computed result:</p> <pre><code>$float = Math::BigFloat->new($mbi2 / $mbi); # = 2.0 thus wrong!</code></pre> <p>Beware also of the order of more complicated expressions like:</p> <pre><code>$integer = ($mbi2 + $mbi) / $mbf; # int / float => int $integer = $mbi2 / Math::BigFloat->new($mbi); # ditto</code></pre> <p>If in doubt, break the expression into simpler terms, or cast all operands to the desired resulting type.</p> <p>Scalar values are a bit different, since:</p> <pre><code>$float = 2 + $mbf; $float = $mbf + 2;</code></pre> <p>will both result in the proper type due to the way the overloaded math works.</p> <p>This section also applies to other overloaded math packages, like Math::String.</p> <p>One solution to you problem might be autoupgrading|upgrading. See the pragmas <a href="/5.12.2/bignum">bignum</a>, <a href="/5.12.2/bigint">bigint</a> and <a href="/5.12.2/bigrat">bigrat</a> for an easy way to do this.</p> </dd> <dt id="bsqrt()2"><a class="permalink" href="#bsqrt()2">#</a><a id="bsqrt2"></a>bsqrt()</dt> <dd> <p><code>bsqrt()</code> works only good if the result is a big integer, e.g. the square root of 144 is 12, but from 12 the square root is 3, regardless of rounding mode. The reason is that the result is always truncated to an integer.</p> <p>If you want a better approximation of the square root, then use:</p> <pre><code>$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</code></pre> </dd> <dt id="brsft()2"><a class="permalink" href="#brsft()2">#</a><a id="brsft2"></a>brsft()</dt> <dd> <p>For negative numbers in base see also <a href="/5.12.2/brsft">brsft</a>.</p> </dd> </dl> <h1 id="LICENSE"><a class="permalink" href="#LICENSE">#</a>LICENSE</h1> <p>This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.</p> <h1 id="SEE-ALSO"><a class="permalink" href="#SEE-ALSO">#</a><a id="SEE"></a>SEE ALSO</h1> <p><a href="/5.12.2/Math::BigFloat">Math::BigFloat</a>, <a href="/5.12.2/Math::BigRat">Math::BigRat</a> and <a href="/5.12.2/Math::Big">Math::Big</a> as well as <a href="/5.12.2/Math::BigInt::BitVect">Math::BigInt::BitVect</a>, <a href="/5.12.2/Math::BigInt::Pari">Math::BigInt::Pari</a> and <a href="/5.12.2/Math::BigInt::GMP">Math::BigInt::GMP</a>.</p> <p>The pragmas <a href="/5.12.2/bignum">bignum</a>, <a href="/5.12.2/bigint">bigint</a> and <a href="/5.12.2/bigrat">bigrat</a> also might be of interest because they solve the autoupgrading/downgrading issue, at least partly.</p> <p>The package at <a href="http://search.cpan.org/search?mode=module&query=Math%3A%3ABigInt">http://search.cpan.org/search?mode=module&query=Math%3A%3ABigInt</a> contains more documentation including a full version history, testcases, empty subclass files and benchmarks.</p> <h1 id="AUTHORS"><a class="permalink" href="#AUTHORS">#</a>AUTHORS</h1> <p>Original code by Mark Biggar, overloaded interface by Ilya Zakharevich. Completely rewritten by Tels http://bloodgate.com in late 2000, 2001 - 2006 and still at it in 2007.</p> <p>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!</p> </div> <div id="footer"> <p>Perldoc Browser is maintained by Dan Book (<a href="https://metacpan.org/author/DBOOK">DBOOK</a>). Please contact him via the <a href="https://github.com/Grinnz/perldoc-browser/issues">GitHub issue tracker</a> or <a href="mailto:dbook@cpan.org">email</a> regarding any issues with the site itself, search, or rendering of documentation.</p> <p>The Perl documentation is maintained by the Perl 5 Porters in the development of Perl. Please contact them via the <a href="https://github.com/Perl/perl5/issues">Perl issue tracker</a>, the <a href="https://lists.perl.org/list/perl5-porters.html">mailing list</a>, or <a href="https://kiwiirc.com/client/irc.perl.org/p5p">IRC</a> to report any issues with the contents or format of the documentation.</p> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js" integrity="sha512-ubuT8Z88WxezgSqf3RLuNi5lmjstiJcyezx34yIU2gAHonIi27Na7atqzUZCOoY4CExaoFumzOsFQ2Ch+I/HCw==" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> <script src="/highlight.pack.js"></script> <script>hljs.highlightAll();</script> </body> </html>