go-ruby-cmath

Ruby's CMath in pure Go โ€” complex-aware sqrt / exp / log / trig, MRI-compatible, no cgo.

pure Go ยท zero cgo CMath stdlib real โ†” complex sqrt ยท cbrt ยท exp ยท log trig + hyperbolic + inverses MRI branch cuts Number value model 100% coverage 6 arches
Documentation GitHub
Documentation (MkDocs Material + mike) License: BSD-3-Clause Go 1.26.4+ Coverage 100%

go-ruby-cmath is a pure-Go (no cgo) reimplementation of Ruby's CMath standard library โ€” the complex-aware trigonometric and transcendental functions of MRI 4.0.5's cmath gem. CMath accepts real or complex arguments and returns a real result when the input lies on the real branch (CMath.sqrt(4) is 2.0) and a complex result otherwise (CMath.sqrt(-4) is (0+2i)). This library reproduces that exact real-vs-complex decision and MRI's branch cuts and float formulas โ€” without any Ruby runtime โ€” over a small explicit Number value model. It is a CMath backend for go-embedded-ruby, a standalone sibling of go-ruby-regexp, go-ruby-marshal and go-ruby-yaml โ€” differential-tested against MRI, 100% coverage, CI green across 6 arches and 3 OSes.

The Number value model ready

A Number is a real-or-complex value, the Go analogue of Ruby’s Float-or-Complex โ€” Real(x) and Complex(re, im) build arguments, and Complex(re, 0) stays complex exactly as Complex(1, 0).real? is false in Ruby.

Real-vs-complex branch ready

Each function returns a real result on the real branch (Sqrt(Real(4)) is 2.0) and a complex result otherwise (Sqrt(Real(-4)) is (0+2i)), reproducing CMath’s exact real-vs-complex decision.

Roots, exp & log ready

Sqrt, Cbrt, Exp, Log (with optional base), Log2, Log10 โ€” mirroring CMath.sqrt / cbrt / exp / log / log2 / log10, on MRI’s principal branch cuts.

Trig & hyperbolic ready

Sin / Cos / Tan, Sinh / Cosh / Tanh, and the inverses Asin / Acos / Atan / Atan2 / Asinh / Acosh / Atanh โ€” the inverses built from this package’s own Log and Sqrt, exactly as the cmath gem builds them.

MRI branch cuts ready

Outside the real branch, each function uses the same closed-form expression CMath’s Ruby source uses, so the principal branch cuts and float results agree with ruby -rcmath to floating-point rounding.

MRI oracle & coverage ready

Golden values captured from MRI 4.0.5 hold coverage at 100%; an oracle suite drives ruby -rcmath across a broad real / negative / out-of-domain / complex corpus. Green across all six 64-bit Go arches and three OSes, cgo disabled.

A faithful port of Ruby's CMath module in pure Go, cgo disabled, so it cross-compiles and embeds anywhere. It reproduces CMath's real-vs-complex branch test, principal branch cuts and closed-form complex expressions over a small Number value model. Validated differentially against ruby -rcmath across a real / negative / out-of-domain / complex corpus. It is a standalone, reusable module and a CMath backend for the sibling org github.com/go-embedded-ruby.