如何在Python中无导入实现梯形积分并编写指定参数的积分函数?
Implementing Trapezoidal Integration in Python (No External Libraries)
Let's fill in the core logic for the integral function to compute the trapezoidal estimate of a function's integral over a given interval. Here's the step-by-step solution:
Core Logic Breakdown
The trapezoidal rule splits the interval (x0, xn) into n equal-width subintervals. Each subinterval forms a trapezoid, and the total integral is the sum of all these trapezoid areas. The formula we’ll use is:
Integral ≈ (h/2) * [f(x0) + 2f(x1) + 2f(x2) + ... + 2*f(xn-1) + f(xn)]
whereh = (xn - x0)/nis the width of each subinterval.
Complete Code with Integrated Core Logic
def f1(x): return x * 4 * (1 - x) * 4 / (1 + x ** 2) def f2(x): e = 2.718281828459045 return e ** -x def integral(f, interval, n): ''' computes estimate of integral of f over interval based on deviding interval into n trapeziums ''' if not (callable(f) and isinstance(interval, tuple) and isinstance(n, int)): return if not (len(interval)==2 and isinstance(interval[0], float) and isinstance(interval[1], float) and interval[0]<interval[1]): return # Core trapezoidal integration logic starts here x0, xn = interval h = (xn - x0) / n # Calculate width of each trapezoid total = f(x0) + f(xn) # Start with first and last function values (only counted once) # Add 2*f(x) for all intermediate points (shared between two trapezoids) for i in range(1, n): current_x = x0 + i * h total += 2 * f(current_x) # Compute final integral estimate integral_estimate = total * h / 2 # Core logic ends here return integral_estimate # Test the example case print(integral(lambda x : x, (1.0, 2.0), 100)) # Outputs ~1.5, matching the exact integral result
Key Details
- We first extract the interval bounds and calculate the subinterval width
h. - The sum initializes with the first and last function values because each only appears in one trapezoid.
- For every intermediate point, we add twice the function value—since these points are the "shared edge" between two adjacent trapezoids.
- Finally, multiply the total sum by
h/2to get the final integral estimate.
内容的提问来源于stack exchange,提问作者orsa
相关产品推荐
相关产品推荐

