编写for循环以将lambda函数应用于多个步长值



我正在求解h的多步值的lambda方程。现在,我已经硬编码了一个值,并成功生成了我需要的:

# Specify the lambda function
dy = lambda x,y: x**3
# Specify the Initial conditions
xi = 0 
xf = 2
h=0.5 # This is the hard-coded variable
n = int((xf - xi) / h)
x = 0
y = 0
print('x tt y')
print('%f t %f'% (x, y))
x_var = []
y_var = []
for i in range(1, n+1):
y = y + dy(x,y) * h
x = x + h
y_var.append(y)
x_var.append(x)
print('%f t %f'% (x,y))

error = 4 - y_var[-1]
print("The error for the delta x value is {}".format(error))

然而,我在一个列表中有多个h值:h = [0.5, 0.25, 0.125, 0.0625, 0.03125, 0.015625, 0.0078125, 0.00390625],我需要在每个h值上迭代lambda函数,为每次迭代创建新的x_vary_var列表,并打印出每次迭代的错误项(即4- y_var[-1]。此外,n值将因每次迭代而变化,因为每次迭代的h值将不同。

以下是我尝试过的:

# Specify the lambda function
dy = lambda x,y: x**3
# Initial conditions
xi = 0 
xf = 2
h = [0.5, 0.25, 0.125, 0.0625, 0.03125, 0.015625, 0.0078125, 0.00390625] # List to iterate over
n = int((xf - xi) / h) # The n value needs to change for each iteration, since h is different
x = 0
y = 0
print('x tt y')
print('%f t %f'% (x, y))
x_var = []
y_var = []
for i in h:
for i in range(1, n+1):
y = y + dy(x,y) * h
x = x + h
y_var.append(y)
x_var.append(x)
print('%f t %f'% (x,y))
error = 4 - y_var[-1]
print("The error for the delta x value is {}".format(error))

但是,会抛出以下错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [56], in <cell line: 7>()
5 xf = 2
6 h = [0.5, 0.25, 0.125, 0.0625, 0.03125, 0.015625, 0.0078125, 0.00390625]
----> 7 n = int((xf - xi) / h)
9 x = 0
10 y = 0
TypeError: unsupported operand type(s) for /: 'int' and 'list'

问题是,不能用值列表除((xf-xi(/h(。您可以生成n:的列表

n=[int((xf-xi(/x(对于h中的x]

最后重新设计for循环。

顺便说一句。事实上,我真的不明白你想达到什么目的;(

要更深入地学习python,请始终检查实例的类型,例如:键入(h(,它将显示您的列表。在下一步中,您可以检查列表数据类型支持的操作数。

https://docs.python.org/3/library/stdtypes.html?highlight=list

所有数据类型都是您要研究的主题。

最新更新