Home      |       Contents       |       About

Prev: -       |       Next: Strings

Numerics

Integers

  • Integers are generated from the 'int' class
  • Precision for integer representation is not limited: Python 3 dynamically allocates the necessary memory space to represent arbitrary long integers. The only limit is the computer physical memory
In [1]:
a = 10
b = 20
print(a + b)

c = 2**1000   
c
30
Out[1]:
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
  • Arithmetic operators
In [36]:
a = 4
b = 25
a+b, a-b, a*b, a/b, b/a, b//a, b%a, b**a

# Addition '+'
# Subtraction '-'
# Multiplication '*'
# Division '/'
# Integer (floor) division '//'
# Modulus (remainder division) '%'
# Exponent '**' 
Out[36]:
(29, -21, 100, 0.16, 6.25, 6, 1, 390625)
  • Comparison operators

    See more about operators here

In [42]:
a = 5
b = 20
a == b
# Other comparison operators: <, >, >=, <=, != (not equal), <> (not equal)
Out[42]:
False

Floats

  • Floating point numbers ('floats' or 'reals') are generated from the 'float' class
  • Python follows the IEEE 754 for float numbers representation. All floats are represented as 'double precision' numbers which means: 64 bits totally distributed as follows:

    • Significand part: 52 bits + 1 bit for sign
    • Exponent part: 11 bits
  • Smaller float: ca. 5.0*1e-324, Largest float: ca. 1.8*1e308

In [2]:
a = 5e3
a+1
Out[2]:
5001.0
In [3]:
b = 1e-1
b+1
Out[3]:
1.1
In [4]:
x = 13.5
y = 0.8
k = x**y
k
Out[4]:
8.021711060847016
  • Watch out for precision limitations in floats
In [86]:
a = 0.1
b = 0.2
a+b            

# Why?
Out[86]:
0.30000000000000004

See more on float precision here

  • Some suggestions on how to deal with float precision limitations
In [92]:
# 1) Use the 'round()' function
a = 0.1
b = 0.2
print(a+b, round(a+b,2))

# 2) Control not for equality but for "less than an acceptable error" 
err = 1e-3
abs((x+y)-0.3) <= err
0.30000000000000004 0.3
Out[92]:
True

Complex

  • Complex numbers consist of two parts: 'real' and 'imaginary'
  • A useful module when working with complex numbers is cmath
In [102]:
x = 2.5 + 4j

a = -2
b = 0.5
w = complex(a,b)
x, w

w.real, w.imag
w.conjugate()

import cmath
dir(cmath)
cmath.polar(x)
Out[102]:
(4.716990566028302, 1.0121970114513341)

Further reading

. Free learning material
. See full copyright and disclaimer notice