Writing a lambda function, within another function

65 Views Asked by At

I have a function, area_approximator(), which calculates the area underneath a graph. I want the user to define a function (for example, f = 2*x), and then define limits (a, b), and the number of trapeziums the function will count, N. The function, area_approximator(), should then calculate the total area traced by the function defined by the user.

Currently, I have been able to make area_approximator() work by using a user input, to allow the user the define the function f.

def area_approximator(a, b, N, f):

    # The width of each trapezium, w
    w = abs((b - a) / N)

    # A list containing the heights, or y values, of each trapezium's left and right sides, is created
    heights = np.linspace(a, b, N+1)
    realheights = [f(h) for h in heights]

    # The total area is found by summing the area of of all trapeziums
    area = 0
    for i in range(N):
        area += 0.5 * (realheights[i] + realheights[i+1]) * w

    return area

area_approximator(a, b, N, f)

function = input('Define the function for x: ')
f = lambda x: eval(function)

However, I would like area_approximator() to work without the need for user input, so that the user can simply type 'area_approximator(1, 2, 3, 2x)' and get a result (for a = 1, b = 2, N = 3, f = 2 * x, in this case)
My attempts are as follows.

def area_approximator(a, b, N, f):

    g = lambda x: eval(f)

    # The width of each trapezium, w
    w = abs((b - a) / N)

    # A list containing the heights, or y values, of each trapezium's left and right sides, is created
    heights = np.linspace(a, b, N+1)
    realheights = [g(h) for h in heights]

    # The total area is found by summing the area of of all trapeziums
    area = 0
    for i in range(N):
        area += 0.5 * (realheights[i] + realheights[i+1]) * w

    return area

area_approximator(a, b, N, f)

However, when I attempt to use this, it gives a NameError for any value of f I use (for example f = 5*x)

0

There are 0 best solutions below