Python 二分查找与方程求解提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
二分查找
a为左边界 b为右边界 value为真实值
注意:二分查找只适用于顺序列表的数值查找,乱序不适用
def bisection(List,a,b,value):
#a为左边界 b为右边界 value为真实值
left=a
right=b
while left<=right:
mid = (left + right) // 2
if List[mid]==value:
return mid
elif List[mid]>value:
right=mid-1
elif List[mid]<value:
left=mid+1
return None
List=[1,2,3,4,5,6,7,8,9,13,14,15,18,23,56,57,58,67,68,73,75,79,98,99,101]
answer=bisection(List,0,20,56)
print(f'索引为{answer}')
二分法求解方程
def f(x):
return x**2-8
def bisection_f(f, a, b):
# f为函数,a为左边界,b为右边界
error = 0.00001 # 误差精度
left = a
right = b
while left <= right :
mid = (left + right) / 2
if f(mid) == 0:
return mid
elif f(mid) > 0:
right = mid
elif f(mid) < 0:
left = mid
if right-left<=error:
return mid
return mid
answer=bisection_f(f, 0, 10)
print(f'当x={answer}时f(x)=0')
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)