2. Numbers
Contents:
Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin. - John von Neumann (1951) 2.0. IntroductionNumbers, the most basic data type of almost any programming language, can be surprisingly tricky. Random numbers, numbers with decimal points, series of numbers, and the conversion of strings to numbers all pose trouble. Perl works hard to make life easy for you, and the facilities it provides for manipulating numbers are no exception to that rule. If you treat a scalar value as a number, Perl converts it to one. This means that when you read ages from a file, extract digits from a string, or acquire numbers from any of the other myriad textual sources that Real Life pushes your way, you don't need to jump through the hoops created by other languages' cumbersome requirements to turn an ASCII string into a number.
Perl tries its best to interpret a string as a number when you use it as one (such as in a mathematical expression), but it has no direct way of reporting that a string doesn't represent a valid number. Perl quietly converts non-numeric strings to zero, and it will stop converting the string once it reaches a non-numeric character - so "
Recipe 2.16
shows how to get a number from strings containing hexadecimal or octal representations of numbers like " As if integers weren't giving us enough grief, floating-point numbers can cause even more headaches. Internally, a computer represents numbers with decimal points as floating-point numbers in binary format. Floating-point numbers are not the same as real numbers; they are an approximation of real numbers, with limited precision. Although infinitely many real numbers exist, you only have finite space to represent them, usually about 64 bits or so. You have to cut corners to fit them all in.
When numbers are read from a file or appear as literals in your program, they are converted from decimal representation (e.g., 0.1) to internal representation. 0.1 can't be precisely represented as a binary floating-point number, just as 1/3 can't be exactly represented as a non-repeating decimal number. The computer's binary representation of 0.1, therefore, isn't exactly 0.1. To 20 decimal places, it is
Performing arithmetic on
binary representations of floating-point numbers can accumulate errors in the representations. In the preceding example,
Recipe 2.4
shows how to convert an ASCII string representing a binary number (e.g., "
Random numbers are the topic of several recipes. Perl's We round out the chapter with recipes on trigonometry, logarithms, matrix multiplication, complex numbers, and the often-asked question: "How do you put commas in numbers?" Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|