[PATCH] lib/math/int_log: add natural logarithmic function intloge()

Benji Dunn posted 1 patch 1 month, 4 weeks ago
include/linux/int_log.h | 19 +++++++++++++++++++
lib/math/int_log.c      | 24 ++++++++++++++++++++++++
2 files changed, 43 insertions(+)
[PATCH] lib/math/int_log: add natural logarithmic function intloge()
Posted by Benji Dunn 1 month, 4 weeks ago
Helpful to do natural logarithm on some NTC thermistors.

Signed-off-by: Benji Dunn <helicobacterpylori@163.com>
---
 include/linux/int_log.h | 19 +++++++++++++++++++
 lib/math/int_log.c      | 24 ++++++++++++++++++++++++
 2 files changed, 43 insertions(+)

diff --git a/include/linux/int_log.h b/include/linux/int_log.h
index 0a6f58c38..b452ff298 100644
--- a/include/linux/int_log.h
+++ b/include/linux/int_log.h
@@ -53,4 +53,23 @@ extern unsigned int intlog2(u32 value);
  */
 extern unsigned int intlog10(u32 value);
 
+/**
+ * intloge - computes loge of a value; the result is shifted left by 24 bits
+ *
+ * @value: The value (must be != 0)
+ *
+ * to use rational values you can use the following method:
+ *
+ *   intloge(value) = intloge(value * 10^x) - x * intloge(10)
+ *
+ * Some usecase examples:
+ *
+ *	intloge(10) will give 2.302... * 2^24
+ *
+ *	intloge(2.718) = intloge(2718) - 3 *intloge(10) = 0.999... * 2^24
+ *
+ * return: loge(value) * 2^24
+ */
+extern unsigned int intloge(u32 value);
+
 #endif
diff --git a/lib/math/int_log.c b/lib/math/int_log.c
index 8f9da3a2a..34d1c5065 100644
--- a/lib/math/int_log.c
+++ b/lib/math/int_log.c
@@ -131,3 +131,27 @@ unsigned int intlog10(u32 value)
 	return (log * 646456993) >> 31;
 }
 EXPORT_SYMBOL(intlog10);
+
+unsigned int intloge(u32 value)
+{
+	/**
+	 *	returns: loge(value) * 2^24
+	 *	wrong result if value = 0 (loge(0) is undefined)
+	 */
+	u64 log;
+
+	if (unlikely(value == 0)) {
+		WARN_ON(1);
+		return 0;
+	}
+
+	log = intlog2(value);
+
+	/**
+	 *	we use the following method:
+	 *	loge(x) = log2(x) * loge(2)
+	 */
+
+	return (log * 1488522236) >> 31;
+}
+EXPORT_SYMBOL(intloge);
-- 
2.30.2