Commit 2f8ed6b1 authored by Kittipong Maneewong's avatar Kittipong Maneewong

ส่งงาน week12

parent 121124af
#Bracketing minimum
def f(x) : return x**2-2*x+1
from matplotlib import pyplot as plt
import numpy as np
x=[x/10 for x in range(-20,20,1)]
y=[f(xi) for xi in x]
print(x)
print(y)
a,b=-2,2
fa,fb=f(a),f(b)
plt.plot(x,y,"g-")
plt.show()
#next
def bracket(f, **kwargs):
a = float(kwargs['a'])
b = float(kwargs['b'])
h = float(kwargs['h'])
xi = a
oldf = f(xi)
xi += h
newf = f(xi)
while newf < oldf :
oldf = newf
xi += h
newf = f(xi)
xi -= h
print('Solution xi',xi,f(xi))
bracket(f,a=-2,b=2,h=0.01)
#Golden Section Search
import math
R = (-1 + 5**0.5)/2
def n(a=-2,b=2,ebs=10**-9) :
from math import log as ln
return int(-ln(R)*ln(eps/abs(b-a)))
def search(f,a,b,tol=1.0e-9):
nIter = n(a,b)
0.618033989
C = 1.0 - R
# First telescoping
x1 = R*a + C*b; x2 = C*a + R*b
f1 = f(x1); f2 = f(x2)
# Main loop
for i in range(nIter):
if f1 > f2:
a = x1
x1 = x2; f1 = f2
x2 = C*a + R*b; f2 = f(x2)
else:
b = x2
x2 = x1; f2 = f1
x1 = R*a + C*b; f1 = f(x1)
if f1 < f2: return x1,f1
return x2,f2
search(f,-2,2)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment