前几章比较简单,本文纯粹是为了对基本概念做个记录,顺便码一下。
第三章
3.3 近似解和二分查找
3.3.1 平方根迭代近似解
x=25
epsilon = 0.01
step = epsilon**2
numGuesses = 0
ans = 0
while abs(ans**2-x) >= epsilon and ans <= x:
ans += step
numGuesses += 1
print(f'numGuesses ={numGuesses}')
if abs(ans**2 - x) >= epsilon:
print(f'Failed on square root of {x}')
else:
print(f'{ans} is close to square root of {x}')
3.3.1 平方根二分查找近似解
x=25
epsilon = 0.01
low = 0
high = max(1,x)
numGuesses = 0
ans = (high + low)/2
while abs(ans**2-x) >= epsilon:
print(f'low = {low},high = {high}')
numGuesses += 1
if ans**2 < x:
low = ans
else:
high = ans
ans = (high + low)/2
print(f'numGuesses = {numGuesses}')
print(f'{ans} is close to square root of {x}')
3.4 关于浮点数
浮点数都是高精度的近似值
x = 0
for i in range(10):
x += 0.1
if x == 1:
print(f'{x} = 1')
else:
print(f'{x} is not 1.0')
3.5 牛顿-拉弗森法
求解多项式
epsilon = 0.01
k = 25
guess = k/2
while abs(guess*guess - k) >= epsilon:
guess -= (((guess**2)-k)/(2*guess))
print(f'Square root of {k} is about {guess}')
4.2 规范(测试用例)
def findRoot(x,power,epsilon):
'''二分法找平方根'''
if x <0 and power%2==0:
return None
low = min(-1,x)
high = max(1,x)
ans = (high + low)/2
while abs(ans**power-x) >= epsilon:
if ans**power < x:
low = ans
else:
high = ans
ans = (high + low)/2
return ans
def testFindRoot():
epsilon=0.0001
for x in [0.25,-0.25,2,-2,8,-8]:
for power in range(1,4):
print(f'Testing x ={str(x)} and power = {power}')
result=findRoot(x,power,epsilon)
if result == None:
print(' No root')
else:
print(f' {result**power}~={x}')
4.3 递归
4.3.1 阶乘
def factR(n):
if n == 1:
return n
else:
return n*factR(n-1)
4.3.2 斐波那契
def fib(n):
if n==0 or n==1:
return 1
else:
return fib(n-1)+fib(n-2)
def testFib(n):
for i in range(n+1):
print(f'fib of {i} = {fib(i)}')
4.3.3 回文检测
def isPalindrome(s):
'''回文检测,忽略点符号、空格、大小写'''
def toChars(s):
s=s.lower()
letters=''
for c in s:
if c in 'abcdefghijklmnopqrestuvwxyz':
letters=letters+c
return letters
def isPal(s):
print(f'isPal called with {s}')
if len(s)<=1:
print('About to return Ture from base case')
else:
answer=s[0]==s[-1] and isPal(s[1:-1])
print(f'About to return {answer} for {s}')
return answer
return isPal(toChars(s))
def testIsPalindrome():
print('Try dogGod')
print(isPalindrome('dogGod'))
print('Try doGood')
print(isPalindrome('doGood'))
4.4 全局变量
用于打印函数内循环变量,查找错误点,还是不错的
def fib(x):
global numFibcalls
numFibcalls+=1
if x==0 or x==1:
return 1
else:
return fib(x-1)+fib(x-2)
def testFib(n):
for i in range(n+1):
global numFibcalls
numFibcalls=0
print(f'fib of {i} = {fib(i)}')
print(f'fib called {numFibcalls} times')