Skip to content

feat(compiler): compute and format complex numbers - #547

Merged
paralin merged 1 commit into
s4wave:devfrom
cogentcore:feat/complex-arithmetic
Oct 25, 2026
Merged

paralin merged 1 commit into
s4wave:devfrom
cogentcore:feat/complex-arithmetic

Conversation

@rcoreilly

Copy link
Copy Markdown
Contributor

Complex numbers are objects of their real and imaginary parts, but +, -, * and / of complex operands lowered to the JavaScript operators, which concatenate the objects as strings or give NaN, and fmt formatted a complex number as a struct, {1 2} rather than (1+2i).

The compiler now lowers the binary arithmetic operators, unary minus and the assignment forms on complex types to runtime helpers, complexAdd, complexSub, complexMul, complexDiv and complexNeg. An operand that is a constant of integer or float value lowers to a number, which the helpers take as a complex number with a zero imaginary part. A complex64 result is rounded to float32 parts. complexDiv follows the Go runtime's complex128div (Smith's algorithm, with the C99 corrections for infinities and zeros), so division by zero and by infinities gives the same results as Go, without panicking.

fmt formats a complex number as Go does for %v and the float verbs e, f and g, with the imaginary part always signed: (1+2i), (1.00+2.00i), (3.000000e+00-1.000000e+00i). It recognizes one by the basic type it is boxed with or, inside composite values, by its form.

complex_arithmetic checks the operators, the assignment forms, complex64 rounding, division by zero and infinity, and formatting against Go.

Complex numbers are objects of their two parts, but the arithmetic operators lowered to the JavaScript ones, which concatenate or give NaN for objects, and fmt formatted them as structs.

The compiler now lowers +, -, *, / and unary - of complex operands, and their assignment forms, to runtime helpers, rounding complex64 results to float32 parts. Division follows the Go runtime's complex128div, so division by zero and by infinities gives the same infinities and NaNs. fmt formats a complex number as Go does, for %v and the float verbs.

Signed-off-by: Randall C. O'Reilly <oreilly@ucdavis.edu>
@paralin
paralin changed the base branch from master to dev October 25, 2026 18:38
@paralin
paralin merged commit fd055d8 into s4wave:dev Oct 25, 2026
7 checks passed
@paralin

paralin commented Oct 25, 2026

Copy link
Copy Markdown
Member

Landed on master as ef8c3f1, rebased onto the batch #532 to #550, with regenerated fixtures in fca8071.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants