ziglang/zig
260
5.9k
Fork
You've already forked zig
764

std.math.acosh of large negative numbers does not return nan #35315

Open
opened 2026年05月15日 09:08:41 +02:00 by 13091101 · 4 comments

Zig Version

0.16.0

Steps to Reproduce and Observed Behavior

I stumbled on this by accident, but the title describes the problem quite accurately: acosh should return nan for negative numbers, but returns finite values for some large negative values.

Steps to reproduce

Input:

 const std: type = @import("std");
 
 pub fn main() void {
 const x: f64 = -1.9e4;
 const result: f64 = std.math.acosh(x);
 std.debug.print("x: {e}, acosh(x): {e}, isNan: {}\n", .{ x, result, std.math.isNan(result) });
 }

Output:
x: -1.9e4, acosh(x): -7.288321402140781e0, isNan: false

This seems to start returning finite values for inputs smaller than -1e4. It seems to work correctly for certain values (e.g. 4e-4, 1.5e-4, 2e-4).

Reproducible with the following build modes:

  • Debug Mode / Default zig run and zig build run.
  • ReleaseFast, ReleaseSafe.

Observed Behaviour

  • std.math.acosh(-1.9e4) returns -7.288321402140781e0
  • std.math.acosh(-2e4) returns -nan

Environment Information

  • OS: NixOS Yarara
  • Zig version: 0.16.0
  • target: x86_64-linux.6.19.8...6.19.8-gnu.2.42 (Intel Alderlake)

Expected Behavior

Expected Behaviour

  • std.math.acosh(-1.9e4) should return nan
  • std.math.acosh(-2e4) should return nan
### Zig Version 0.16.0 ### Steps to Reproduce and Observed Behavior I stumbled on this by accident, but the title describes the problem quite accurately: acosh should return `nan` for negative numbers, but returns finite values for some large negative values. ### Steps to reproduce Input: ``` const std: type = @import("std"); pub fn main() void { const x: f64 = -1.9e4; const result: f64 = std.math.acosh(x); std.debug.print("x: {e}, acosh(x): {e}, isNan: {}\n", .{ x, result, std.math.isNan(result) }); } ``` Output: ```x: -1.9e4, acosh(x): -7.288321402140781e0, isNan: false``` This seems to start returning finite values for inputs smaller than `-1e4`. It seems to work correctly for certain values (e.g. `4e-4, 1.5e-4`, `2e-4`). Reproducible with the following build modes: - Debug Mode / Default `zig run` and `zig build run`. - ReleaseFast, ReleaseSafe. ### Observed Behaviour - `std.math.acosh(-1.9e4)` returns `-7.288321402140781e0` - `std.math.acosh(-2e4)` returns `-nan` ### Environment Information - OS: NixOS Yarara - Zig version: 0.16.0 - target: x86_64-linux.6.19.8...6.19.8-gnu.2.42 (Intel Alderlake) ### Expected Behavior ### Expected Behaviour - `std.math.acosh(-1.9e4)` should return `nan` - `std.math.acosh(-2e4)` should return `nan`
Contributor
Copy link

The acosh implementation is a Zig port of the musl code. I downloaded a fresh cross toolchain from musl.cc (Note: it's community supported and not affiliated with the musl project, trust at your own risk).

#include <stdio.h>#include <math.h>
int main(void)
{
 printf("%f\n", acosh(-1.9e4));
 return 0;
}
$ ./x86_64-linux-musl-cross/bin/x86_64-linux-musl-cc -o acosh acosh.c -lm -static
$ ./acosh
-7.288321

So it looks like the problem originated upstream, and should probably be reported there too.

The problematic part of the code seems to be this branch in acosh64:

// |x| < 0x1p26elseif(e<0x3FF+26){return@log(2*x-1/(x+@sqrt(x*x-1)));}

The idea here is that 2x - 1/(x + sqrt(x^2 - 1)) is only ever non-negative if x >= 1, so @log will return NaN for all values that are outside the domain of arccosh. The expression isn't an approximation, and in fact:

@log(2*x-1/(x+@sqrt(x*x-1)))=@log(x+sqrt(x*x-1))=arccosh(x)

So this code isn't wrong per se, when one is working with real numbers. What's happening is that the expression 1 / (x + @sqrt(x * x - 1)) is falling victim to catastrophic cancellation. One of examples given on that page is that of arcsine(ix). Note that arcsine(ix) = i arcsinh(x), which has a fairly similar definition to arccosh(x), so this is almost a textbook example.

Let x: f128 = -1.9e4 for a moment:

1/(x+@sqrt(x*x-1))==-37999.99997368421050809155699567155>-38000

And so inner expression inside @log(...) is negative, and @log returns NaN.

But if we switch back to double precision f64:

1/(x+@sqrt(x*x-1)))==-38000.00068347437<-38000

Which gives an incorrect positive expression inside @log(...).

The `acosh` implementation is a Zig port of the `musl` code. I downloaded a fresh cross toolchain from [musl.cc](https://musl.cc/) (Note: it's community supported and not affiliated with the musl project, trust at your own risk). ```c #include <stdio.h> #include <math.h> int main(void) { printf("%f\n", acosh(-1.9e4)); return 0; } ``` ``` $ ./x86_64-linux-musl-cross/bin/x86_64-linux-musl-cc -o acosh acosh.c -lm -static $ ./acosh -7.288321 ``` So it looks like the problem originated upstream, and should probably be reported there too. The problematic part of the code seems to be this branch in `acosh64`: ```zig // |x| < 0x1p26 else if (e < 0x3FF + 26) { return @log(2 * x - 1 / (x + @sqrt(x * x - 1))); } ``` The idea here is that `2x - 1/(x + sqrt(x^2 - 1))` is only ever non-negative if `x >= 1`, so `@log` will return `NaN` for all values that are outside the domain of `arccosh`. The expression isn't an approximation, and in fact: ```zig @log(2 * x - 1 / (x + @sqrt(x * x - 1))) = @log(x + sqrt(x * x - 1)) = arccosh(x) ``` So this code isn't _wrong_ per se, when one is working with *real* numbers. What's happening is that the expression `1 / (x + @sqrt(x * x - 1))` is falling victim to [catastrophic cancellation](https://en.wikipedia.org/wiki/Catastrophic_cancellation#Example:_Complex_arcsine). One of examples given on that page is that of `arcsine(ix)`. Note that `arcsine(ix) = i arcsinh(x)`, which has a fairly similar definition to `arccosh(x)`, so this is almost a textbook example. Let `x: f128 = -1.9e4` for a moment: ```zig 1 / (x + @sqrt(x * x - 1)) == -37999.99997368421050809155699567155 > -38000 ``` And so inner expression inside `@log(...)` is negative, and `@log` returns `NaN`. But if we switch back to double precision `f64`: ```zig 1 / (x + @sqrt(x * x - 1))) == -38000.00068347437 < -38000 ``` Which gives an incorrect positive expression inside `@log(...)`.
Contributor
Copy link

As a fix, I'd suggest switching to an implementation based on FreeBSD. Something like this:

conststd=@import("std");constmath=std.math;constexpect=std.testing.expect;fnacosh64(x:f64)f64{consti=@as(i64,@bitCast(x));conste:i12=@intCast(i>>52);constm=@as(u64,@bitCast(i))&0x000F_FFFF_FFFF_FFFF;if(e<0x3FF){// x < 1// I'm following the FreeBSD semantics of using a signalling NaN in this case, // but don't know if that is desired behaviour for Zigreturnstd.math.snan(f64);}elseif(e>=0x7FF){// x is inf or NaNreturnx+x;}elseif(e>=0x41B){// x > 2^28return@log(x)+math.ln2;}elseif(e==0x3FFandm==0){// x == 0return0.0;}elseif(e>0x400){// 2^28 > x > 2return@log(2*x-1/(x+@sqrt(x*x-1)));}else{returnmath.log1p(x-1+@sqrt((x-1)*(x-1)+2*(x-1)));}}testacosh64{constepsilon=0.000001;tryexpect(math.approxEqAbs(f64,acosh64(1.5),0.962424,epsilon));tryexpect(math.approxEqAbs(f64,acosh64(37.45),4.315976,epsilon));tryexpect(math.approxEqAbs(f64,acosh64(89.123),5.183133,epsilon));tryexpect(math.approxEqAbs(f64,acosh64(123123.234375),12.414088,epsilon));}test"acosh64.special"{tryexpect(math.isNan(acosh64(math.nan(f64))));tryexpect(math.isNan(acosh64(0.5)));tryexpect(math.isNan(acosh64(-1.9e-4)));}

I'd put a PR together quickly myself, but I only have access to my work machine at the moment. The above may not be exactly correct either, I just threw it together quickly, modifying it slightly to use Zig's arbitrary sized integers and reduce nesting.

As a fix, I'd suggest switching to an [implementation based on FreeBSD](https://cgit.freebsd.org/src/tree/lib/msun/src/e_acosh.c). Something like this: ```zig const std = @import("std"); const math = std.math; const expect = std.testing.expect; fn acosh64(x: f64) f64 { const i = @as(i64, @bitCast(x)); const e: i12 = @intCast(i >> 52); const m = @as(u64, @bitCast(i)) & 0x000F_FFFF_FFFF_FFFF; if (e < 0x3FF) { // x < 1 // I'm following the FreeBSD semantics of using a signalling NaN in this case, // but don't know if that is desired behaviour for Zig return std.math.snan(f64); } else if (e >= 0x7FF) { // x is inf or NaN return x + x; } else if (e >= 0x41B) { // x > 2^28 return @log(x) + math.ln2; } else if (e == 0x3FF and m == 0) { // x == 0 return 0.0; } else if (e > 0x400) { // 2^28 > x > 2 return @log(2 * x - 1 / (x + @sqrt(x * x - 1))); } else { return math.log1p(x - 1 + @sqrt((x - 1) * (x - 1) + 2 * (x - 1))); } } test acosh64 { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, acosh64(1.5), 0.962424, epsilon)); try expect(math.approxEqAbs(f64, acosh64(37.45), 4.315976, epsilon)); try expect(math.approxEqAbs(f64, acosh64(89.123), 5.183133, epsilon)); try expect(math.approxEqAbs(f64, acosh64(123123.234375), 12.414088, epsilon)); } test "acosh64.special" { try expect(math.isNan(acosh64(math.nan(f64)))); try expect(math.isNan(acosh64(0.5))); try expect(math.isNan(acosh64(-1.9e-4))); } ``` I'd put a PR together quickly myself, but I only have access to my work machine at the moment. The above may not be exactly correct either, I just threw it together quickly, modifying it slightly to use Zig's arbitrary sized integers and reduce nesting.

I'm not too familiar with the specifics of implementing this as part of the math library, as I started using Zig very recently, but is there a particular reason all the conditions need to be handled in our case? Something like this:

conststd=@import("std");constmath=std.math;fnacosh64(x:f64)f64{consti:i64=@bitCast(x);conste:i64=@bitCast(i>>52);// I couldn't get it to compile successfully with i12if(e<0x3FF){returnmath.snan(f64);}elseif(e>=0x41B){return@log(x)+math.ln2;}else{return@log(x+@sqrt((x*x)-1));}}test"acosh64"{varxo256=std.Random.Xoshiro256.init(0);varrng=xo256.random();consttol:f64=1e-14;consttest_count:usize=1e7;constrange:f64=1e8;for(0..test_count)|_|{constx:f64=range*rng.float(f64)-0.5*range;constcurrent:f64=math.acosh(x);constproposed:f64=acosh64(x);if(x<1.0){trystd.testing.expect(math.isNan(proposed));}elseif(math.isNan(x)){trystd.testing.expect(math.isNan(proposed));}elseif(math.isInf(x)){trystd.testing.expect(math.isInf(proposed));}else{trystd.testing.expect(math.approxEqAbs(f64,current,proposed,tol));}}}

Doesn't have quite as much conditional complexity and seems to handle all cases correctly, at least from what I have been able to test so far, and should propagate infs/nans. It also seems to outperform the current implementation (~2x) based on very rudimentary testing.

I'm not too familiar with the specifics of implementing this as part of the math library, as I started using Zig very recently, but is there a particular reason all the conditions need to be handled in our case? Something like this: ```zig const std = @import("std"); const math = std.math; fn acosh64(x: f64) f64 { const i: i64 = @bitCast(x); const e: i64 = @bitCast(i >> 52); // I couldn't get it to compile successfully with i12 if (e < 0x3FF) { return math.snan(f64); } else if (e >= 0x41B) { return @log(x) + math.ln2; } else { return @log(x + @sqrt((x * x) - 1)); } } test "acosh64" { var xo256 = std.Random.Xoshiro256.init(0); var rng = xo256.random(); const tol: f64 = 1e-14; const test_count: usize = 1e7; const range: f64 = 1e8; for (0..test_count) |_| { const x: f64 = range * rng.float(f64) - 0.5 * range; const current: f64 = math.acosh(x); const proposed: f64 = acosh64(x); if (x < 1.0) { try std.testing.expect(math.isNan(proposed)); } else if (math.isNan(x)) { try std.testing.expect(math.isNan(proposed)); } else if (math.isInf(x)) { try std.testing.expect(math.isInf(proposed)); } else { try std.testing.expect(math.approxEqAbs(f64, current, proposed, tol)); } } } ``` Doesn't have quite as much conditional complexity and seems to handle all cases correctly, at least from what I have been able to test so far, and should propagate infs/nans. It also seems to outperform the current implementation (~2x) based on very rudimentary testing.
Contributor
Copy link

Sorry, that should've been an @intCast. I've corrected it.

And I'm not sure which conditions really need to be handled here, the catastrophic cancellation just nerd sniped me early and I figured I'd go with something tried and tested.

Sorry, that should've been an `@intCast`. I've corrected it. And I'm not sure which conditions really need to be handled here, the catastrophic cancellation just nerd sniped me early and I figured I'd go with something tried and tested.
Sign in to join this conversation.
No Branch/Tag specified
master
elfv2
spork8
restricted
0.16.x
panic-rewrite
parking-futex-lockfree
windows-Io-cleanup
Io-watch
ParseCommandLineOptions
windows-async-files
poll-ring
debug-file-leaks-differently
debug-file-leaks
ProcessPrng
elfv2-dyn
jobserver
threadtheft
io-threaded-no-queue
0.15.x
Io.net
comptime-allocator
restricted-function-pointers
cli
wasm-linker-writer
wrangle-writer-buffering
sha1-stream
async-await-demo
fixes
0.14.x
ast-node-methods
macos-debug-info
make-vs-configure
fuzz-macos
sans-aro
ArrayList-reserve
incr-bug
llvm-ir-nosanitize-metadata
ci-tarballs
ci-scripts
threadpool
0.12.x
new-pkg-hash
json-diagnostics
more-doctests
rework-comptime-mutation
0.11.x
ci-perf-comment
stage2-async
0.10.x
autofix
0.9.x
aro
hcs
0.8.x
0.7.x
0.16.0
0.15.2
0.15.1
0.15.0
0.14.1
0.14.0
0.12.1
0.13.0
0.12.0
0.11.0
0.10.1
0.10.0
0.9.1
0.9.0
0.8.1
0.8.0
0.7.1
0.7.0
0.6.0
0.5.0
0.4.0
0.3.0
0.2.0
0.1.1
0.1.0
Labels
Clear labels
abi/f32
abi/ilp32
abi/sf
accepted
This proposal is planned.
arch/21k
arch/6502
arch/aarch64
arch/alpha
arch/amdgcn
arch/arc
arch/arc32
arch/arc64
arch/arm
arch/avr
arch/bfin
arch/bpf
arch/colossus
arch/cris
arch/csky
arch/dlx
arch/epiphany
arch/fr30
arch/frv
arch/hexagon
arch/hppa
arch/hppa64
arch/ia64
arch/kalimba
arch/kvx
arch/lanai
arch/lm32
arch/loongarch32
arch/loongarch64
arch/m32r
arch/m68k
arch/m88k
arch/mcore
arch/microblaze
arch/mips
arch/mips64
arch/mmix
arch/moxie
arch/mrisc32
arch/msp430
arch/nds32
arch/ns32k
arch/nvptx
arch/or1k
arch/powerpc
arch/powerpc64
arch/propeller
arch/riscv32
arch/riscv64
arch/rl78
arch/rx
arch/s390x
arch/sh
arch/sparc
arch/sparc64
arch/spirv
arch/spu
arch/tricore
arch/v850
arch/vax
arch/vc4
arch/ve
arch/wasm
arch/x86
arch/x86_64
arch/xcore
arch/xtensa
autodoc
The web application for interactive documentation and generation of its assets.
backend/c
The C backend outputs C source code.
backend/llvm
The LLVM backend outputs an LLVM bitcode module.
backend/self-hosted
The self-hosted backends produce machine code directly.
binutils
Zig's included binary utilities: zig ar, zig dlltool, zig lib, zig ranlib, zig objcopy, and zig rc.
breaking
Implementing this issue could cause existing code to no longer compile or have different behavior.
build system
The Zig build system - zig build, std.Build, the build runner, and package management.
debug info
An issue related to debug information (e.g. DWARF) produced by the Zig compiler.
docs
An issue with documentation, e.g. the language reference or standard library doc comments.
error message
This issue points out an error message that is unhelpful and should be improved.
frontend
Tokenization, parsing, AstGen, ZonGen, Sema, Legalize, and Liveness.
fuzzing
An issue related to Zig's integrated fuzz testing.
incremental
Reuse of internal compiler state for faster compilation.
lib/c
This issue relates to Zig's libc implementation and/or vendored libcs.
lib/compiler-rt
This issue relates to Zig's compiler-rt library.
lib/cxx
This issue relates to Zig's vendored libc++ and/or libc++abi.
lib/std
This issue relates to Zig's standard library.
lib/tsan
This issue relates to Zig's vendored libtsan.
lib/ubsan-rt
This issue relates to Zig's ubsan-rt library.
lib/unwind
This issue relates to Zig's vendored libunwind.
linking
Zig's integrated object file and incremental linker.
miscompilation
The compiler reports success but produces semantically incorrect code.
os/android
os/contiki
os/dragonfly
os/driverkit
os/emscripten
os/freebsd
os/fuchsia
os/haiku
os/hermit
os/hurd
os/illumos
os/ios
os/linux
os/maccatalyst
os/macos
os/managarm
os/netbsd
os/ohos
os/openbsd
os/plan9
os/redox
os/rtems
os/serenity
os/tvos
os/uefi
os/visionos
os/wasi
os/watchos
os/windows
proposal
This issue suggests language modifications. If it also has the "accepted" label then it is planned.
release notes
This issue or pull request should be mentioned in the release notes.
testing
This issue is related to testing the compiler, standard library, or other parts of Zig.
zig cc
Zig as a drop-in C-family compiler.
zig fmt
The Zig source code formatter.
zig reduce
The Zig source code reduction tool.
bounty
https://ziglang.org/news/announcing-donor-bounties
bug
Observed behavior contradicts documented or intended behavior.
contributor-friendly
This issue is limited in scope and/or knowledge of project internals.
downstream
An issue with a third-party project that uses this project.
enhancement
Solving this issue will likely involve adding new logic or components to the codebase.
infra
An issue related to project infrastructure, e.g. continuous integration.
optimization
A task to improve performance and/or resource usage.
question
No questions on the issue tracker; use a community space instead.
regression
Something that used to work in a previous version stopped working
upstream
An issue with a third-party project that this project uses.
use case
Describes a real use case that is difficult or impossible, but does not propose a solution.
No labels
abi/f32
abi/ilp32
abi/sf
accepted
arch/21k
arch/6502
arch/aarch64
arch/alpha
arch/amdgcn
arch/arc
arch/arc32
arch/arc64
arch/arm
arch/avr
arch/bfin
arch/bpf
arch/colossus
arch/cris
arch/csky
arch/dlx
arch/epiphany
arch/fr30
arch/frv
arch/hexagon
arch/hppa
arch/hppa64
arch/ia64
arch/kalimba
arch/kvx
arch/lanai
arch/lm32
arch/loongarch32
arch/loongarch64
arch/m32r
arch/m68k
arch/m88k
arch/mcore
arch/microblaze
arch/mips
arch/mips64
arch/mmix
arch/moxie
arch/mrisc32
arch/msp430
arch/nds32
arch/ns32k
arch/nvptx
arch/or1k
arch/powerpc
arch/powerpc64
arch/propeller
arch/riscv32
arch/riscv64
arch/rl78
arch/rx
arch/s390x
arch/sh
arch/sparc
arch/sparc64
arch/spirv
arch/spu
arch/tricore
arch/v850
arch/vax
arch/vc4
arch/ve
arch/wasm
arch/x86
arch/x86_64
arch/xcore
arch/xtensa
autodoc
backend/c
backend/llvm
backend/self-hosted
binutils
breaking
build system
debug info
docs
error message
frontend
fuzzing
incremental
lib/c
lib/compiler-rt
lib/cxx
lib/std
lib/tsan
lib/ubsan-rt
lib/unwind
linking
miscompilation
os/android
os/contiki
os/dragonfly
os/driverkit
os/emscripten
os/freebsd
os/fuchsia
os/haiku
os/hermit
os/hurd
os/illumos
os/ios
os/linux
os/maccatalyst
os/macos
os/managarm
os/netbsd
os/ohos
os/openbsd
os/plan9
os/redox
os/rtems
os/serenity
os/tvos
os/uefi
os/visionos
os/wasi
os/watchos
os/windows
proposal
release notes
testing
zig cc
zig fmt
zig reduce
bounty
bug
contributor-friendly
downstream
enhancement
infra
optimization
question
regression
upstream
use case
Milestone
Clear milestone
No items
No milestone
Projects
Clear projects
No items
No project
Assignees
Clear assignees
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
ziglang/zig#35315
Reference in a new issue
ziglang/zig
No description provided.
Delete branch "%!s()"

Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?