我开发了一个类,以便使用牛顿-拉普森方法求解非线性方程来求解后向欧拉。 该类也适用于ODE系统(它需要一个函数数组..)
这是我的课程:
class Backward(Euler):
solved = False
def __init__(self, dydt: Rhs, filename : str=' ', save :bool=True):
self.save = save
self.file = filename
super().__init__(dydt)
def solve(self):
toll = 10e-12
self.time, self.u = self.dydt.createArray()
print('Running Newton-Rapson Backward Euler ....')
for i in range(len(self.time)-1):
u0 = self.u[i].T
u1 = u0 - np.linalg.inv(np.eye(len(self.dydt.u0)) - self.dt * self.dydt.Df(self.time[i+1],u0)) * (u0 - self.dt * self.dydt.f(self.time[i+1], u0).T - self.u[i].T )
error = np.array([1.0])
iters = 0
while True:
try:
u0 = u1.T
u1 = u0 - np.linalg.inv(np.eye(len(self.dydt.u0)) - self.dt * self.dydt.Df(self.time[i+1],u0)) * (u0 - self.dt * self.dydt.f(self.time[i+1], u0).T - self.u[i].T )
iters += 1
error = np.abs(u1-u0)
if error <= toll:
break
if iters >= 10000:
raise ValueError('Too many iterations!')
except ValueError as ex:
print('Error occurred in Implicit-NR Euler Solvers: %s' %ex.args)
return None , None
self.u[i+1] = u1.T
#-------------------------------------------
print('...Done!')
我收到此错误:
Running Newton-Rapson Backward Euler ....
Error occurred in Implicit-NR Euler Solvers: The truth value of an ars ambiguous.
Use a.any() or a.all()
如果我尝试使用error.all()或error.any(),则问题永远不会收敛... 此方法的输入参数为:
eq1 = lambda t,u : u[1]
eq2 = lambda t,u : u[2]
eq3 = lambda t,u : u[3]
eq4 = lambda t,u : -8*u[0]+ np.sin(t)*u[1]-3*u[3]+t**2
func1 = np.array([eq1,eq2,eq3,eq4])
y0 = np.array([1.,2.,3.,4])
system1 = rhs.Rhs(func1, 0,5,y0, 1000 )
其中Rhs是一个包装类,其中包含要解决的函数等数据。
编辑,我遵循您的建议,谢谢。我放了toll = 10e-3
,但问题仍未解决...(迭代次数过多),如果我放了错误[0],[ 0]打印shape is 4,4
,然后我得到
File "system01.py", line 41, in main
bet,beu = bwdeuler.solve()
File "/home/marco/Programming/Python/Numeric/OdeSystem/euler.py", line 378, in solve
self.u[i+1] = u1.T
ValueError: could not broadcast input array from shape (4,4) into shape (4)