From 2e80d5e38ed92f67767d87b544894cdc254f9459 Mon Sep 17 00:00:00 2001 From: SPRESENSE <41312067+SPRESENSE@users.noreply.github.com> Date: Sat, 10 Jul 2021 21:14:17 +0900 Subject: [PATCH] libs/libc/math: Fix calculation error of log function Fix a problem where the log function would loop infinitely by calculation error when a specific value was passed. For example, in the following case, the log function loops infinitely and never returns. So, this commit fixes to return the right value. double a = 7883961.5; double b = log(a); --- libs/libc/math/lib_log.c | 6 +++--- libs/libc/math/lib_logf.c | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/libs/libc/math/lib_log.c b/libs/libc/math/lib_log.c index ba7aae3e7c..638ed62b0a 100644 --- a/libs/libc/math/lib_log.c +++ b/libs/libc/math/lib_log.c @@ -60,7 +60,7 @@ double log(double x) { double y; double y_old; - double ney; + double ey; double epsilon; int relax_factor; int iter; @@ -75,8 +75,8 @@ double log(double x) while (y > y_old + epsilon || y < y_old - epsilon) { y_old = y; - ney = exp(-y); - y -= 1.0 - x * ney; + ey = exp(y); + y -= (ey - x) / ey; if (y > 700.0) { diff --git a/libs/libc/math/lib_logf.c b/libs/libc/math/lib_logf.c index e813568bf3..b53805da84 100644 --- a/libs/libc/math/lib_logf.c +++ b/libs/libc/math/lib_logf.c @@ -58,7 +58,7 @@ float logf(float x) { float y; float y_old; - float ney; + float ey; float epsilon; int relax_factor; int iter; @@ -73,8 +73,8 @@ float logf(float x) while (y > y_old + epsilon || y < y_old - epsilon) { y_old = y; - ney = expf(-y); - y -= 1.0F - x * ney; + ey = expf(y); + y -= (ey - x) / ey; if (y > FLT_MAX_EXP_X) {