From 73e6889e5e8dcb0989b39b8269a50f130c17b1cd Mon Sep 17 00:00:00 2001 From: fdai7848 Date: Sat, 3 Feb 2024 19:10:27 +0100 Subject: [PATCH] add approximation for pi by gauss-legendre --- src/reihen.c | 15 +++++++++++++++ src/reihen.h | 1 + test/test_reihen.c | 8 ++++++++ 3 files changed, 24 insertions(+) diff --git a/src/reihen.c b/src/reihen.c index b9f15e9..4e3ebb0 100644 --- a/src/reihen.c +++ b/src/reihen.c @@ -28,4 +28,19 @@ double exponential(double x){ double euler(){ return exponential(1); +} + +double pi(double eps){ + double a = 1, b = 1/powerD(0.5, 2), t = 0.25, p = 1; + double aNew, piold, pi = 1; + do{ + aNew = .5 * (a + b); + b = powerD(0.5 , a * b); + t -= p * (a - aNew) * (a - aNew); + a = aNew; + p *= 2; + piold = pi; + pi = (a + b) * (a + b) / (4 * t); + } while (absD(pi - piold) > eps); + return pi; } \ No newline at end of file diff --git a/src/reihen.h b/src/reihen.h index 20f8a18..36d8468 100644 --- a/src/reihen.h +++ b/src/reihen.h @@ -3,5 +3,6 @@ double exponential(double x); double euler(); +double pi(); #endif // reihen.h \ No newline at end of file diff --git a/test/test_reihen.c b/test/test_reihen.c index 13d490c..1329b6f 100644 --- a/test/test_reihen.c +++ b/test/test_reihen.c @@ -36,4 +36,12 @@ void test_Exponent_with_negative_number(void){ TEST_ASSERT_DOUBLE_WITHIN(0.000001, 0.135335, r2); } +void test_pi(void){ + double r1; + + r1 = pi(1e-8); + + TEST_ASSERT_DOUBLE_WITHIN(0.0000001, 3.14159265, r1); +} + #endif // TEST \ No newline at end of file