程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python:實現area under curve曲線下面積算法(附完整源碼)

編輯:Python

Python:實現area under curve曲線下面積算法

from __future__ import annotations
from collections.abc import Callable
def trapezoidal_area(
fnc: Callable[[int | float], int | float],
x_start: int | float,
x_end: int | float,
steps: int = 100,
) -> float:
x1 = x_start
fx1 = fnc(x_start)
area = 0.0
for i in range(steps):
# Approximates small segments of curve as linear and solve
# for trapezoidal area
x2 = (x_end - x_start) / steps + x1
fx2 = fnc(x2)
area += abs(fx2 + fx1) * (x2 - x1) / 2
# Increment step
x1 = x2
fx1 = fx2
return area
if __name__ == "__main__":
def f(x):
return x**3 + x**2
print("f(x) = x^3 + x^2")
print("The area between the curve, x = -5, x = 5 and the x axis is:")
i = 10
while i <= 100000:
print(f"with {
i} steps: {
trapezoidal_area(f, -5, 5, i)}")
i *= 10

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved