commit fd680ba5fbe99dde71b6ec28ecae1cddf4fed71b (tree)
parent 4cad6f5372f6f17e249c24fba4d23466fa853fc0
Author: mihael <hi@mihaelm.com>
Date: Sun, 15 Mar 2026 23:13:24 +0100
`libzigc`: Implement `tanh`
The changes were tested by running following commands:
```
$ ./build/stage3/bin/zig build -p stage4 -Denable-llvm -Dno-lib
$ stage4/bin/zig build test-libc -Dlibc-test-path=<LIBC-TEST-PATH> -Dtest-filter=tanh -fqemu -fwasmtime --summary line
Build Summary: 1289/1289 steps succeeded
```
Diffstat:
4 files changed, 5 insertions(+), 47 deletions(-)
diff --git a/lib/c/math.zig b/lib/c/math.zig
@@ -63,6 +63,7 @@ comptime {
symbol(&pow, "pow");
symbol(&pow10, "pow10");
symbol(&pow10f, "pow10f");
+ symbol(&tanh, "tanh");
}
if (builtin.target.isMuslLibC()) {
@@ -338,3 +339,7 @@ test "rint" {
try expectEqual(@as(f64, 2.0), rint(2.5));
try expectEqual(@as(f64, 4.0), rint(3.5));
}
+
+fn tanh(x: f64) callconv(.c) f64 {
+ return math.tanh(x);
+}
diff --git a/lib/libc/musl/src/math/tanh.c b/lib/libc/musl/src/math/tanh.c
@@ -1,45 +0,0 @@
-#include "libm.h"
-
-/* tanh(x) = (exp(x) - exp(-x))/(exp(x) + exp(-x))
- * = (exp(2*x) - 1)/(exp(2*x) - 1 + 2)
- * = (1 - exp(-2*x))/(exp(-2*x) - 1 + 2)
- */
-double tanh(double x)
-{
- union {double f; uint64_t i;} u = {.f = x};
- uint32_t w;
- int sign;
- double_t t;
-
- /* x = |x| */
- sign = u.i >> 63;
- u.i &= (uint64_t)-1/2;
- x = u.f;
- w = u.i >> 32;
-
- if (w > 0x3fe193ea) {
- /* |x| > log(3)/2 ~= 0.5493 or nan */
- if (w > 0x40340000) {
- /* |x| > 20 or nan */
- /* note: this branch avoids raising overflow */
- t = 1 - 0/x;
- } else {
- t = expm1(2*x);
- t = 1 - 2/(t+2);
- }
- } else if (w > 0x3fd058ae) {
- /* |x| > log(5/3)/2 ~= 0.2554 */
- t = expm1(2*x);
- t = t/(t+2);
- } else if (w >= 0x00100000) {
- /* |x| >= 0x1p-1022, up to 2ulp error in [0.1,0.2554] */
- t = expm1(-2*x);
- t = -t/(t+2);
- } else {
- /* |x| is subnormal */
- /* note: the branch above would not raise underflow in [0x1p-1023,0x1p-1022) */
- FORCE_EVAL((float)x);
- t = x;
- }
- return sign ? -t : t;
-}
diff --git a/src/libs/musl.zig b/src/libs/musl.zig
@@ -1003,7 +1003,6 @@ const src_files = [_][]const u8{
"musl/src/math/sinl.c",
"musl/src/math/__tan.c",
"musl/src/math/__tandf.c",
- "musl/src/math/tanh.c",
"musl/src/math/tanhf.c",
"musl/src/math/tanhl.c",
"musl/src/math/__tanl.c",
diff --git a/src/libs/wasi_libc.zig b/src/libs/wasi_libc.zig
@@ -793,7 +793,6 @@ const libc_top_half_src_files = [_][]const u8{
"musl/src/math/sinl.c",
"musl/src/math/__tan.c",
"musl/src/math/__tandf.c",
- "musl/src/math/tanh.c",
"musl/src/math/tanhf.c",
"musl/src/math/tanhl.c",
"musl/src/math/__tanl.c",