summaryrefslogtreecommitdiffstats
path: root/src/commonlib/include/commonlib/rational.h
diff options
context:
space:
mode:
authorVinod Polimera <quic_vpolimer@quicinc.com>2022-07-20 17:25:44 +0530
committerShelley Chen <shchen@google.com>2022-08-03 03:26:13 +0000
commit75283119296e5d6ce3a1c6d857a92a43ff0afec0 (patch)
tree37fa1a7d7d853859e3c2e0a412a580912d90c33f /src/commonlib/include/commonlib/rational.h
parent65377eba7fa0c7d46e5e88a92f667ae40ea08ef2 (diff)
downloadcoreboot-75283119296e5d6ce3a1c6d857a92a43ff0afec0.tar.gz
coreboot-75283119296e5d6ce3a1c6d857a92a43ff0afec0.tar.bz2
coreboot-75283119296e5d6ce3a1c6d857a92a43ff0afec0.zip
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 <quic_vpolimer@quicinc.com> Reviewed-on: https://review.coreboot.org/c/coreboot/+/66010 Reviewed-by: Yu-Ping Wu <yupingso@google.com> Tested-by: build bot (Jenkins) <no-reply@coreboot.org>
Diffstat (limited to 'src/commonlib/include/commonlib/rational.h')
-rw-r--r--src/commonlib/include/commonlib/rational.h22
1 files changed, 22 insertions, 0 deletions
diff --git a/src/commonlib/include/commonlib/rational.h b/src/commonlib/include/commonlib/rational.h
new file mode 100644
index 000000000000..f172e0b191ec
--- /dev/null
+++ b/src/commonlib/include/commonlib/rational.h
@@ -0,0 +1,22 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+
+#ifndef _COMMONLIB_RATIONAL_H_
+#define _COMMONLIB_RATIONAL_H_
+
+#include <stddef.h>
+
+/*
+ * Calculate the best rational approximation for a given fraction,
+ * with the restriction of maximum numerator and denominator.
+ * For example, to find the approximation of 3.1415 with 5 bit denominator
+ * and 8 bit numerator fields:
+ *
+ * rational_best_approximation(31415, 10000,
+ * (1 << 8) - 1, (1 << 5) - 1, &n, &d);
+ */
+void rational_best_approximation(
+ unsigned long numerator, unsigned long denominator,
+ unsigned long max_numerator, unsigned long max_denominator,
+ unsigned long *best_numerator, unsigned long *best_denominator);
+
+#endif /* _COMMONLIB_RATIONAL_H_ */