[英]While Loop true and false for approximation of roots
我對編程有點陌生,並且正在嘗試創建近似於根的代碼。 也就是說,我正在做類似於牛頓微積分的方法。 這個想法是,我要輸入一個大值,減去直到知道已經通過了根,然后再增加一個較小的數量,直到通過了根為止,然后迭代直到出現一些舒適的錯誤為止。區域。
這是一些偽代碼:
def approx(a,b,i):
while ((1/2)**i) >= (1/2)**10:
while (another function is true):
modify values, record root = r
while (the same function above is false):
modify values, record root = r
return approx(a,b,i+1)
return(a,b,r)
這似乎在Python中不起作用,所以我想知道是否有人可以指出我正確的方向。
編輯:包括我的實際代碼:
from fractions import *
from math import sqrt
from math import fabs
def pweight(c,d):
if d > c:
return pweight(d,c)
else:
return [c+d,c,d]
def eweight(a,b):
if a == b:
return [a]
elif b > a:
return eweight(b,a)
else:
return [b] + eweight(a-b,b)
def weight(a,b,c,d):
if a*b/2 > c*d:
print("No Embedding Exists")
return (False)
else:
return (True, [c+d]+sorted((pweight(c,d) + eweight(a,b))[1:], reverse=True))
def wgt(a,b,c,d):
return ([c+d]+sorted((pweight(c,d) + eweight(a,b))[1:], reverse=True))
def red(a,i,k):
d=a[0]-a[1]-a[2]-a[3]
if any(item < 0 for item in a[1:]):
# print ("No Embedding Exists")
return (False, i)
elif d >= 0:
# print ("Embedding Exists! How many iterations?")
# print(i)
return (True, i)
elif d<0:
a=[a[0]+d,a[1]+d,a[2]+d,a[3]+d]+a[4:]
a=[a[0]]+sorted(a[1:],reverse=True)
k.append(a)
i=i+1
return red(a,i,k)
def works(a,b):
L = sqrt(a/(2*b))
w = weight(1,a,L,L*b)
return w[0] and red(w[1],0,[])
def inf(a,b,i):
while ((1/2)**(i+1)) >= (1/2)**(10)):
while works(a,b):
a = a - (1/2)**i
L = sqrt(a/(2*b))
while not works(a,b):
a = a + (1/2)**(i+1)
L = sqrt(a/(2*b))
return inf(a,b,i+1)
return (a,b,L)
我想輸入“ inf(9,1,0)”,並使此代碼返回接近(255 / 32,1,sqrt(255/64))的內容。 主要問題是函數“ inf(a,b,i)”中的“ while works(a,b):”和“ while not works(a,b):”。 我希望函數在“ while正常”和“ while無效”之間切換,直到i = 9。
任何形式的一般想法都會受到贊賞(即,您如何在while循環中執行某種交替功能)。
如果要在它們之間交替,請不要將它們各自放在while
循環中,
while i < 9:
if works(a, b):
do something
if not works(a, b):
do something else
而你在測試什么while
條件需要的東西,在循環變化的地方。 否則,您將陷入無限循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.