go-ruby-complex

Ruby's Complex number in pure Go — exact on the numeric tower, MRI byte-exact, no cgo.

pure Go · zero cgo MRI byte-exact exact numeric tower Integer · Rational · Float exact arithmetic Abs · Arg · Conjugate Parse("1+2i") Polar Inspect / ToS 100% coverage 6 arches
Documentation GitHub
Documentation (MkDocs Material + mike) License: BSD-3-Clause Go 1.26.4+ Coverage 100%

go-ruby-complex is a pure-Go (no cgo) reimplementation of Ruby's Complex number — the a+bi number, byte-exact with MRI's inspect / to_s and arithmetic, without any Ruby runtime. Unlike Go's built-in complex128, Ruby's Complex keeps its two parts on the numeric tower: an Integer part stays an arbitrary-precision Integer, a Rational part stays Rational, and only a Float part becomes Float — so Complex(1,2)*Complex(1,2) is the exact (-3+4i). It was extracted from rbgo's internals into a reusable standalone library and is bound by rbgo as a native module just like go-ruby-rational and go-ruby-regexp — differential-tested against MRI, 100% coverage, CI green across 6 arches and 3 OSes.

Numeric tower (Num) ready

Each part is a Num — a small union of Integer (*big.Int), Rational (*big.Rat) and Float (float64) — preserving exactness exactly as MRI does. IsInt / IsRat / IsFloat / Float64 inspect it.

Exact-preserving arithmetic ready

Add / Sub / Mul / Div / Pow keep Integer and Rational parts exact: Integer×Integer stays Integer, anything Rational stays Rational, division canonicalises — Complex(2,3)**5 == (122-597i) exactly.

Magnitude & phase ready

Abs (via math.Hypot), the exact Abs2, Arg / Angle / Phase (via math.Atan2), Conjugate, Rectangular and PolarParts.

Constructors & parsing ready

New / Rect, Polar, and Parse for MRI’s Complex(string) grammar — "1+2i", "-i", "1/2+3/4i", "2.5-1.5i", "1@2" polar, j imaginary unit, _ digit separators.

MRI-exact rendering ready

Inspect ((1+2i), ((1/2)+(3/4)*i), (Infinity+1i)) and ToS (1+2i, 1/2+3/4i), reproducing Ruby’s Float#to_s formatting and the sign / *i rules.

Differential oracle & coverage ready

A wide corpus of constructors, arithmetic, conversions and string parses built here and compared byte-for-byte against the system ruby’s inspect / to_s; 100% coverage, gofmt + go vet clean, green across all six 64-bit Go arches and three OSes.

A faithful, pure-Go port of Ruby's Complex, cgo disabled, so it cross-compiles and embeds anywhere. Validated differentially against the system ruby binary — output compared byte-for-byte. It is a standalone, reusable module extracted from rbgo's internals, and a backend for the sibling org github.com/go-embedded-ruby.