- while循环
x = 3
ans = 0
itersLeft = x
while (itersLeft != 0):
ans = ans+x
itersLeft = itersLeft - 1
print(str(x)+'*'+str(x)+'='+str(ans))
break
“当遇到break语句时,它将引领我跳出循环的计算”for循环
x = int(raw_input('Enter an integer:'))
for ans in range(0,abs(x)+1):
if ans**3 == abs(x):
break #跳出循环体
if ans**3 != abs(x):
#不确定是因为满足条件跳出还是因为穷尽了跳出
print(str(x)+'is not a perfect cube')
else:
if x<0:
ans = -ans
print('Cube root of+str(x)'+'is'+str(ans))
浮点数float
- 如果没有整数p,使得x*2^p是一个整数,那么,内部将一直是一个近似值。
- 所以,如果需要判断两个浮点数是否相同,不应该使用x==y的方式,因为是近似值,而应该使用 abs(x-y)<0.0001这样的形式。
“近似”的思想
x = 25
epsilon = 0.1
step = epsilon**2
numGuesses = 0
ans = 0.0
while abs(ans**2-x))>=epsilon and ans<=x:
ans +=step
numGuesses +=1
print('numGuesses='+str(numGuesses))
if abs(ans**2-x)>=epsilon:
print('Failed on square root of'+str(x))
else:
print(str(ans)+'is close to the square root of'+str(x))
思考:step的设置和实现时长矛盾
- Bisection search 二分查找
不断取中点后判断,每次都能去掉一半的潜在答案, pretty cool!
x = 25
epsilon = 0.01
numGuesses = 0
low = 0
high = x
ans = (low+high)/2.0
while abs(ans**2-x)>=epsilon:
print('low='+str(low)+'high='+str(high)+'ans='+str(ans))
numGuesses +=1
if ans**2 < x:
low = ans
else:
high = ans
ans = (low+high)/2.0
print('numGuesses =' + str(numGuesses))
print(str(ans)+' is close to square root of '+ str(x))
- Newton-Raphson 牛顿拉夫逊算法
求一元n阶方程的解
g-p(g)/p’(g)比g更接近解
#求y = x*x的解
eplison = 0.01
y = 24.0
guess = y/2.0
while abs(guess**2-y)>=eplison:
guess = guess-((guess**2)-y)/(2*guess)
print('Square root of'+str(y)+' is about ' + str(guess))