The topic of this article is the numbers in Python. Details each of the numeric types, the various operators they apply to, and the built-in functions for working with numbers. At the end of the article, a few modules in the standard library for working with numbers are briefly introduced.
This article address: http://www.cnblogs.com/archimedes/p/python-number.html, reprint please indicate source address.
Number Type
The numbers provide scalar storage and direct access. It is a non-changeable type, meaning that the value of the change number generates a new object. Of course, this process is transparent to both the programmer and the user, and does not affect how the software is developed. Python supports multiple numeric types: integer, Long, Boolean, double, decimal, and complex.
Create a numeric object and use it to assign a value
(Numeric object)
Creating a numeric object is as simple as assigning a value to a variable:
>>> anint=1>>> along=-555555555555l>>> afloat=3.141595468565>>> acomplex=1.334 +4.5433j
update a numeric object
By assigning a value to a numeric object (re), you can "update" a numeric object. We enclose the update in quotation marks because you are not actually updating the original value of the object. This is because numeric objects are immutable objects . The object model of Python is somewhat different from the regular object model. What you think of the update is actually generating a new numeric object and getting a reference to it. In the process of learning programming, we have been taught that the variable is like a box containing the value of the variable. In Python, a variable is more like a pointer to a box that is loaded with variable values. You can't change the contents of a box for an immutable type, but you can point the pointer to a new box. each time you assign a different number to a variable, you actually create a new object and assign it to the variable. (not just numbers, for all immutable types)
Anint + =1 = 2.718281828
Test with the following code:
>>> anint=1>>> ID (anint)10416152>>> anint+=1>>> ID (anint) 10416140
How to delete a numeric object
According to Python's law, you can't really delete a numeric object, you just don't use it anymore. If you actually want to delete a reference to a numeric object, use the DEL statement . After you delete a reference to an object, you can no longer use the reference (the variable name) unless you assign it a new value. an Nameerror exception is thrown if an attempt is made to use an object reference that has been deleted.
Deldel
Python's four main number types 1. Integral type
Python has several integer types. A Boolean type is an integral type with only two values. Conventional integers are integral types that most modern systems can recognize. Python also has a long integer type. However, it represents a value that is much larger than a long integer in the C language. Let's take a look at these types and then look at the operators and built-in functions for Python integer types.
1.1 Boolean type
Python supports Boolean types starting from version 2.3. The value range for this type is only two values, which is the Boolean value True and the Boolean value False.
1.2 Standard integer types
The standard integer type of Python is the most common numeric type. On most 32-bit machines, the range of values for a standard integer type is 231 to 231-1, which is 2,147,483,648 to 2,147,483,647. If you compile Python with a 64-bit compiler on a 64-bit machine, the integer on this system will be 64 bits. Here are some examples of Python standard integer type objects:
0101 84-237 0x80 017-680-0x92
python standard integer type equivalent to C (signed) long integer。 Integers are generally represented in decimal, but Python also supports octal or hexadecimal notation for integers.If the octal integer starts with the number "0", the hexadecimal integer begins with "0x" or "0X".
1.3 Long integer type
About Python Long integer types What we have to mention is that you should not confuse it with the long integer type of C or other compiled languages. The typical value range for long integers of those languages is 32-bit or 64-bit.python's long integer type can express values only in relation to the (virtual) memory size supported by your machine, in other words, Python can easily express large, large, large integers. A long integer type is a superset of a standard integer type, and a long integer type is useful when your program needs to use an integer larger than the standard integer type.Add an L (uppercase or lowercase) after an integer value to indicate that the integer is a long integer. This integer can be in decimal, octal, or hexadecimal. Here are some examples of long integers:
16384l-0x4e8l 017l-2147483648l 052144364L
299792458l 0xdecadedeadbeefbadfeeddeal-5432101234l
Edit by Vheavens
Edit by Vheavens
Core style:long integers in uppercase letters "L", the current integer and long integers are gradually becoming unified, and you only have the opportunity to see "L" When you call the Repr () function on a long integer, and if you call the STR () function on a long integer object, you cannot see L. Examples are as follows:
>>> along = 999999999l >>>Print
1.4 Unification of integral type and long integer type
These two types of integers are being gradually unified into one. Before Python 2.2, a standard integer type object that exceeded the range of values would overflow (such as the above-mentioned number above 232), but there was no such error since Python2.2.
>>> 9999 * *8"<stdin>" in
Double-precision floating-point number
Floating-point numbers in Python are similar to the double type in the C language, and are two-precision floating-point numbers that can be represented by a direct decimal or scientific notation. Each floating-point number occupies 8 bytes (64 bits), fully complies with the IEEE754 number specification (52M/11E/1S), where 52 bits are used to represent the bottom, 11 bits are used to represent the exponent (which can represent a range of approximately 10 of a plus or minus 308.25), and the remaining bit represents the symbol. This looks quite perfect, however, the actual accuracy depends on the machine architecture and the compiler that created the Python interpreter. Floating-point values usually have a decimal point and an optional suffix e (uppercase or lowercase, which indicates scientific notation). The positive (+) or negative (-) can be used between the E and the exponent to indicate the positive and negative of the exponent (a positive word can omit the symbol). Here are some examples of typical floating-point values:
plural
A combination of a real number and an imaginary number forms a complex number. A complex number is a pair of ordered floating-point numbers (x, y). represented as X + YJ, where x is the real part, and Y is the part of the imaginary number. Gradually the plural in the daily operations, machinery, electronics and other industries have been widely used. As some researchers repeatedly manufacture tools for complex operations, in the Python1.4 version of a long time ago, the complex number finally became a true Python data type.
Here are a few concepts about complex numbers in the Python language:
Imaginary numbers cannot exist alone, and they are always combined with a real part with a value of 0.0 to form a complex number.
Complex numbers consist of real and imaginary parts
syntax to represent imaginary numbers: REAL+IMAGJ
Both the real and imaginary parts are floating-point numbers
The imaginary part must have a suffix of J or J.
1. Built-in properties of complex numbers
Complex objects have data attributes, which are the real and imaginary parts of the complex number, respectively. The complex number also has the Conjugate method, which calls it to return the complex's conjugate complex object.
Plural properties
Property Description
Num.real the real part of the plural
Num Num.imag The imaginary part of the complex number
Num.conjugate () returns the conjugate complex number of the complex number
>>> c=2.3+2.5j>>> c.real2.3>>> c.imag2.5>>> c.conjugate ( ) (2.3-2.5j)
Operator
Numeric types can perform multiple operations. There are even specialized integer operators, from standard operators to numeric operators.
5.5.1 Mixed-mode operators
Python supports the addition of different numeric types. When an integer and a floating-point number are added, the system determines whether to use integer addition or floating-point addition (there is no blending operation). Python uses the method of numeric type casting to resolve the problem of inconsistent numeric types , that is, it forces one operand to be converted to the same data type as the other operand. This is not an arbitrary operation, it follows the following basic rules:
First, if the two operands are of the same data type, there is no need for a type conversion. Python checks whether an operand can be converted to an operand of another type only if the two operand types are inconsistent. If you can, convert it and return the result of the conversion.
Because some conversions are not possible, the conversion process must follow several rules, compared to converting a complex number to a non-complex type, converting a floating-point to an integer, and so on. To convert an integer to a floating-point number, simply add a. 0 after the integer. To convert a non-complex to a complex number, you only need to add a virtual part of "0j".
The basic principle of these type conversions is that integers are converted to floating-point numbers, and non-complex numbers are converted to complex numbers. This describes the coerce () method in the Python language reference:
If one operand is a complex number, the other operand is converted to a complex number.
Otherwise, if one operand is a floating-point number, the other operand is converted to a floating-point number.
Otherwise, if one of the operands is a long integer, the other operand is converted to a long integer;
Otherwise, both must be ordinary integers, without type conversions.
Conversions between numeric types are automated, and programmers do not need to encode their own type conversions. Python provides coerce () built-in functions to help you implement this transformation.
See the following flowchart to illustrate the rules for casting:
Arithmetic operators
Python supports the monocular operator plus (+) and minus (-), binocular operators, +,-,*,/,%, and * *, which represent addition, subtraction, multiplication, division, take-up, and power operations, respectively. A new divisible operator//is also added from Python2.2.
Traditional Division
In the case of integer division, traditional division removes the fractional part and returns an integer (the floor is removed). If one of the operands is a floating-point number, True division is performed. Many languages, including the Python language, are this behavior. Look at the following example:
##
Real division.
The division operation always returns the real quotient, regardless of whether the operand is an integer or a floating-point number. In future versions of Python, this will be the standard behavior for division operations. This can also be done at this stage by executing the from __future__ Import Division Directive .
from __future__ Import ##
Floor removal
Starting with Python 2.2, a new operator//has been added in order to perform the floor except for://division Regardless of the operand's numeric type, always remove the fractional part, returning the nearest number in the number sequence that is smaller than the true quotient.
###
Power Operation
The precedence relationship between the exponentiation operator and the unary operator is special: The exponentiation operator has a lower precedence than the unary operator of its left operand, and has a higher precedence than the unary operator of the right operand, because of this feature you will find two * * in the arithmetic operator table. Here are a few examples:
###
In the 2nd case, the interpreter calculates the 3**2 and then takes the opposite number, we need to give "3" parentheses to get the result of our hope. In the last example, the result is 4** (-1), which is the result of a given priority.
Traceback (innermost last):
File "<stdin>", line 1, in?
Valueerror:integer to the negative power
Here are more examples of Python numerical operations:
>>> -442-77-519 >>>edit by Vheavens edit by Vheavens>>> 4 * * 3 >>> >>> 4.2 * 3.2 98.7183139527 >>> 8/3 2 >>> 8.0/3.0 2.66 666666667 >>> 8 3 2 >>> (60.-32.) * (5./9. ) 15.5555555556 >>> * 0x04 >>> 0170/4 >>> 0x80 + 0777 639 >>> 45L * 22L 990L >>> 16399L + 0xa94e8l 709879L >>> -2147483648l-52147483648l-54294967296l >>> 64.375+1j + 4.2 3-8.5j (68.605-7.5j) >>> 0+1j * * 2#Same as 0+ (lj**2)( -1+0j)>>> 1+1j * * 2#Same as 1+ (lj**2)0j>>> (1+1J) * * 2 2j
View Code
* Bitwise operator (for integers only)
Python integers support standard bit operations: Negation (~), bitwise-AND (&), or (|) and XOR (^) and left (<<) and right-shift (>>). Python handles bit operations like this:
A negative number is treated as a positive 2-step complement.
The left and right shift n bits are equal to the N power operations of 2 without overflow checking: 2**n.
For long integers, the bitwise operator uses a modified 2-complement form to allow the symbol bits to extend infinitely to the left. The precedence of the inverse (~) operation is the same as the numeric monocular operator, which is the highest priority in all bitwise operators. The left and right shift operations take precedence, but are lower than the addition and subtraction operations. With, or, the lowest precedence of the XOR operation. All bitwise operators are listed in Table 5.4 by priority level
Built-in functions and factory functions
Standard type Functions
CMP (), str (), and type () built-in functions. These functions can be used with all standard types. For numeric objects, these functions compare the size of two numbers, convert numbers to strings, and return the type of a numeric object.
Convert factory Functions
the function int (), long (), float (), and complex () are used to convert other numeric types to the corresponding numeric types. Starting with Python2.3, Python's standard data type adds a new member: A Boolean (Boolean) type. From this, true and false now have constant values that are true and false (no longer 1 and 0)
Here are some examples of using built-in functions:
>>> Int (4.255554 >>> Long (42L >>> Float (44.0 >>> Complex (4) (4+>>>>>> Complex (2.4,-8) (2.4-8j>>> >>> Complex (2.3e-10, 45.3e4) (2.3e-10+453000j)
function Function
Python has five arithmetic built-in functions for numerical operations: ABS (), coerce (), Divmod (), pow (), pow (), and round (). We'll take a look at each of these functions and give some useful examples:
ABS () returns the absolute value of the given parameter. If the argument is a complex number, it returns MATH.SQRT (Num.real2 + num.imag2)
Coerce () returns only one tuple containing two numeric elements of type conversion complete
The Divmod () built-in function combines division and take-rest operations to return a tuple containing quotient and remainder. For integers, the return value is the result of the floor addition and the fetch operation. For floating-point numbers, the returned quotient part is Math.floor (NUM1/NUM2), and for the plural, the quotient part is Ath.floor ((num1/num2). Real).
>>> Divmod (3) (3, 1)>>> divmod (2.5) (4.0, 0.0)>> > divmod (2.5, 0.0, 2.5)>>> divmod (2+1j, 2.3+4.3j) (0j, (2+1j))
Round () is used to round up floating-point numbers. It has an optional number of decimal digits parameter. If you do not provide a decimal parameter, it returns the integer closest to the first parameter (but still a floating-point type). The second parameter tells the round function to precisely specify the number of digits after the decimal point.
>>> round (3)3.0>>> round (3.154)3.0>>> round (3.499999, 1) Import math for in range: print round (Math.PI, N) 3.03.13.143.1423.14163.141593.1415933.14159273.141592653.141592654
Numerical operations built-in functions:
function function
ABS (num) returns the absolute value of num
Coerce (NUM1, num2) converts NUM1 and num2 to the same type and then returns as a tuple
Divmod (NUM1, num2) division-the combination of the take-rest operation. Returns a tuple (num1/num2,num1% num2). Rounding of floating-point and plural quotient
The POW (NUM1, num2, mod=1) takes the num2 of the NUM1, and if the MoD parameter is supplied, the result of the calculation is then the remainder operation of the MoD.
Round (FLT, ndig=0) accepts a floating-point number flt and rounds it, saving ndig decimal places. If the Ndig parameter is not provided, the default is 0 digits after the decimal point
Round () only for floating-point numbers
Built-in functions that apply only to integers:
function operation
Hex (num) Converts a number to hexadecimal number and returns as a string
The OCT (num) converts numbers into octal numbers and returns them as strings
Chr (num) converts the number of ASCII values to ASCII characters, which can range from only 0 <= num <= 255
Ord accepts an ASCII or Unicode character (a string of length 1) and returns the corresponding ASCII or Unicode value.
UNICHR (NUM) accepts Unicode code values and returns their corresponding Unicode characters. The range of code values accepted depends on whether your Python is built on ucs‐2 or ucs‐4
Python Basics (10)--Digital