Search code examples
pythonfor-looplambda

Writing a for loop to apply a lambda function over multiple step values


I am solving a lambda equation for multiple step values of h. Right now, I have hard-coded one value and have successfully generated what I need:

# 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 \t\t 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))

However, I have multiple h values in a list: h = [0.5, 0.25, 0.125, 0.0625, 0.03125, 0.015625, 0.0078125, 0.00390625] , and I need to iterate the lambda function over each h value, create new x_var and y_var lists for each iteration, and print out the error term for each iteration (which is 4- y_var[-1]. In addition, the n value will change for each iteration, as the h value will be different for each iteration.

Here is what I have tried:

# 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 \t\t 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))

However, the following error is thrown:

---------------------------------------------------------------------------
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'

Solution

  • The Problem is, that you can not divide ((xf - xi) / h) by a list of values. You can generate a list of n:

    n = [int((xf-xi)/x) for x in h]

    and finally redesign your for-loops.

    btw. I actually didnt really understand what you want to reach ;)

    To learn python more deeply, always inspect the type of your instances, exg.: type(h), it will show you list. In next step you can check for supported operands of list-datatype.

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

    All in all datatypes is your topic to study.