def init(x0,h):
x1=x0
f1=func(x1)
x2=x0+h
f2=func(x2)
if(f1>f2):
h=2*h
else:
h=-h
x3=x1
x1=x2
x2=x3
f3=f1
f1=f2
f2=f3
x3=x0+h
f3=func(x3)
while(f2>=f3):
h=2*h
x1=x2
f1=f2
x2=x3
f2=f3
x3=x0+h
f3=func(x3)
b=x2
fb=f2
print(x1,x2,x3)
if(h>0):
a=x1
fa=f1
c=x3
fc=f3
else:
a=x3
fa=f3
c=x1
fc=f1
abc=[a,b,c,fa,fb,fc]
return abc
def GSM(x0,h,e):
""" 初始值,步长,精度"""
sq=init(x0,h)
a=sq[0]
b=sq[2]
x1=a+0.382*(b-a)
x2=a+0.618*(b-a)
f1=func(x1)
f2=func(x2)
n=1
while(b-a>e):
if(f1<f2):
b=x2;x2=x1;f2=f1
x1=a+0.382*(b-a)
f1=func(x1)
else:
n0=1
a=x1;x1=x2;f1=f2
x2=a+0.618*(b-a)
f2=func(x2)
print("第",n,"次迭代",a," ",b)
n+=1
xr=(a+b)/2
fr=func(xr)
result=[xr,fr]
return result
def func(x):
f=3*x**3-4*x+2
return f
GSM.rar_GSM
版权申诉
62 浏览量
2022-09-23
17:23:22
上传
评论
收藏 546B RAR 举报
周楷雯
- 粉丝: 79
- 资源: 1万+