我想推进euler,后向欧拉和梯形方法的实现,并在python中绘制1s和2阶ODE,特别是对于谐振子和指数衰减。
到目前为止,我已经在代码上完成了很多工作。
import math
import mathplotlib
import numpy
import scipy
# First Order ODE (y' = f(x, y)) Solver using Euler method
# xa: initial value of independent variable
# xb: final value of independent variable
# ya: initial value of dependent variable
# n : number of steps (higher the better)
# Returns value of y at xb.
def Euler1(f, xa, xb, ya, n):
h = (xb - xa) / float(n)
x = xa
y = ya
for i in range(n):
y += h * f(x, y)
x += h
return y
# Second Order ODE (y'' = f(x, y, y')) Solver using Euler method
# y1a: initial value of first derivative of dependent variable
def Euler2(f, xa, xb, ya, y1a, n):
h = (xb - xa) / float(n)
x = xa
y = ya
y1 = y1a
for i in range(n):
y1 += h * f(x, y, y1)
y += h * y1
x += h
return y
if __name__ == "__main__":
print Euler1(lambda x, y: math.cos(x) + math.sin(y), 0, 1, 1, 1000)
print Euler2(lambda x, y, y1: math.sin(x * y) - y1, 0, 1, 1, 1, 1000)
它给我一个错误的打印Euler1说SyntaxError:无效语法
任何人都可以帮助我解决其他需要做的工作以及在python中进行梯形方法的指导