Skip to content

Commit 4196c4b

Browse files
author
Zo Bot
committed
remove the abs() around the trapezoid segment sum so signed area comes through
The trapezoidal rule is a signed-area approximation: each linear segment between (x1, f(x1)) and (x2, f(x2)) contributes (f(x1) + f(x2)) * (x2 - x1) / 2 to the running total. The previous code wrapped that in abs(), which forced the running total to be non-negative. For functions that are positive in the test range the abs() was a no-op and the existing doctests passed, but two natural cases broke: - f(x) = -x**2 from -1.0 to 1.0 returns +0.6666... instead of -0.6666... - f(x) = x from -2.0 to 2.0 returns 4.0 instead of 0 (the symmetric linear function integrates to zero across the origin) The doctests use f(x)=5 and f(x)=9*x**2 — both non-negative in the test range, so they coincidentally worked. Drop the abs() and the formula now returns the correct signed approximation for any real-valued f. Verified with python3 -m doctest maths/area_under_curve.py: 5/5 pass.
1 parent 234e0e7 commit 4196c4b

1 file changed

Lines changed: 1 addition & 1 deletion

File tree

maths/area_under_curve.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def trapezoidal_area(
4141
# for trapezoidal area
4242
x2 = (x_end - x_start) / steps + x1
4343
fx2 = fnc(x2)
44-
area += abs(fx2 + fx1) * (x2 - x1) / 2
44+
area += (fx2 + fx1) * (x2 - x1) / 2
4545
# Increment step
4646
x1 = x2
4747
fx1 = fx2

0 commit comments

Comments
 (0)