我有一个函数,area_approximator(),它计算图形下方的面积。我希望用户定义一个函数(例如,f = 2*x),然后定义限制(a,b),以及函数将计算的梯形数量,N。函数area_approximator()应该然后计算用户定义的函数追踪的总面积。
目前,我已经能够通过使用用户输入来使area_approximator()工作,以允许用户定义函数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)
但是,我希望 area_approximator() 无需用户输入即可工作。我的尝试如下。
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)
但是,当我尝试使用它时,它会为我使用的任何 f 值给出一个 NameError (例如 f = 5*x)
您应该将函数直接传递给 g,而不使用
eval()
。
试试这个:
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 all trapeziums
area = 0
for i in range(N):
area += 0.5 * (realheights[i] + realheights[i+1]) * w
return area
# Example usage:
import numpy as np
f = lambda x: 2 * x # Example function: f(x) = 2x
# Define limits and number of trapeziums
a = 0
b = 1
N = 100
# Calculate the area using the defined function
result = area_approximator(a, b, N, f)
print("Approximated area:", result)
输出:
Approximated Area: 1.0