From 75283119296e5d6ce3a1c6d857a92a43ff0afec0 Mon Sep 17 00:00:00 2001 From: Vinod Polimera Date: Wed, 20 Jul 2022 17:25:44 +0530 Subject: commonlib: Add support for rational number approximation This patch adds a function to calculate best rational approximation for a given fraction and unit tests for it. Change-Id: I2272d9bb31cde54e65721f95662b80754eee50c2 Signed-off-by: Vinod Polimera Reviewed-on: https://review.coreboot.org/c/coreboot/+/66010 Reviewed-by: Yu-Ping Wu Tested-by: build bot (Jenkins) --- tests/commonlib/Makefile.inc | 4 +++ tests/commonlib/rational-test.c | 57 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+) create mode 100644 tests/commonlib/rational-test.c (limited to 'tests') diff --git a/tests/commonlib/Makefile.inc b/tests/commonlib/Makefile.inc index 054e7db16d..6df1db8fc5 100644 --- a/tests/commonlib/Makefile.inc +++ b/tests/commonlib/Makefile.inc @@ -2,7 +2,11 @@ subdirs-y += bsd +tests-y += rational-test tests-y += region-test +rational-test-srcs += tests/commonlib/rational-test.c +rational-test-srcs += src/commonlib/rational.c + region-test-srcs += tests/commonlib/region-test.c region-test-srcs += src/commonlib/region.c diff --git a/tests/commonlib/rational-test.c b/tests/commonlib/rational-test.c new file mode 100644 index 0000000000..4d6c215aad --- /dev/null +++ b/tests/commonlib/rational-test.c @@ -0,0 +1,57 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ + +#include +#include + +struct rational_test_param { + unsigned long num, den; + unsigned long max_num, max_den; + unsigned long exp_num, exp_den; +}; + +static const struct rational_test_param test_params[] = { + /* Exceeds bounds, semi-convergent term > half last term */ + { 1230, 10, 100, 20, 100, 1}, + /* Exceeds bounds, semi-convergent term < half last term */ + { 34567, 100, 120, 20, 120, 1}, + /* Closest to zero */ + { 1, 30, 100, 10, 0, 1}, + /* Closest to smallest non-zero */ + { 1, 19, 100, 10, 1, 10}, + /* Exact answer */ + { 1155, 7735, 255, 255, 33, 221}, + /* Convergent */ + { 27, 32, 16, 16, 11, 13}, + /* Convergent, semiconvergent term half convergent term */ + { 67, 54, 17, 18, 5, 4}, + /* Semiconvergent, semiconvergent term half convergent term */ + { 453, 182, 60, 60, 57, 23}, + /* Semiconvergent, numerator limit */ + { 87, 32, 70, 32, 68, 25}, + /* Semiconvergent, demominator limit */ + { 14533, 4626, 15000, 2400, 7433, 2366}, +}; + +static void test_rational(void **state) +{ + int i; + unsigned long num = 0, den = 0; + + for (i = 0; i < ARRAY_SIZE(test_params); i++) { + rational_best_approximation(test_params[i].num, test_params[i].den, + test_params[i].max_num, test_params[i].max_den, + &num, &den); + assert_int_equal(num, test_params[i].exp_num); + assert_int_equal(den, test_params[i].exp_den); + } +} + +int main(void) +{ + const struct CMUnitTest tests[] = { + cmocka_unit_test(test_rational), + }; + + return cmocka_run_group_tests(tests, NULL, NULL); +} + -- cgit v1.2.3