Thoughts on Python numerics
- Today we build upon our pythonic problem solving skills by introducing the notion of type
- A type is a collection of values along with operators and functions that can manipulate those values.
- There are three basic types in Python
int
: provides support for integer arithmetic
float
: provides support for decimal arithmetic
str
: provides support for string production and manipulation
- The important arithmetic operators are described below, in there variables
a
areb
are numeric values. Except for the decimal division operator, if both operands are integer, the value of the operation is integer; otherwise, the value of the operation is decimal. For the decimal division operator, the result is always decimal.
a + b
The sum of a
andb
a - b
The difference of b
froma
a * b
The product of a
andb
a / b
The decimal quotient a
divided byb
a // b
The truncated quotient of of a
divided byb
a ** b
The remainder when b
does not evenly divideb
a % b
The remainder when b
does not evenly dividea
- The two important string operators are described below, in there value
s
is a string andn
is an integer.
s + t
The contatenation (gluing) of strings s
andt
n * s
If n
is positive, it is the concatenation ofs
with itselfn-1
times; otherwise it is the''
s * n
Equals n * s
- Typos are maddening. When you write and read code, do it mindfully,
- A module is a library (collection) of Python resources. They are typically functins.
- An
import
statement gives its code file access to an external Python resource. For example, The statement
import math
gives its code access to the standard Python math library.
- An invocation of a function
f()
from a modulem
requiresm.
in front of the invoked functionf()
. For example,math.sin( 45 )
invokes themath
module’s functionsin()
to determine the sine of 45 degrees.
- All values in Python are stored in base 2. An individual binary digit is called a bit. A bit is either 0 or 1.
- Most Python implementations use 64 bits to represent a decimal number, where 1 bit keeps track of the sign of the number, 10 bits keep track of the power of 2 being represented. and 53 bits to store the number itself.
- Why 64 bits for a decimal number — modern computers have 64-bit operating systems.
- With only 64 bits to represent a decimal value, the best approximation of π in Python is kept track by
math.pi
, which equals3.141592653589793
.
© 2019 Jim Cohoon | Resources from previous semesters are available. |