一维搜索的二次插值法
python
# 搜索区间,分别是x[0](为了对齐下标,无意义),x1,x2,x3
x = [0, 0, 1, 3]
# 结果x
xb = 0
# 精确度
e = 0.2
def f(x2):
return 3 * (x2 ** 3) - 4 * x2 + 2
def c1():
res = (f(x[1]) - f(x[3])) / (x[1] - x[3])
return res
def c2():
res = (((f(x[1]) - f(x[2])) / (x[1] - x[2])) - c1()) / (x[2] - x[3])
print("c2 =", res)
return res
def XB():
c_1 = c1()
print("c1 =", c_1)
res = 0.5 * (x[1] + x[3] - (c_1 / c2()))
print("xb =", res)
return res
def getNewx1x3(newx2):
a = {
"1": x[1],
"new2": newx2,
"old2": x[2],
"3": x[3]
}
sorted(a.items(), key=lambda t: t[1])
l = list(a.keys())
i = 0
for k in l:
if k == "new2":
break
i += 1
return a[l[i - 1]], a[l[i + 1]]
for i in range(1000):
xb = XB()
fxb = f(xb)
print("fxb =", fxb)
if abs(x[2] - xb) < e:
break
aa = {
"fxb": [fxb, xb],
"f(x[1])": [f(x[1]), x[1]],
"f(x[2])": [f(x[2]), x[2]],
"f(x[3])": [f(x[3]), x[3]],
}
sorted(aa.items(), key=lambda t: t[1][0])
newx2 = list(aa.values())[0][1]
x[1], x[3] = getNewx1x3(newx2)
x[2] = newx2
print("new x1, x2, x3 =", x[1], x[2], x[3], end="
")
print("xb, fxb =", xb, fxb)