20250526
This commit is contained in:
34
160-11.py
Normal file
34
160-11.py
Normal file
@@ -0,0 +1,34 @@
|
||||
def SecantSolve(fx, x0, x1, err=1e-10, N0=100):
|
||||
count = 0
|
||||
print(f"k={count}: x{count}={x0}, f(x{count})={fx(x0)}")
|
||||
count += 1
|
||||
print(f"k={count}: x{count}={x1}, f(x{count})={fx(x1)}")
|
||||
count += 1
|
||||
while abs(x1 - x0) > err or abs(fx(x1)) > err:
|
||||
if fx(x1) == fx(x0):
|
||||
return None,0
|
||||
x2 = x1 - fx(x1) * (x1 - x0) / (fx(x1) - fx(x0))
|
||||
print(f"k={count}: x{count}={x2}, f(x{count})={fx(x2)}")
|
||||
count += 1
|
||||
if count > N0:
|
||||
return None,-1
|
||||
x0 = x1
|
||||
x1 = x2
|
||||
return x2,1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
err = 1e-5
|
||||
N0 = 100
|
||||
|
||||
x0 = 0.3
|
||||
x1 = 0.4
|
||||
fx = lambda x: x**4 - 3*x + 1
|
||||
|
||||
result, status = SecantSolve(fx, x0, x1, err, N0)
|
||||
if status == 1:
|
||||
print(f"fx收敛 解为: {result}")
|
||||
elif status == -1:
|
||||
print("fx不收敛")
|
||||
else:
|
||||
print("分母为0,无法收敛")
|
||||
62
160-12.py
Normal file
62
160-12.py
Normal file
@@ -0,0 +1,62 @@
|
||||
def MullerSolve(fx,x0,x1,x2,err1,err2,N):
|
||||
count = 0
|
||||
f0 = fx(x0)
|
||||
f1 = fx(x1)
|
||||
f2 = fx(x2)
|
||||
q = (x2 - x1) / (x1 - x0)
|
||||
p = 0
|
||||
a = 0
|
||||
b = 0
|
||||
c = 0
|
||||
while True:
|
||||
p = (x2 - x0) / (x1 - x0)
|
||||
|
||||
a = q**2 * f0 - q*p*f1 + q*f2
|
||||
b = q**2 *f0 - p**2 *f1 + (p + q)*f2
|
||||
c = p*f2
|
||||
h1 = 0
|
||||
if b < 0:
|
||||
h1 = -2 * c / (b - (b**2 - 4*a*c)**0.5)
|
||||
else:
|
||||
h1 = -2 * c / (b + (b**2 - 4*a*c)**0.5)
|
||||
x3 = x2 + h1 * (x2 - x1)
|
||||
f3 = fx(x3)
|
||||
|
||||
print(f"k={count}: x{count}={x0:.5}, f(x{count})={f0:.5}; x{count+1}={x1:.5}, f(x{count+1})={f1:.5}; x{count+2}={x2:.5}, f(x{count+2})={f2:.5}; x{count+3}={x3:.5}, f(x{count+3})={f3:.5}")
|
||||
print(f"p={p:.5}, q={q:.5}, a={a:.5}, b={b:.5}, c={c:.5}, h={h1:.5}")
|
||||
|
||||
k = err1 + 1
|
||||
if abs(f3) < 1:
|
||||
k = abs(x3 - x2)
|
||||
else:
|
||||
k = abs(x3 - x2) / abs(f3)
|
||||
|
||||
if abs(f3) < err2 or k < err1:
|
||||
return x3, 1
|
||||
count += 1
|
||||
if count > N:
|
||||
return None, 0
|
||||
x0 = x1
|
||||
x1 = x2
|
||||
x2 = x3
|
||||
f0 = f1
|
||||
f1 = f2
|
||||
f2 = f3
|
||||
q = h1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
err1 = 1e-5
|
||||
err2 = 1e-5
|
||||
N = 100
|
||||
|
||||
x0 = 0.3
|
||||
x1 = 0.5
|
||||
x2 = 0.4
|
||||
fx = lambda x: 8*x**4 - 8*x**2 + 1
|
||||
|
||||
result, status = MullerSolve(fx, x0, x1, x2, err1, err2, N)
|
||||
if status == 1:
|
||||
print(f"fx收敛 解为: {result}")
|
||||
else:
|
||||
print("fx不收敛")
|
||||
Reference in New Issue
Block a user