Algorithm principle
- Step 1: For the objective function f(x), determine the initial interval [a, b], and determine the calculation termination condition (point distance criterion) ε;
- Step 2: Calculate f'((a+b)/2);
- Step 3: If f'((a+b)/2)<0, indicating that the extreme point is in the interval of [(a+b)/2,b], let a=(a+b)/2;
- Step 4: If f'((a+b)/2)>0, it means that the extreme point is in the interval [a,(a+b)/2], let b=(a+b)/2;
- Step 5: If ba<ε, terminate the iteration, otherwise return to Step 2;
Remarks : For the case where the function is not convenient to find the derivative function, a small amount of σ can be taken, f((a+b)/2-σ)<f((a+b)/2+σ), which means f'((a+ b)/2)>0, otherwise f'((a+b)/2)<0;
Algorithm implementation
def func(x):
return x**2 + x + 5
left = -100
right = 100
sigma = 0.0001
mid = (left + right) / 2
while (1):
x1 = mid - sigma
x2 = mid + sigma
if (func(x1) < func(x2)):
right = x2
else:
left = x1
if (right - left < 0.001):
break
mid = (left + right) / 2
print("left=%s,right=%s" % (left, right))