5.1 Number types
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.
How to update a numeric object
Because you don't actually update 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
Afloat = 2.718281828
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 (see 3.5.6). To delete a reference to an object
, you can no longer use this reference (the variable name) unless you assign it a new value. If an attempt is made to use a
A Nameerror exception is thrown when an object reference is deleted.
Del Anint
Del along, afloat, Acomplex
5.3 Double-precision floating-point numbers
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:
0.0-777. 1.6-5.555567119 96e3 * 1.0
4.3e25 9.384e-23-2.172818 Float (12) 1.000000001
3.1416 4.2e-10-90. 6.022e23-1.609e-19
5.4 plural
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.
Here are some examples of complex numbers:
64.375+1j 4.23-8.5j 0.23-8.55j 1.23e-045+6.7e+089j
6.23+1.5j-1.23-875j 0+1j 9.80665-8.31441j-.0224+0j
Table 5.1 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
>>> Acomplex = -8.333-1.47j
>>> Acomplex
( -8.333-1.47j)
>>> Acomplex.real
-8.333
>>> Acomplex.imag
-1.47
>>> Acomplex.conjugate ()
( -8.333+1.47j)
Table 5.1 describes all the properties of a complex number
5.5.1 Mixed-mode operators
As you may recall, when you add two numbers in the past, you must try to ensure that the operands are of the appropriate type. Naturally, addition always uses the + sign, but in computer language it's not that simple, because there are many different types of numbers.
When two integers are added, the + sign represents an integer addition, and when two floating-point numbers are added, + represents the floating-point number addition, and so on. In Python, even non-numeric types can use the + operator. For example, the string A + string B does not represent an addition operation, it means that the two strings are concatenated to generate a new string. The key is to support each data type of the + operator, and you must tell Python how the + operator should work. This also embodies the specific application of the overload concept.
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. Converts an integer to a floating-point number, as long as the integer is appended with a. 0. 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 the need for type conversions
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:
>>> # Perform integer result (floor) # flooring except
0
>>> 1.0/2.0 # Returns actual quotient# true Division
0.5
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 Division
>>>
>>> # returns Real quotient
0.5
>>> 1.0/2.0 # returns real quotient
0.5
Floor removal
Starting with Python 2.2, a new operator//has been added in order to perform the floor except://Division Not
The number of numeric types that a tube operand always removes, and returns the nearest number in a sequence of numbers that is smaller than the true quotient.
>>> 1//2 # Floors result, returns integer # floor except, return integer
0
>>> 1.0//2.0 # Floors result, returns float # floor except, return floating-point number
0.0
>>>-1//2 # Move left on number line# returns an integer smaller than –0.5, which is-1
-1
Power operation
The precedence relationship between the exponentiation operator and the unary operator is particularly special: The power operator is more than its left-hand operand
The unary operator has a lower precedence than
The unary operator of the right-hand operand is of high priority, because of this feature you will find two in the arithmetic operator table
* *. Here are a few examples:
>>> 3 * * 2
9
>>>-3 * * 2 # * * Priority higher than left-
-9
>>> (-3) * * 2 # Parentheses Increase-the priority level
9
>>> 4.0 * *-1.0 # * * Priority lower than right-
0.25
5.6.2 Numeric type functions
Python now has a series of built-in functions for numeric types. Some functions are used for numeric type conversions, while others perform some common operations.
Convert Factory functions
the function int (), long (), float (), and complex () are used to convert other numeric types to the corresponding numeric types.
Here are some examples of using built-in functions:
>>> Int (4.25555)
4
>>> Long (42)
32k
>>> Float (4)
4.0
>>> Complex (4)
(4+0J)
>>>
>>> Complex (2.3e-10, 45.3e4)
(2.3E-10+453000J)
Table 5.5 Summary of numerical factory functions
Class (Factory function) operation
BOOL (obj) b returns the Boolean value of the Obj object, which is the return value of the obj.__nonzero__ () method
int (obj, base=10) returns an integer representation of a string or numeric object, similar to String.atoi (); From Python 1.6,
A long (obj, base=10) returns a character or a length integer representation of a data object, similar to String.atol (), from ython1.6 Optional input parameters are introduced.
Float (obj) returns a floating-point representation of a string or data object, similar to String.atof () complex (str) Orcomplex (real, imag=0.0) returns the plural representation of a string
function function
Python has five arithmetic built-in functions for numerical operations: ABS (), coerce (), Divmod (), pow (), pow ()
and round ().
ABS () returns the absolute value of the given parameter. If the argument is a complex number, it returns MATH.SQRT (Num.real2 +
Num.imag2). Here are some examples of abs () functions:
>>> ABS ( -1)
1
>>> ABS (10.)
10.0
>>> ABS (1.2-2.1j)
2.41867732449
>>> abs (0.23-0.78)
0.55
Function coerce (), Although technically it is a data type conversion function, it behaves more like an arithmetic
character, so I put it in this section. In the 5.5.1 section, we discussed how Python performs numeric type conversions. The
Function coerce () provides the programmer with a way to customize two numeric type conversions without relying on a Python interpreter.
This feature is useful for a newly created numeric type. The function coerce () returns only one tuple that contains the two numeric elements for which the type has finished converting
. Here are a few examples:
>>> coerce (1, 2)
(1, 2)
>>>
> >> Coerce (1.3, 134L)
(1.3, 134.0)
>>>
>>> coerce (1, 134L)
(1L, 134L)
>>
>>> Coerce (1j, 134L)
(1j, (134+0j))
>>>
>>> coerce (1.23-41j, 134L)
( (1.23-41j), (134+0J)) the
Divmod () built-in function combines division and take-rest operations to return a tuple containing quotient and remainder. For an integer, the
says that its 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 (10,3)
(3, 1)
>>> divmod (3,10)
(0, 3)
>>> Divmod (10,2.5)
(4.0, 0.0)
>>> Divmod (2.5,10)
(0.0, 2.5)
>>> Divmod (2+1j, 0.5-1j)
(0J, (2+1j))
Both the function pow () and the Double star (* *) operators can perform exponential operations. But the difference is not just
One is the operator and the other is the built-in function.
Before Python 1.5, there were no * * operators. The built-in function pow () also accepts a third optional parameter, a
The remainder parameter. If you have this parameter, the POW () first takes an exponential operation and then takes the result of the operation and the third parameter
The remainder operation. This feature is primarily used for cryptographic operations and is better than the POW (x, y)% Z performance, because the function
Implementation is similar to the C function pow (x, y, z).
>>> Pow (2,5)
32
>>>
>>> Pow (5,2)
25
>>> Pow (3.141592,2)
9.86960029446
>>>
>>> Pow (1+1j, 3)
( -2+2J)
The built-in function, round (), is used to round up floating-point numbers. It has an optional number of decimal digits parameter. If
does not provide a decimal parameter that returns the integer closest to the first argument (but still a floating-point type). The second parameter tells
The round function accurately assigns the result to the specified number of digits after the decimal point.
>>> Round (3)
3.0
>>> Round (3.45)
3.0
>>> Round (3.4999999)
3.0
>>> round (3.4999999, 1)
3.5
>>> Import Math
It is important to note that the round () function is rounded by rounding the rules. That is, round (0.5) gets 1,
Round (-0.5) gets-1. Look at Int (), round (), Math.floor () These functions seem to be doing the same thing.
, it's easy to confuse them, isn't it? The differences between them are listed below:
?? the function int () truncates the fractional part directly. (The return value is an integer)
?? The function floor () Gets the integer closest to the original number but less than the original number. (return value is floating point)
?? The function round () gets the integer nearest to the original number. (return value is floating point)
?? The example uses four positive numbers and four negative numbers as the parameters of these three functions, and compares the returned results to a list.
(For comparison purposes, we also convert the return value of the Int () function to a floating-point number).
Int (0.2) +0.0
Floor (0.2) +0.0
Round (0.2) +0.0
--------------------
Int (0.7) +0.0
Floor (0.7) +0.0
Round (0.7) +1.0
--------------------
Int (1.2) +1.0
Floor (1.2) +1.0
Round (1.2) +1.0
--------------------
Int (1.7) +1.0
Floor (1.7) +1.0
Round (1.7) +2.0
--------------------
Int (-0.2) +0.0
Floor (-0.2)-1.0
Round (-0.2) +0.0
Built-in functions for integers only
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.
5.7.1 boolean "Number"
Starting with Python2.3, the Boolean type is added to Python. Although Boolean values appear to be "True" and "False,"
But in fact it is a subclass of integer, corresponding to 1 and 0 of integers. The following are the main concepts about Boolean types:
?? There are two values that never change to True or false.
?? A Boolean is a subclass of an integral type, but can no longer be inherited to produce its subclasses.
?? The default value of an object without the __nonzero__ () method is True.
?? For any number that has a value of zero or an empty set (empty list, empty tuple, empty dictionary, and so on), the Boolean value in Python is false.
?? In mathematical operations, the Boolean value of true and false corresponds to 1 and 0, respectively.
?? Most standard library functions and built-in Boolean functions that previously returned integers now return a Boolean type.
?? Both True and false are now not keywords, but will be in future versions of Python.
5.8 Related Modules
There are many modules in the Python standard library dedicated to handling numeric type objects, which enhance and extend the built-in functions
Functions of the function and numerical operations. Table 5.8 Lists a few of the more core modules. To learn more about these modules, see
Documents or online documentation for these modules.
For advanced digital Scientific computing applications, you will be interested in the famous third party package Numeric (NumPy) and scipy
Interesting. For more information about these two packages please visit the following URL.
http://numeric.scipy.org/
http://scipy.org/
Table 5.8 Number Type related modules
Module Introduction
Decimal decimal floating-point arithmetic class decimal
Array of efficient numeric arrays (characters, integers, floating-point numbers, etc.)
Math/cmath standard C library mathematical operation function. General mathematical operations in the match module, complex operations in the Cmath module
The function implementation of the operator numeric operator. such as Tor.sub (m,n) equivalent
Core module: Random
When your program requires random numbers, the random module can be useful. The module contains multiple pseudo-random number occurrences
With the current timestamp as a random number seed. This allows you to start working whenever you load the module. The following columns
The most commonly used functions in this module are:
Two integer arguments that return a random integer between the two
Randrange () it takes the same parameters as the range () function, and returns a random range ([start,]stop[,step]) result.
Uniform () is almost the same as Randint (), but it returns a floating-point number between the two (excluding the range cap).
Random () similar to uniform () only the lower bound constant equals 0.0, the upper limit is equal to 1.0
Choice () randomly returns an element of a given sequence (for a sequence, see chapter sixth)
Fifth chapter number