计算图形下方区域的程序
我正在写一个程序,目的是通过计算梯形的面积来找出图形下方的面积。这个程序有以下几个步骤:
- 首先,询问用户想要的图形函数、边界点(在x轴上的位置),以及他们想要计算的梯形数量。
- 接着,计算每个梯形的宽度,方法是把边界点之间的长度除以梯形的数量。
- 然后,找出每个梯形的起始点和结束点的图形高度(也就是y值)。
- 最后,使用梯形面积的公式,计算每个梯形的面积。然后把这些面积加起来,就能得到图形下方的总面积。
import numpy
# Our function, along with boundary values and total number of trapeziums (N)
def f(x):
return x*2
x1 = float(input('Define first boundary value'))
x2 = float(input('Define second boundary value'))
N = float(input('Define number of trapeziums used'))
# The width of each trapezium, w
w = abs(float((x2-x1)/N))
# The true heights, or y value, of each trapezium's end points
heights = []
for h in numpy.arange(x1, x2+w, w):
heights.append(h)
realheights = [f(h) for h in heights]
# Applying the defined function (1/2((h1+h2)*w)), to find the area of each trapezium
我用x*2
作为一个占位符函数,但我希望用户能够定义他们想要的函数。我还不太清楚如何将这个函数应用到实际的高度值上,以计算梯形的面积。
1 个回答
0
试试这个:
import numpy
# Function to calculate the area under the curve
def calculate_area(f, x1, x2, N):
# The width of each trapezium, w
w = abs((x2 - x1) / N)
# The true heights, or y value, of each trapezium's end points
heights = numpy.linspace(x1, x2, N+1)
realheights = [f(h) for h in heights]
# Applying the formula for the area of each trapezium
area = 0
for i in range(N):
area += 0.5 * (realheights[i] + realheights[i+1]) * w
return area
# Get user inputs
x1 = float(input('Define first boundary value: '))
x2 = float(input('Define second boundary value: '))
N = int(input('Define number of trapeziums used: '))
# Prompt the user to input the function as a string and evaluate it
function_str = input('Define the function (e.g., "x**2" for x squared): ')
f = lambda x: eval(function_str)
# Calculate and print the area under the curve
area = calculate_area(f, x1, x2, N)
print('Area under the curve:', area)
输出结果:
