5 types

int

integers are represented using base-2(binary) digits, not base-10(decimal)

10011(base-2) required 5 bits

what’s the range of integer number can be represented using 8 bits?

11111111(base-2) required 8 bits, could represent largest 255

Using 8 bits are able to represent range [-127, 127], since 0 does not require a sign, we can squeeze out an extra number to [-128, 127]

How large an integer can be depends on how many bits are used, some languages(Java, C) provide multiple distinct integer types that use a fixed number of bits. Python doesn’t work that way, the int object uses a variable number of bits, can use 32, 64, 96 bits etc.(increase bits by need)

int arithmetic
  • int +(-, *, **, //, %) int => int
  • int / int => float

integer base change algorithm


Fraction

represent rational number


float

represent real number

CPython float is implemented using the C double type which implements the IEEE double-precision binary float, also called binary64

float uses a fixed number of bytes, in standard, CPython/3.6/64bits using 8 bytes(64 bits)

representation
  • decimal
  • binary

problem: some numbers do not have a finite representation

  • 1/3 can not represent accurate by decimal expansion
  • 1/10 can not represent accurate by binary expansion

Coercing float to integer -> data loss

truncation: math.trunc(), constructor of int() use truncation

floor: math.floor()

ceiling: math.ceil()

round: round()

Banker’s Rounding

decimal

avoid the approximation issues with floats

why not just use Fraction?

complex computation and extra memory using, to add two fractions needs common denominator, and simplify also. E.x. 1/10 + 2/5 = 5/10 = 1/2

why not just use float?

finance, banking where exact finite representations are required

context

decimals have a context that controls certain aspects:

  • precision during arithmetic operations
  • rounding algorithm

this context can be global(default) or local

decimal vs float

  • not easy to code like float object
  • not all mathematical function or database aggregation supported
  • more memory overhead
  • much slower performance than floats

Complex Number

Boolean

subclass of int

True and False are singleton objects, they will always retain their same memory address throughout the lifetime of your application, therefore you can use operator either is or ==

All object in Python have an associated truth value, except:

  • None
  • False
  • 0, 0+0j
  • empty sequences
  • empty mapping type
  • custom class implement __bool__ or __len__

Operator Precedence

  1. ()  # use parentheses to make more readable
  2. >, >=, <, <=, ==, !=, in, is
  3. not
  4. and
  5. or

Short-Circuit Evaluation

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。