strings
- a sequence of case-sensitive characters
- can compare: ==. <, >, <=, >=
>>> 'a' < 'b'
True
## alphabetic order
- len()
- aStr[ ] indexing and slicing
- immutable
Approximate Solutions
Exhaustive Numeration
Quesiont: Finding the cube root(三次方根)of a number.
- Guess: take small steps to generate guesses in order
–> Start with a guess and increment by a small value - Check: check to see if the guess is close enough
–> ( ) < epsilon 【close enough:smaller than the epsilon 小于误差】
epsilon: the fifth letter of the Greek alphabet (Ε, ε), a short vowel, transliterated as e
In mathematics, a small positive infinitesimal (extremely small) quantity, usually denoted or , whose limit is usually taken as . The late mathematician P. Erdős also used the term “epsilons” to refer to children (Hoffman 1998, p. 4).
More efficient --> Bisection
small ---- half point — big
precondtion: Bisection search works when the function varies monotonically with input. 单调函数
Floats
- Floats approxiamte real numbers
- Decimal 十进制
302 = 310**2 + 0101 + 210*0 - Binary 二进制
10011 = 12**4 + 023 + 0*22 + 12**1 + 12**0
Decimal --> Binary
def convert10to2(n):
'''
converting a decimal n to binary form
n: a whole number (int)
return: a binary form number (str)
'''
binary = ''
isNegative = False
if n < 0:
isNegative = True
n = abs(n)
if n == 0:
binary = '0'
while n > 0:
binary = str(n % 2) + binary
n = n //2
if isNegative:
binary = '-' + binary
return binary
Fractions & Floats in python
Decimal: 1.949 == 1949 / 10^3
Binary: (0.375) 0.011 = 11 (3) / 2^3
def convert10to2Fra(n):
'''
converting a decimal n to binary form
n: a fraction between 0 and 1 (float)
return: a binary form number (str)
'''
# finding p, which makes n*(2**p) a whole num
p = 0
while n*(2**p)%1 != 0:
p += 1
intN = int(n*(2**p))
resultN = convert10to2(intN)
resultn = '0.' + (p-len(resultN))*'0' + resultN
return p, resultn
floats in python
representation
key: to find the p that makes (n*2^p) a whole number, which sometimes is not possilbe
–> thus floats in python is represented by approximation, rather than a real number
Iterative Algorithm
Guess-Check-Guess
- Finding a close enough guess by setting an epsilon
- Using a looping construct
while abs() >= epsilon:
How to generate guesses
-
Exhaustive enumeration
n += 1 -
Bisection search
guess = (high + low) / 2
adjusting high/low
precondition: monotonical function -
Newton-Raphson
for root finding