Python entry-level number

Source: Internet
Author: User
Tags floor division integer division
The topic of this article is numbers in Python. Describes each numeric type in detail, the various operators they apply, and the built-in functions used to process numbers. At the end of the article, I briefly introduced several modules used to process numbers in the standard library. Numeric type

Numbers provide scalar storage and direct access. It is a type that cannot be changed, that is, the value of a change number will generate a new object. Of course, this process is transparent to both programmers and users, and does not affect the way software is developed. Python supports multiple numeric types: integer, long integer, Boolean, double-precision floating point, decimal floating point, and plural.
Create a value object and assign values to it
(Numeric object)
Creating a value object is as simple as assigning a value to a variable:

The code is as follows:


>>> AnInt = 1
>>> Along =-555555555555L
>>> Afloat = 3.141595468565
>>> Acomplex = 1.334 + 4.5433j

Update numeric object

By assigning a value to a numeric object, you can "update" a numeric object. We quote these two words because you have not actually updated the original value of the object. This is because numeric objects cannot be changed. The object model of Python is somewhat different from the conventional object model. In your opinion, the update actually generates a new value object and gets its reference. In the process of learning programming, we have been receiving such education that variables are like a box containing variable values. In Python, variables are more like a pointer pointing to a box containing variable values. For unchangeable types, you cannot change the content of the box, but you can direct the pointer to a new box. Every time another number is assigned to a variable, a new object is actually created and assigned to the variable. (This is not just a number, but for all the unchangeable types)

The code is as follows:


AnInt + = 1
AFloat = 1, 2.718281828

Test with the following code:

The code is as follows:


>>> AnInt = 1
>>> Id (anInt)
10416152
>>> AnInt + = 1
>>> Id (anInt)
10416140

How to delete a numeric object

According to the Python rule, you cannot really delete a numeric object. you just don't use it anymore. If you want to delete a reference to a numeric object, use the del statement. After deleting an object reference, you cannot use this reference (variable name) unless you assign it a new value. If you try to reference a deleted object, a NameError exception is thrown.

The code is as follows:


Del anInt
Del aLong, aFloat, aComplex

Four main numeric types of Python

1. integer

Python has several integer types. Boolean is an integer with only two values. Regular integer is an integer that can be recognized by most modern systems. Python also has a long integer type. However, it indicates that the value is much larger than the long integer in C language. Next, let's take a look at these types, and then study the operators and built-in functions used for the Python integer type.

1.1 Boolean

Python supports the Boolean type from version 2.3. The value range of this type is only two values, namely, True and False.

1.2 standard integer type

The standard integer type of Python is the most common numeric type. On most 32-bit machines, the value range of the standard integer type is-231 to 231-1, that is,-2,147,483,648 to 2,147,483,647. If you use a 64-bit compiler to compile Python on a 64-bit machine, the integer in this system will be 64-bit. The following are examples of Python standard integer objects:
0101 84-237 0x80 017-680-0X92
The Python Standard integer type is equivalent to a C (signed) long integer. Integers are generally expressed in decimal format, but Python also supports octal or hexadecimal notation to represent integers. If the octal integer starts with the number "0", The hexadecimal integer starts with "0x" or "0X.

1.3 long integer

What we must mention about the Python long integer type is not to confuse it with the long integer type in C or other compiled languages. The typical value range of long integers in those languages is 32-bit or 64-bit. The value that can be expressed in the long integer type of Python is only related to the (virtual) memory size supported by your machine. In other words, Python can easily express large and large integers. The long integer type is a superset of the standard integer type. when your program needs an integer that is larger than the standard integer type, the long integer type can be used. Add an L (either in upper or lower case) after an integer to indicate that this integer is a long integer. This integer can be in decimal, octal, or hexadecimal format. Here are some examples of long integers:

The code is as follows:


16384L-0x4E8L 017L-2147483648l 052144364L
299792458l 0 xDECADEDEADBEEFBADFEEDDEAL-5432101234L
Edit By Vheavens
Edit By Vheavens

Core style: The long integer is represented by an uppercase letter "L". Currently, the integer and the long integer are gradually unified. you only need to call repr () for the long integer () "L" is displayed only when the function is used. if you call the str () function for a long integer object, you cannot see L. Example:

The code is as follows:


>>> ALong = 999999999l
>>> ALong
999999999L
>>> Print aLong
999999999

1.4 uniformity of integer and long integer

The two integer types are gradually unified into one. Before Python 2.2, objects of the standard integer type exceeded the value range (for example, the number greater than 232 mentioned above), but since Python2.2 there will be no such errors.

The code is as follows:


>>> 9999 ** 8
Traceback (most recent call last ):
File" ", Line 1, in?
OverflowError: integer exponentiation
Python 1, 2.2
>>> 9999 ** 8
99920027994400699944002799920001L

Double-precision floating point number

The floating point in Python is similar to the double type in C. It is a double-precision floating point. it can be expressed in decimal or scientific notation. Each Floating point occupies 8 bytes (64 bits) and fully complies with the IEEE754 standard (52 M/11E/1 S). 52 bits are used to represent the bottom, 11 bits are used to represent the exponent (the value can be expressed in the range of about 308.25 to the power of plus or minus 10), and the remaining bits represent the symbol. This looks perfect, however, the actual precision depends on the machine architecture and the compiler that creates the Python interpreter. Floating point values usually have a decimal point and an optional suffix e (in upper or lower case, indicating scientific notation ). Between e and an index, you can use positive (+) or negative (-) to indicate positive and negative values of the index. (if positive numbers are used, symbols can be omitted ). The following are examples of typical floating point values:

The code is as follows:


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

Plural

A combination of a real number and a virtual number forms a plural number. A plural number is an ordered floating point number (x, y ). X + yj, where x is a real number and y is a virtual number. Gradually, the plural has been widely used in daily operations, machinery, electronics, and other industries. As researchers repeatedly create tools for complex operations, in Python1.4, a long time ago, the plural has finally become a real Python data type.
The following are several concepts about plural in Python:

Virtual numbers cannot exist independently. they always form a complex number together with a real number with a value of 0.0.

A complex number consists of a real number and a virtual number.

Syntax for representing the virtual number: real + imagj

Both the real and virtual parts are floating point numbers.

The imaginary part must have a suffix j or J.


1. built-in attributes of the plural
The plural object has data attributes, namely the real and virtual parts of the plural. The complex number also has the conjugate method. you can call this method to return the complex number's compound number object.

Plural attribute

Attribute description
Num. real the real part of the plural
Num. imag the imaginary part of the plural number
Num. conjugate () returns the combination of the complex numbers.

The code is as follows:


>>> C = 2.3 + 2.5j
>>> C. real
2.3
>>> C. imag
2.5
>>> C. conjugate ()
(2.3-2.5j)

Operator

You can perform multiple operations on the numeric type. From Standard operators to numeric operators, there are even specialized integer operators.

5.5.1 mixed-mode operators

Python supports adding different numeric types. When an integer is added to a floating point number, the system determines whether to use the integer addition or the floating point addition (in fact, there is no mixed operation ). Python uses the numeric type forced conversion method to solve the problem of inconsistent numeric types, that is, it forcibly converts one operand to the same data type as the other operand. This operation is not random and follows the following basic rules:

First, if both operands are of the same data type, type conversion is unnecessary. Python checks whether an operand can be converted to another type only when the two operands have different types. If possible, convert it and return the conversion result.

Some conversions are impossible. for example, if a result converts a plural number to a non-plural type and a floating point number to an integer, the conversion process must follow several rules. To convert an integer to a floating point number, you only need to add a. 0 after the integer. To convert a non-plural value to a plural value, you only need to add a "0j" virtual number.

The basic principle of these types of conversion is: integer to floating point, non-plural to plural. The coerce () method is described as follows in the Python language reference:
If one operand is a plural value, the other operand is converted to a plural value.
Otherwise, if one operand is a floating point number, and the other operand is converted to a floating point number.
Otherwise, if one operand is a long integer, the other operand is converted to a long integer;
Otherwise, both must be common integers without type conversion.
The conversion between numeric types is automatically performed, and the programmer does not need to encode and process the type conversion by himself. Python provides coerce () built-in functions to help you implement this conversion.

The following flowchart illustrates the rules for forced conversion:

Arithmetic operators

Python supports single object operators (+) and minus (-), binary operators, +,-, *,/, %, and **, indicating addition, subtraction, multiplication, respectively, division, remainder, and power operation. From Python2.2, a new division operator // is added //.

Traditional division
For integer division, the traditional division removes the fractional part and returns an integer (floor Division ). If one of the operands is a floating point number, the real division is executed. Many languages, including Python, use this behavior. See the following example:

The code is as follows:


>>> 1/2 # perform integer result (floor) # floor Division
0
>>> 1.0/2.0 # returns actual quotient # Real division
0.5

Real division

Division operations always return the real operator, whether the operand is an integer or a floating point number. In future versions of Python, this will be the standard behavior of division operations. This can also be done by executing the from _ future _ import pision command.

The code is as follows:


>>> From _ future _ import pision
>>>
>>> 1/2 # returns real quotient
0.5
>>> 1.0/2.0 # returns real quotient
0.5

Floor Division

Starting from Python 2.2, a new operator // has been added to execute the floor Division: // Division, regardless of the numeric type of the operand, the fractional part is always removed, returns the nearest number in a number sequence that is smaller than the real quotient.

The code is as follows:


>>> 1 // 2 # floors result, returns integer # floor Division, return an integer
0
>>> 1.0 // 2.0 # floors result, returns float # return floating point number for floor Division
0.0
>>>-1 // 2 # move left on number line # returns an integer smaller than-0.5, that is,-1
-1

Power operation

The priority relationship between power operators and unary operators is special: power operators have lower priority than the unary operators in the left-side operations, and higher priority than the unary operators in the right-side operations, because of this feature, you will find two ** in the arithmetic operator table **. the following are examples:

The code is as follows:


>>> 3 ** 2
9
>>>-3 ** 2 # ** the priority is higher than the left-side-
-9
>>> (-3) ** 2 # brackets increase-priority
9
>>> 4.0 **-1.0 # ** the priority is lower than the-on the right-
0.25

In 2nd cases, the interpreter calculates 3 ** 2 and then obtains the opposite number. we need to add brackets to "-3" to get the expected result. In the last example, the result is 4 ** (-1), which is the result obtained according to the specified priority.

The code is as follows:


>>> 4 **-1
Traceback (innermost last ):

File" ", Line 1, in?
ValueError: integer to the negative power

The following is an example of more Python numeric operations:

The code is as follows:


>>>-442-77
-519
>>>
Edit By Vheavens
Edit By Vheavens
>>> 4 ** 3
64
>>>
>>> 4.2*3.2
98.7183139527
>>> 8/3
2
>>> 8.0/3.0
2.66666666667
>>> 3, 8%
2
>>> (60.-32.) * (5./9 .)
15.5555555556
>>> 14*0x04
56
>>> 0170/4
30
>>> 0x80 + 0777
639
>>> 45L * 22L
990L
>>> 16399L + 0xA94E8L
709879L
>>>-2147483648L-52147483648L
-54294967296L
>>> 64.375 + 1j + 4.23-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

* Bitwise operators (only applicable to integers)

Python integers support standard bitwise operations: inverse (~), Shifts by bit and (&), or (|), or (^), left (<), and right (> ). Python handles bitwise operations like this:
A negative number is treated as a two-digit complement of a positive number.
Shift left and shift right N bits are equivalent to the power operation of 2 without overflow check: 2 ** N.
For long integers, the bitwise operator uses a modified binary complement form, allowing the symbol bit to be infinitely expanded to the left. Reverse (~) The operation priority is the same as that of the single-digit operator. it is the highest priority among all bitwise operators. The left-and right-shift operations have the second priority, but are lower than the addition and subtraction operations. AND, OR, the unique or operation has the lowest priority. All bitwise operators are listed in Table 5.4 by priority

Built-in and factory functions

Standard functions
Cmp (), str () and type () built-in functions. These functions can be used for all standard types. For numeric objects, these functions compare the sizes of two numbers, convert numbers into strings, and return the types of numeric objects.

Conversion Factory functions
The int (), long (), float (), and complex () functions are used to convert other numeric types into corresponding numeric types. From Python2.3, a new member is added to the standard data type of Python: Boolean. Since then, the constant values of true and false are available (not 1 and 0)

The following are examples of using built-in functions:

The code is as follows:


>>> Int (4.25555)
4
>>> Long (42)
42L
>>> Float (4)
4.0
>>> Complex (4)
(4 + 0j)
>>>>>> Complex (2.4,-8)
(2.4-8j)
>>>
>>> Complex (2.3e-10, 45.3e4)
(2.3e-10 + 0000000j)

Function
Python has five built-in functions for numeric operations: abs (), coerce (), pmod (), pow (), pow (), and round (). We will browse these functions one by one and give some useful examples:

Abs () returns the absolute value of a given parameter. If the parameter is a complex number, math. sqrt (num. real2 + num. imag2) is returned)

Coerce () returns only one tuples containing two numeric elements after type conversion.

The pmod () built-in function combines division and remainder operations to return a tuple containing the quotient and remainder. The return value of an integer is the result of the floor Division and remainder operation. For floating point numbers, math. floor (num1/num2) is returned, and for the plural, ath. floor (num1/num2). real) is used ).

The code is as follows:


>>> Pmod (10, 3)
(3, 1)
>>> Pmod (10, 2.5)
(4.0, 0.0)
>>> Pmod (2.5, 10)
(0.0, 2.5)
>>> Pmod (2 + 1j, 2.3 + 4.3j)
(0j, (2 + 1j ))

Round () is used to round a floating point number. It has an optional decimal point parameter. If the decimal point parameter is not provided, it returns the nearest integer (but still floating point type) to the first parameter ). The second parameter tells the round function to specify the number of digits after the decimal point.

The code is as follows:


>>> Round (3)
3.0
>>> Round (3.154)
3.0
>>> Round (3.499999, 1)
3.5

>>> Import math
>>> For n in range (10 ):
Print round (math. pi, n)

3.0
3.1
3.14
3.142
3.1416
3.14159
3.141593
3.1415927
3.14159265
3.141592654

Built-in numeric functions:

Function
Abs (num) returns the absolute value of num.
Coerce (num1, num2) converts num1 and num2 to the same type, and then returns
Pmod (num1, num2) division-a combination of remainder operations. Returns a tuple (num1/num2, num1 % num2 ). Remove floating-point and plural operators
Pow (num1, num2, mod = 1) takes the num2 power of num1. if the mod parameter is provided, the computation result is used to perform the remainder operation on mod.
Round (flt, ndig = 0) accepts a floating point flt and rounding it to save the ndig decimal places. If the ndig parameter is not provided, the default value is 0 digits after the decimal point.
Round () is only used for floating point numbers.

Only applicable to integer built-in functions:

Function operations
Hex (num) converts a number to a hexadecimal number and returns it as a string.
Oct (num) converts a number to an octal number and returns it as a string
Chr (num) converts the number of ASCII values to ASCII characters in the range of 0 <= num <= 255
Ord (chr) accepts an ASCII or Unicode character (a string of 1) and returns the corresponding ASCII or Unicode value.
Unichr (num) accepts the Unicode code value and returns the corresponding Unicode character. The accepted code value range depends on whether your Python is built on ucs‐2 or ucs‐4.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.