# Three: Python object type detailed one: number (bottom)

Source: Internet
Author: User

One: bit operation

In addition to general mathematical operations, Python supports most mathematical expressions in C language. This includes operations that treat integers as bits strings . For example, you can also implement displacements and Boolean operations:

`>>> x = 1   #0001>>> x << 2  #shift left 2 bits:01004& Gt;>> x | 2   #Bitwise or:00113>>> x & 1  #Bitwise and:00011`

This bitwise-masking operation allows us to encode multiple flags and values for an integer. Here, we're not too involved in more detail about "bit arithmetic". If necessary, it is supported. In python3.1, the Bit_length method of integers also allows us to query the number of binary bits required to represent the value of a number in binary notation. In addition, by using the bin () and the built-in function Len () to get the length of the binary string, and then subtract 2, you can often get the same result, albeit less efficient:

`>>> x = 99>>> bin (x), X.bit_length () ('0b1100011', 7) >>>bin (+), (bit_length) ('0b100000000', 9)>> > Len (BIN)-2    # string length minus the digital-binary flag ' 0b ' two-bit length 9`

Second: Other built-in math tools

In addition to the core object types, Python supports built-in functions and built-in modules for digital processing. Built-in function pow (), ABS (), Calculate power and absolute value, respectively. Here are some built-in math modules that contain most of the tools in the math library in C.

`>>> ABS ( -42.0), sum ((1,2,3,4))  #sum () acts on a sequence of numbers (42.0,10)>>>min ( 3,1,2,4), Max (3,1,2,4)  #min () and Max () functions accept a parameter sequence or a single parameter (1,4)`

Note that modules such as built-in math must be imported first, but built-in functions such as ABS () do not need to be imported for direct use. In other words, the module is an external component, and the built-in function is in an implicit namespace, and Python automatically searches for the program's variable name. This namespace corresponds to a module named Builtins in python3.0 (__builtin__ in python2.6).

Three: Decimal type:

A) Fractional numbers: Decimals are created by calling the function after an imported module, rather than by allowing constant expressions. Functionally, decimal objects are like floating-point numbers, except that they have fixed digits and decimal points, so decimals are floating-point numbers with fixed precision . The fractional type is an ideal tool for performance of fixed precision features (e.g., sum of money) and for better digital accuracy. We were able to produce a decimal object by calling the constructor of the decimal in the decimal module and passing in a string . This string has the number of decimal digits we want to display in the result. When the intensive reading is not the same, Python automatically upgrades to the largest number of decimals:

`>>>0.1 + 0.1 + 0.1-0.3#lack of accuracy of floating point numbers5.5511151231257827e-17>>>Print(0.1 + 0.1 + 0.1-0.3)#using print still doesn't solve the problem5.55111512313e-17>>>>>>>>> fromDecimalImportDecimal#You can use decimal operations to solve>>>decimal ('0.1') + Decimal ('0.1') + Decimal ('0.1')-Decimal ('0.3')#The result is a decimal placeDecimal ('0.0')`

In python3.1, you will be able to create a decimal object from a floating-point object, via decimal. Decimal.from_float (1.25) Form of invocation. This conversion is accurate, but sometimes produces more digits.

b) Set global precision: Other tools in the decimal module can be used to set the precision of all decimal values, set error handling, and so on. For example, a context object in this module allows you to specify the precision (number of decimal digits) and rounding mode (loft, rounding, and so on). This precision applies globally to all decimals created in the calling thread:

`>>> fromDecimalImportDecimal>>>decimal ('1')/Decimal ('7') Decimal ('0.1428571428571428571428571429')>>>Importdecimal>>>decimal.getcontext (). Prec = 4>>> Decimal ('1')/Decimal ('7') Decimal ('0.1429')`

c) Decimal Context Manager: You can use the Context Manager statement to reset the temporal precision. After the statement exits, the precision is set to the initial value:

`>>>Importdecimal>>> Decimal. Decimal ('1.00')/Decimal. Decimal ('3.00') Decimal ('0.333333333333333333333')>>>>>>With Decimal.localcontext () as CTX: ... Ctx.prec= 2... decimal. Decimal ('1.00')/Decimal. Decimal ('3.00') ... Decimal ('0.33')>>>>>> Decimal. Decimal ('1.00')/Decimal. Decimal ('3.00') Decimal ('0.333333333333333333333')`

Four: Score Type:

A) score creation: 1, fractions are used in a way that is similar to decimals, which is also present in the module; importing its constructor and passing a numerator and a denominator can produce a fraction.

2, a fractional object can also be created from a floating-point string , which is similar to a decimal.

`>>> fromFractionsImportFraction#To create a fractional object with a constructor function>>>x = fraction (1,3)#Numerator,denominator>>>y = fraction (4,6)>>> fromFractionsImportFraction#To create a fractional object with a floating-point string>>>fraction ('.') fraction (1,4)>>>fraction ('1.25') fraction (5,4)`

b) Numerical accuracy: In fact, the score remains accurate and the result is automated.

`>>>fromimport# fractional automation Jane >>>fraction (6,12) fraction ( )`

c) Conversion and blending types: In order to support fractional conversions, floating-point objects now have a method (Float.as_integer_ratio ()) that can produce their numerator and denominator ratios, and fractions have a from_float method, and float accepts a fraction as a parameter. (In the test * is a special syntax that extends a tuple into a single parameter)

`>>> (2.5). As_integer_ratio ()  #Float Object Method(5,2)>>>> >>f = 2.5>>>z = Fraction (* (F.as_integer_ratio ()))  #Convert float->fraction:two Args>>>zfraction (5,2)>>>>>>fraction.from_float (1.75) Fraction (7,4)>>>>>>fraction (* (1.75). As_integer_ratio ())  # Convert float->fraction:other Fraction (7,4)`

Mixed type: fraction + int->fraction

Fraction + Float

Fraction + fraction->fraction

Warning: Although floating-point numbers can be converted to fractions, in some cases there is an unavoidable loss of precision when doing so, since this number is imprecise in its original floating-point form. When needed, we can simplify such a result by limiting the maximum denominator value (Fraction.limit_denominator (n), where n is the maximum of the denominator):

`>>>4.0/3>>>1.3333333333333>>>x = (4.0/3). As_integer_ratio ()  #  Precision loss from float to fraction>>>x (6004799503160661, 4503599627370496)> >>>>>a = Fraction (* (4.0/3). As_integer_ratio ())>>>afraction ( 6004799503160661, 4503599627370496)>>>>>>a.limit_denominator (Ten) Fraction ( 5,3)`

V: Collection

A collection (set) is a new type, which is an unordered collection of some unique, immutable objects (collection). By definition, an item appears only once in the collection, no matter how many times it is added. Collections can be iterated, grow or shorten as needed, and can contain a variety of object types.

A) collection creation: To create a collection object, pass a sequence or other iterative object to the built-in set () function; The collection does not contain positional information, it is a set of unordered collections, and the collection supports general mathematical set operations through expression operators. Warning: You cannot apply these expressions on a generic sequence, you must create a collection from a sequence before you can use these tools.

b) operator of the set: ' In ' (membership), '-' (difference), ' | ' (Union), ' & ' (intersection), ' ^ ' (XOR), ' > ' (superset), ' < ' (subset) ...

c) How the collection operates: Add () (insert an item), Updata () (by location), remove () (deletes an item by value) Notice: Allows Dir to view all available methods on any collection instance or collection type name.

D) as an iterative container, the collection can also be used in operations such as Len, for loops, and list parsing, however, because they are unordered, all operations such as indexes and shards are not supported.

e) Although the set expressions described above typically require two collections, they are often valid for any iteration type based on the corresponding form of the method. Notice: isinstance (object,iterable) can be used to determine if an object is an iterator .

`>>>x = Set ('ABCDE')#The following tests are run in python2.6>>>y = Set ('bdxyz')#Create a collection in python2.6>>>Xset (['a','b','C','D','e'])>>>>>>'e' inchX#operator TestTrue>>>z = x.intersection (y)#x & y #方法测试>>>Zset (['b','D'])>>>z.add ('spam')>>>Zset (['b','D','spam'])>>>z.update (Set (['X','Y']))#In-place Union>>>Zset (['b','D','spam','X','Y'])>>>z.remove ('b')>>>Zset (['D','spam','X','Y'])>>>>>>>>>s = Set ([All])>>>s.union ([3,4])#A collection of methods can be used for any object of an iterative type, and the list type is an iterative objectSet ([1,2,3,4])>>>s.intersection ((1,3,5))#tuple is an iterative objectSet ([1,3]) S.issubset (range (-5,5))#determining the range of elements in the S collection is not between [ -5,5]True`

VI: Collection Constants in Python 3.0

A) in python3.0, set ([1,2,3,4]) and {1,2,3,4} are equivalent, the previous one is the 2.6 version of the collection form, followed by the 3.0 version of the collection form. Regardless of how the collection is created, version 3.0 displays it using the new constant format. However, built-in set functions are required in the 3.0 release to create an empty collection or to build a collection from an existing iteration object.

Warning: Immutable restriction: The collection can only contain immutable (hash-able) object types. Therefore, lists and dictionaries cannot be embedded in the collection, but if you need to store composite values, tuples can be embedded.

The set itself is immutable, so it cannot be embedded directly into other collections, and if you need to store a collection in another collection, you can call frozenset like set, but it creates an immutable collection that cannot be modified and can be nested into other collections.

`>>>s = {1}>>>s.add ([2,3]) typeerror:unhashable type:'List'>>>s.add ({'a': 1}) typeerror:unhashable type:'Dict'>>>s.add ((2,3))>>>s{1, (2,3)}#No list or dict,but tuple okay>>>>>>s = Frozenset ([up])#methods for embedding collections in a collection>>>z = Set ([3,4])>>>Z.add (s)>>>Z{frozenset ({1, 2}), 3, 4}`

VII: Set parsing in Python 3.0:

In addition to constants, Python 3.0 introduces a set parsing construct, similar to the described form of list parsing, but is written in curly braces instead of square brackets and is used for collections instead of lists. The result is a new collection that is created by running the code.

` for inch [1,2,3,4]}  # Set Resolution {16,1,4,9}`
View Code

Eight: Why use a collection?

Because items are stored only once in the collection, the set can be used to filter out duplicates from other sets (collection). That is, you can filter out duplicates in a list.

`>>>l = [1,2,3,1,2,4,5]   # filters out duplicate elements in the list L >>>set (l) {1,2,3,4,5} >>>l = List (set (L))>>>l[1,2,3,4,5]`

Nine: Boolean type

Python now formally has a definitive Boolean data type called bool, with a value of true and false, with a value of true and false being a pre-defined built-in variable name. Internally, only a subclass of the built-in integer type int (viewed in an object-oriented perspective) behaves like integers 1 and 0, but they have specific display logic: they are displayed as the keyword True and false, not the numbers 1 and 0 (technically: bool The string format of STR and REPR has been redefined for its two objects. In addition, Boolean values make the truth more accurate. Eg: an infinite loop can now be written as while True: instead of while 1:. Similarly, flag bits can be set more clearly by using flag = False.

Three: Python object type detailed one: number (bottom)

Related Keywords:
Related Article

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.