From 18f97ed631383f49c5d28dff577e71a34199385c Mon Sep 17 00:00:00 2001 From: lhye200 Date: Thu, 17 Apr 2025 12:41:06 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AC=AC=E5=9B=9B=E7=AB=A01?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 120-3.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 120-3.py diff --git a/120-3.py b/120-3.py new file mode 100644 index 0000000..b240434 --- /dev/null +++ b/120-3.py @@ -0,0 +1,27 @@ +x1, x2 = 3, 6 + + +def fx(x): + return x/(4+x**2) + +# n等分,x1到x2的区间,type=1表示梯形法,type=2表示辛普森法 +def CompositeNewtonCotes(n, type): + if type == 1: + h = (x2 - x1) / n + result = 0 + for i in range(n): + result += (fx(x1 + i * h) + fx(x1 + (i + 1) * h)) + result *= (h / 2) + return result + elif type == 2: + h = (x2 - x1) / n + result = -fx(x1) + fx(x2) + for i in range(n): + result += (4 * fx(x1 + (i + 0.5) * h) + 2 * fx(x1 + i * h)) + result *= (h / 6) + return result + + +if __name__ == "__main__": + print("Composite Trapezoidal Rule: ", CompositeNewtonCotes(8, 1)) + print("Composite Simpson's Rule: ", CompositeNewtonCotes(4, 2)) \ No newline at end of file