Cari di Perl 
    Perl Tutorial
Daftar Isi
(Sebelumnya) Perl's fork() emulationPerl Performance and Optimizat ... (Berikutnya)
Language Reference

Semantics of numbers and numeric operations in Perl

Daftar Isi

NAME

perlnumber - semantics of numbers and numeric operations in Perl

SYNOPSIS

  1. $n = 1234; # decimal integer
  2. $n = 0b1110011; # binary integer
  3. $n = 01234; # octal integer
  4. $n = 0x1234; # hexadecimal integer
  5. $n = 12.34e-56; # exponential notation
  6. $n = "-12.34e56"; # number specified as a string
  7. $n = "1234"; # number specified as a string

DESCRIPTION

This document describes how Perl internally handles numeric values.

Perl's operator overloading facility is completely ignored here. Operatoroverloading allows user-defined behaviors for numbers, such as operationsover arbitrarily large integers, floating points numbers with arbitraryprecision, operations over "exotic" numbers such as modular arithmetic orp-adic arithmetic, and so on. See overload for details.

Storing numbers

Perl can internally represent numbers in 3 different ways: as nativeintegers, as native floating point numbers, and as decimal strings.Decimal strings may have an exponential notation part, as in "12.34e-56".Native here means "a format supported by the C compiler which was usedto build perl".

The term "native" does not mean quite as much when we talk about nativeintegers, as it does when native floating point numbers are involved.The only implication of the term "native" on integers is that the limits forthe maximal and the minimal supported true integral quantities are close topowers of 2. However, "native" floats have a most fundamentalrestriction: they may represent only those numbers which have a relatively"short" representation when converted to a binary fraction. For example,0.9 cannot be represented by a native float, since the binary fractionfor 0.9 is infinite:

  1. binary0.1110011001100...

with the sequence 1100 repeating again and again. In addition to thislimitation, the exponent of the binary number is also restricted when itis represented as a floating point number. On typical hardware, floatingpoint values can store numbers with up to 53 binary digits, and with binaryexponents between -1024 and 1024. In decimal representation this is closeto 16 decimal digits and decimal exponents in the range of -304..304.The upshot of all this is that Perl cannot store a number like12345678901234567 as a floating point number on such architectures withoutloss of information.

Similarly, decimal strings can represent only those numbers which have afinite decimal expansion. Being strings, and thus of arbitrary length, thereis no practical limit for the exponent or number of decimal digits for thesenumbers. (But realize that what we are discussing the rules for just thestorage of these numbers. The fact that you can store such "large" numbersdoes not mean that the operations over these numbers will use allof the significant digits.See Numeric operators and numeric conversions for details.)

In fact numbers stored in the native integer format may be stored eitherin the signed native form, or in the unsigned native form. Thus the limitsfor Perl numbers stored as native integers would typically be -2**31..2**32-1,with appropriate modifications in the case of 64-bit integers. Again, thisdoes not mean that Perl can do operations only over integers in this range:it is possible to store many more integers in floating point format.

Summing up, Perl numeric values can store only those numbers which havea finite decimal expansion or a "short" binary expansion.

Numeric operators and numeric conversions

As mentioned earlier, Perl can store a number in any one of three formats,but most operators typically understand only one of those formats. Whena numeric value is passed as an argument to such an operator, it will beconverted to the format understood by the operator.

Six such conversions are possible:

  1. native integer --> native floating point(*)
  2. native integer --> decimal string
  3. native floating_point --> native integer(*)
  4. native floating_point --> decimal string(*)
  5. decimal string --> native integer
  6. decimal string --> native floating point(*)

These conversions are governed by the following general rules:

  • If the source number can be represented in the target form, thatrepresentation is used.

  • If the source number is outside of the limits representable in the target form,a representation of the closest limit is used. (Loss of information)

  • If the source number is between two numbers representable in the target form,a representation of one of these numbers is used. (Loss of information)

  • In native floating point --> native integer conversions the magnitudeof the result is less than or equal to the magnitude of the source.("Rounding to zero".)

  • If the decimal string --> native integer conversion cannot be donewithout loss of information, the result is compatible with the conversionsequence decimal_string --> native_floating_point --> native_integer.In particular, rounding is strongly biased to 0, though a number like"0.99999999999999999999" has a chance of being rounded to 1.

RESTRICTION: The conversions marked with (*) above involve stepsperformed by the C compiler. In particular, bugs/features of the compilerused may lead to breakage of some of the above rules.

Flavors of Perl numeric operations

Perl operations which take a numeric argument treat that argument in oneof four different ways: they may force it to one of the integer/floating/string formats, or they may behave differently depending on the format ofthe operand. Forcing a numeric value to a particular format does notchange the number stored in the value.

All the operators which need an argument in the integer format treat theargument as in modular arithmetic, e.g., mod 2**32 on a 32-bitarchitecture. sprintf "%u", -1 therefore provides the same result assprintf "%u", ~0.

  • Arithmetic operators

    The binary operators + - * / % == != > <>= <= and the unary operators - abs and -- willattempt to convert arguments to integers. If both conversions are possiblewithout loss of precision, and the operation can be performed withoutloss of precision then the integer result is used. Otherwise arguments areconverted to floating point format and the floating point result is used.The caching of conversions (as described above) means that the integerconversion does not throw away fractional parts on floating point numbers.

  • ++

    ++ behaves as the other operators above, except that if it is a stringmatching the format /^[a-zA-Z]*[0-9]*\z/ the string increment describedin perlop is used.

  • Arithmetic operators during use integer

    In scopes where use integer; is in force, nearly all the operators listedabove will force their argument(s) into integer format, and return an integerresult. The exceptions, abs, ++ and --, do not change theirbehavior with use integer;

  • Other mathematical operators

    Operators such as **, sin and exp force arguments to floating pointformat.

  • Bitwise operators

    Arguments are forced into the integer format if not strings.

  • Bitwise operators during use integer

    forces arguments to integer format. Also shift operations internally usesigned integers rather than the default unsigned.

  • Operators which expect an integer

    force the argument into the integer format. This is applicableto the third and fourth arguments of sysread, for example.

  • Operators which expect a string

    force the argument into the string format. For example, this isapplicable to printf "%s", $value.

Though forcing an argument into a particular form does not change thestored number, Perl remembers the result of such conversions. Inparticular, though the first such conversion may be time-consuming,repeated operations will not need to redo the conversion.

AUTHOR

Ilya Zakharevich ilya@math.ohio-state.edu

Editorial adjustments by Gurusamy Sarathy <[email protected]>

Updates for 5.8.0 by Nicholas Clark <[email protected]>

SEE ALSO

overload, perlop

 
Source : perldoc.perl.org - Official documentation for the Perl programming language
Site maintained by Jon Allen (JJ)     See the project page for more details
Documentation maintained by the Perl 5 Porters
(Sebelumnya) Perl's fork() emulationPerl Performance and Optimizat ... (Berikutnya)