Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,8 @@
returning strided views that share data.
- **Elementwise** — `Add`/`Sub`/`Mul`/`Div` (+ scalar) with full **NumPy
broadcasting**, `Map`/`Neg`/`Abs`, math **ufuncs** (`Sqrt`/`Exp`/`Log`/`Sin`/
`Cos`/…), broadcasting **comparisons** (`Greater`/`Equal`/… returning Bool
`Cos`/…), rounding (`Floor`/`Ceil`, `Round` half to even as `np.round`,
`RoundHalfAway` the old half away from zero), broadcasting **comparisons** (`Greater`/`Equal`/… returning Bool
masks), `Maximum`/`Minimum`, `Logical*`, and the complex parts
`Real`/`Imag`/`Conj`/`Angle`.
- **Reductions** — whole-array (`Sum`/`Prod`/`Max`/`Min`/`Mean`), per-axis
Expand Down Expand Up @@ -141,6 +142,21 @@ one-core rule does not allow; it is kept as
[docs/perf-history.md](docs/perf-history.md) for its kernel-level analysis, and
its ratios are not a verdict.

Float64 `Abs`, `Neg`, `Square`, `Floor`, `Ceil` and `Round` run on the SIMD
kernels of go-simd/floats (v0.23.0), bit for bit the results of `math.Abs`,
`-x`, `x*x`, `math.Floor`, `math.Ceil` and `math.RoundToEven` (`Abs` and `Neg`
keep NaN bits exactly; for the others a signalling NaN may come back quieted):
on 10⁵ float64 on one core of cfarm420 they went from 243–464 µs to 70–81 µs
([docs/perf.md](docs/perf.md), *Since the table*).

**Behaviour change in the next release (a MINOR): `Round` rounds halves to
even.** It is now `np.round` with no decimals, on every dtype (float64, float32
and each part of a complex number): `Round` of 0.5, 1.5, 2.5 and -0.5 gives 0, 2,
2 and -0. Until v0.42.0 it rounded halves away from zero (1, 2, 3, -1), and
that behaviour is now `RoundHalfAway` (`math.Round`, the scalar path, the same
dtypes). The two differ only on exact halves; integers and bools are returned
unchanged by both. There is no decimals variant.

On Apple silicon the GEMM reached parity with tuned BLAS at 1024² (OpenBLAS in
an arm64 VM, single-threaded vecLib on an M4 Max), and every product beats the
pure-Go `gonum` 4–10× (**[BENCHMARKS.md](BENCHMARKS.md)**). On the other
Expand Down
4 changes: 2 additions & 2 deletions SECURITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ standard library's known vulnerabilities; `govulncheck ./...` reports none.

## Audit log

**2026-11-15 (unreleased).** The GEMM moved to
**2026-11-15 (v0.42.0, #122).** The GEMM moved to
[go-blas/blas](https://github.com/go-blas/blas) v0.2.1 (the micro-kernels, their
wrappers, the packing and their fence tests, byte for byte; the audit of that
code is that repository's). What ndarray adds is `internal/blasmm`, which hands
Expand All @@ -82,7 +82,7 @@ on an axis longer than one (a broadcast or reversed view) is copied to a
contiguous matrix first. ndarray keeps the dot kernels (`dot_<arch>.go`), the
mat-vec and the thread pool, with their wrappers and fences.

**2026-11-12 (unreleased, #103).** The gather of `random`'s `Choice`
**2026-11-12 (v0.40.2, #115, Refs #103).** The gather of `random`'s `Choice`
(`takeAxis`, random/arrays.go) now copies bytes through `bytesOf`, an
`unsafe.Slice` view of a slice's backing array of exactly `Len()·size` bytes.
Every dtype the package stores is a fixed-size value without pointers
Expand Down
2 changes: 1 addition & 1 deletion bench/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ require (
github.com/go-blas/blas v0.2.1 // indirect
github.com/go-fft/fft v0.29.0 // indirect
github.com/go-fleettools/fleettools v0.81.0 // indirect
github.com/go-simd/floats v0.17.0 // indirect
github.com/go-simd/floats v0.23.0 // indirect
golang.org/x/sys v0.49.0 // indirect
)

Expand Down
4 changes: 2 additions & 2 deletions bench/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ github.com/go-fleettools/fleettools v0.81.0 h1:UnMflmNw5b82Z+7Ums7UVaW5RrGuACCVm
github.com/go-fleettools/fleettools v0.81.0/go.mod h1:y/o3p2HZAvto9J5G5gtPxhN45zgvaYFAXCY9RCK/lQw=
github.com/go-scikit/refbench v0.3.0 h1:ng9b3FRwOWyarkoHHLar1bs43TWi9TydZeO29Yr9iSw=
github.com/go-scikit/refbench v0.3.0/go.mod h1:PhJxvLwXiQeKLP2f5ndcb9k5k4PTvU1rSFJ/MKRCrU0=
github.com/go-simd/floats v0.17.0 h1:Dv0ZmZ3k0IavvHwQgstpUz+TeIf/gGJ9HEGQ/UART8Q=
github.com/go-simd/floats v0.17.0/go.mod h1:Aq5a6oY5pUqm9Hpi+iV2nrNmaaUb0rwHvUHIerXWSvA=
github.com/go-simd/floats v0.23.0 h1:aHEbbiVmhLmoR8FdUWDCHMRctFajm11wKnfbbs9FOxk=
github.com/go-simd/floats v0.23.0/go.mod h1:Aq5a6oY5pUqm9Hpi+iV2nrNmaaUb0rwHvUHIerXWSvA=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
31 changes: 31 additions & 0 deletions benchmarks/unary_bench_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package benchmarks

import "testing"

// BenchmarkUnary times the float64 unary ufuncs on 10^5 elements, the size of
// the single-core table (#118). RoundHalfAway stays on the scalar path and is
// the control: it is what Round did before it became half-to-even.
func BenchmarkUnary(b *testing.B) {
const n = 100000
x := vec(n)
ops := []struct {
name string
do func()
}{
{"Abs", func() { _ = x.Abs() }},
{"Neg", func() { _ = x.Neg() }},
{"Square", func() { _ = x.Square() }},
{"Floor", func() { _ = x.Floor() }},
{"Ceil", func() { _ = x.Ceil() }},
{"Round", func() { _ = x.Round() }},
{"RoundHalfAway", func() { _ = x.RoundHalfAway() }},
}
for _, op := range ops {
b.Run(op.name, func(b *testing.B) {
b.SetBytes(n * 8)
for i := 0; i < b.N; i++ {
op.do()
}
})
}
}
2 changes: 1 addition & 1 deletion docs/coverage.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ backticked name in the first column. See "Counting" at the end.
| `equal`, `not_equal`, `greater`, `greater_equal`, `less`, `less_equal` | `==`, `~=`, `>`, `>=`, `<`, `<=` | `Equal`, `NotEqual`, `Greater`, `GreaterEqual`, `Less`, `LessEqual` | done | |
| `logical_and`, `logical_or`, `logical_xor`, `logical_not` | `&`, `\|`, `xor`, `~` | `LogicalAnd`, `LogicalOr`, `LogicalXor`, `LogicalNot` | done | |
| `power`, `pow` | `.^` | `Power` | partial | scalar exponent only: no array exponent, no integer-power semantics |
| `around`, `round` | `round` | `Round` | partial | rounds half away from zero (NumPy: half to even); no `decimals` |
| `around`, `round` | `round` | `Round` | partial | half to even, as NumPy (`RoundHalfAway` is the old half away from zero); no `decimals` |
| `clip` | `min(max(..))`, `rescale` | `Clip` | partial | array bounds, one-sided (`a_min` or `a_max` alone) |
| `sinh`, `cosh`, `tanh`, `arcsinh`, `arccosh`, `arctanh`, `asinh`, `acosh`, `atanh` | `sinh`, `cosh`, `tanh`, `asinh`, `acosh`, `atanh` | | missing | scalar kernels (go-numerics/special or math), SIMD later |
| `arcsin`, `arccos`, `arctan`, `asin`, `acos`, `atan` | `asin`, `acos`, `atan` | | missing | same |
Expand Down
1 change: 0 additions & 1 deletion docs/design-dtypes.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,6 @@ dtype by dtype after correctness, `float32` first.
| NumPy | here | why |
|---|---|---|
| `float16` exists; `sqrt(int8)` is `float16` | no `float16`; `sqrt(int8)`, `sqrt(uint8)` and `sqrt(bool)` give `float32` | Go has no half-precision arithmetic; `float32` is the smallest type that holds the result exactly |
| `round` is half-to-even | half-away-from-zero (unchanged) | documented since v0.1.0 |
| `datetime64`, `str_`, `object`, structured dtypes | absent | out of scope for a numeric library |

## Element access
Expand Down
2 changes: 1 addition & 1 deletion docs/design-linalg.md
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,7 @@ kd = 1, 5, 50; allocations counted exactly.

```text
internal/libm/ correctly rounded log, log1p, exp, expm1, pow (moved from random/), + exp2, log2, hypot
internal/kernels/ refgemm micro-kernels (go-asmgen, every GOARCH), no FMA
internal/kernels/ dot, mat-vec and elementwise kernels (the GEMM micro-kernels are in go-blas/blas since v0.42.0)
linalg/internal/lapack/ exact column-major ports of Reference-LAPACK v3.12.1, generic over 4 types
refblas.go level 1-3 BLAS in netlib loop order (dnrm2 Blue, ddot, daxpy, dgemv, dger, dtrmv, dtrsv, dgemm, dtrmm, dtrsm, dsyrk)
arith.go no-fuse helpers, gfortran complex mul/div, lamch, ilaenv, iparmq
Expand Down
3 changes: 2 additions & 1 deletion docs/linalg.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

Package [`linalg`](../linalg) gives ndarray arrays the functions of
`numpy.linalg`, written in Go without cgo or assembly of its own: the
matrix products it relies on are the ndarray package's packed SIMD GEMM.
matrix products it relies on are the packed SIMD GEMM of [go-blas/blas](https://github.com/go-blas/blas), which
ndarray's `MatMul` uses too (the same kernels, moved there in v0.42.0, #122).

| numpy.linalg | linalg |
|---|---|
Expand Down
1 change: 1 addition & 0 deletions docs/perf-exempt.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ Each is named with the reason it has no case (refbench's coverage rule). Every o
- `Array.Display`: builds a Jupyter MIME bundle; NumPy has no counterpart
- `Array.Map`: takes a Go callback per element; the NumPy counterpart (np.vectorize) is a Python loop, not a kernel
- `Array.Ndim`: attribute read
- `Array.RoundHalfAway`: rounds halves away from zero (math.Round); NumPy has no counterpart (np.round is half to even, which is `Array.Round`)
- `Array.SetComplex`: one scalar element access, a few ns; the NumPy counterpart is dominated by the Python interpreter, not a kernel
- `Array.Set`: one scalar element access, a few ns; the NumPy counterpart is dominated by the Python interpreter, not a kernel
- `Array.Shape`: attribute read
Expand Down
29 changes: 29 additions & 0 deletions docs/perf.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,35 @@ rounds:
element at a time. `Full` went from 131–135 µs to 84–104 µs. `Ones` calls
`Full`. `FullOf`, which fills the other dtypes, was not timed.

- Float64 `Abs`, `Neg`, `Square`, `Floor`, `Ceil` and `Round` run on the
go-simd/floats v0.23.0 kernels (above the parallel threshold, split across
cores as before) instead of a scalar loop through `Map`. The results are bit
for bit those of `math.Abs`, `-x`, `x*x`, `math.Floor`, `math.Ceil` and
`math.RoundToEven`. `Abs` and `Neg` keep NaN bits exactly; for `Square`,
`Floor`, `Ceil` and `Round` a signalling NaN may come back quieted
(`TestUnaryKernelsBitIdentical`: edge table, lengths 0–33 and one above the
threshold). `Round` is now half to even, as `np.round`; the old half away
from zero is `RoundHalfAway`, on the scalar path (see the README). `go test -bench Unary` (`benchmarks/unary_bench_test.go`), 10⁵
float64 including the result allocation, one pinned core of cfarm420
(`GOMAXPROCS=1`, `taskset -c 9`), a test binary of v0.42.0 and one of this
change, four interleaved rounds of 1 s, 1-minute load 2.34 at the start and
3.32 at the end. Before → after, range over the rounds:

| operation | before (µs) | after (µs) |
|---|---|---|
| `Abs` | 244–258 | 70–75 |
| `Neg` | 243–249 | 72–75 |
| `Square` | 243–247 | 72–80 |
| `Floor` | 432–457 | 73–81 |
| `Ceil` | 437–464 | 72–81 |
| `Round` (the old one was half away from zero) | 325–340 | 71–80 |

`Round` was measured in a second run of the same kind (four interleaved
rounds, load 2.25 to 2.42), v0.42.0 against this change. `RoundHalfAway`,
the control on the scalar path, takes 324–345 µs in the same run. These are
times of the Go code against itself; no NumPy ratio is claimed here, as the
new table run has not been made.

What remains of the allocation cause is Go's own cost. A CPU profile of a bare
`make([]float64, 100000)` shows about 60% garbage-collector marking (assists
in the allocating goroutine) and about 23% zeroing. NumPy frees each result
Expand Down
16 changes: 15 additions & 1 deletion dtype_api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -310,9 +310,12 @@ func TestTypedUnary(t *testing.T) {
if got := data[float32](t, h.Ceil()); !reflect.DeepEqual(got, []float32{2, -2}) {
t.Errorf("float32 ceil = %v", got)
}
if got := data[float32](t, h.Round()); !reflect.DeepEqual(got, []float32{2, -3}) {
if got := data[float32](t, h.Round()); !reflect.DeepEqual(got, []float32{2, -2}) {
t.Errorf("float32 round = %v", got)
}
if got := data[float32](t, h.RoundHalfAway()); !reflect.DeepEqual(got, []float32{2, -3}) {
t.Errorf("float32 RoundHalfAway = %v", got)
}
if got := data[float32](t, h.Power(2)); !reflect.DeepEqual(got, []float32{2.25, 6.25}) {
t.Errorf("float32 power = %v", got)
}
Expand All @@ -323,6 +326,17 @@ func TestTypedUnary(t *testing.T) {
if got := c.Round(); got.AtComplex(0) != 3+4i {
t.Errorf("complex round = %v", got)
}
cz := must(FromSlice([]complex128{2.5 - 3.5i, -0.5 + 1.5i}, 2))
if got := cz.Round(); got.AtComplex(0) != 2-4i || got.AtComplex(1) != complex(math.Copysign(0, -1), 2) {
t.Errorf("complex round half to even = %v", got)
}
if got := cz.RoundHalfAway(); got.AtComplex(0) != 3-4i || got.AtComplex(1) != -1+2i {
t.Errorf("complex RoundHalfAway = %v", got)
}
ii := must(FromSlice([]int32{-3, 4}, 2))
if got := data[int32](t, ii.RoundHalfAway()); !reflect.DeepEqual(got, []int32{-3, 4}) {
t.Errorf("int RoundHalfAway = %v", got)
}
mustPanic(t, "not defined for complex128", func() { c.Ceil() })
if r := i.Map(func(x float64) float64 { return x + 0.5 }); r.DType() != Float64 || r.At(0) != 1.5 {
t.Errorf("int Map = %v", r)
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ go 1.27.2
require (
github.com/go-blas/blas v0.2.1
github.com/go-fft/fft v0.29.0
github.com/go-simd/floats v0.17.0
github.com/go-simd/floats v0.23.0
)

require golang.org/x/sys v0.49.0 // indirect
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ github.com/go-blas/blas v0.2.1 h1:5uZfmvXVZn9CjE+I3DalALqWHdKz+rbBs8VffH3dAZo=
github.com/go-blas/blas v0.2.1/go.mod h1:WjhlqzQ+RA8tS473f18QtcJl5Q0GonPs3RJIxT5G7Bk=
github.com/go-fft/fft v0.29.0 h1:WtJb5K3dmbLWREvvZ50od0fxtjIBiXrg7mVybz/nPoA=
github.com/go-fft/fft v0.29.0/go.mod h1:GN5V4TWCjV05ECqH1ONfjFM6Z1m2shqCdssxKGqQ41s=
github.com/go-simd/floats v0.17.0 h1:Dv0ZmZ3k0IavvHwQgstpUz+TeIf/gGJ9HEGQ/UART8Q=
github.com/go-simd/floats v0.17.0/go.mod h1:Aq5a6oY5pUqm9Hpi+iV2nrNmaaUb0rwHvUHIerXWSvA=
github.com/go-simd/floats v0.23.0 h1:aHEbbiVmhLmoR8FdUWDCHMRctFajm11wKnfbbs9FOxk=
github.com/go-simd/floats v0.23.0/go.mod h1:Aq5a6oY5pUqm9Hpi+iV2nrNmaaUb0rwHvUHIerXWSvA=
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
39 changes: 39 additions & 0 deletions internal/kernels/unary.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package kernels

import "github.com/go-simd/floats"

// Unary float64 kernels from go-simd/floats (v0.23.0), parallelised above
// ParThreshold like the other elementwise kernels. Each is bit-identical to the
// scalar expression it replaces (math.Abs, -x, x*x, math.Floor, math.Ceil), a
// signalling NaN possibly coming back quieted.

// unaryP runs k over dst/src, serially below ParThreshold and fanned across
// cores above it. len(src) >= len(dst) is required, as for the kernels.
func unaryP(k func(dst, src []float64), dst, src []float64) {
n := len(dst)
if n < ParThreshold {
k(dst, src)
return
}
parallelFor(n, numWorkers(n), func(lo, hi int) {
k(dst[lo:hi], src[lo:hi])
})
}

// AbsP writes |src[i]| into dst[i].
func AbsP(dst, src []float64) { unaryP(floats.Abs, dst, src) }

// NegP writes -src[i] into dst[i].
func NegP(dst, src []float64) { unaryP(floats.Neg, dst, src) }

// SquareP writes src[i]*src[i] into dst[i].
func SquareP(dst, src []float64) { unaryP(floats.Square, dst, src) }

// FloorP writes math.Floor(src[i]) into dst[i].
func FloorP(dst, src []float64) { unaryP(floats.Floor, dst, src) }

// RoundEvenP writes math.RoundToEven(src[i]) into dst[i].
func RoundEvenP(dst, src []float64) { unaryP(floats.RoundEven, dst, src) }

// CeilP writes math.Ceil(src[i]) into dst[i].
func CeilP(dst, src []float64) { unaryP(floats.Ceil, dst, src) }
4 changes: 2 additions & 2 deletions ndarray.go
Original file line number Diff line number Diff line change
Expand Up @@ -842,7 +842,7 @@ func (a *Array) Neg() *Array {
if a.dtype != Float64 {
return a.intUnary(uNeg, (*Array).Neg)
}
return a.Map(func(x float64) float64 { return -x })
return a.unary(kernels.NegP)
}

// Abs returns the elementwise absolute value.
Expand All @@ -852,7 +852,7 @@ func (a *Array) Abs() *Array {
if a.dtype != Float64 {
return a.intUnary(uAbs, (*Array).Abs)
}
return a.Map(kernels.Abs)
return a.unary(kernels.AbsP)
}

// --- reductions ------------------------------------------------------------
Expand Down
19 changes: 11 additions & 8 deletions typed.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,16 +252,18 @@ const (
uNeg
uAbs
uPow
uRoundHalfAway
)

// realFuncs are the float64 functions behind the unary codes.
var realFuncs = [...]func(float64) float64{
uSqrt: math.Sqrt, uExp: math.Exp, uLog: math.Log, uLog2: log2,
uLog10: math.Log10, uSin: math.Sin, uCos: math.Cos, uTan: math.Tan,
uFloor: math.Floor, uCeil: math.Ceil, uRound: math.Round,
uSquare: func(x float64) float64 { return x * x },
uNeg: func(x float64) float64 { return -x },
uAbs: math.Abs,
uFloor: math.Floor, uCeil: math.Ceil, uRound: math.RoundToEven,
uRoundHalfAway: math.Round,
uSquare: func(x float64) float64 { return x * x },
uNeg: func(x float64) float64 { return -x },
uAbs: math.Abs,
}

// complexFuncs are the complex128 functions behind the unary codes; nil where
Expand All @@ -271,10 +273,11 @@ var complexFuncs = [...]func(complex128) complex128{
uLog2: func(z complex128) complex128 { return cmplx.Log(z) / math.Ln2 },
uLog10: cmplx.Log10, uSin: cmplx.Sin, uCos: cmplx.Cos, uTan: cmplx.Tan,
uFloor: nil, uCeil: nil,
uRound: func(z complex128) complex128 { return complex(math.Round(real(z)), math.Round(imag(z))) },
uSquare: func(z complex128) complex128 { return z * z },
uNeg: func(z complex128) complex128 { return -z },
uAbs: nil, // complex abs is real-valued: see absStore
uRound: func(z complex128) complex128 { return complex(math.RoundToEven(real(z)), math.RoundToEven(imag(z))) },
uRoundHalfAway: func(z complex128) complex128 { return complex(math.Round(real(z)), math.Round(imag(z))) },
uSquare: func(z complex128) complex128 { return z * z },
uNeg: func(z complex128) complex128 { return -z },
uAbs: nil, // complex abs is real-valued: see absStore
}

// unaryFloat32 applies f, computed in float64 and rounded, to float32
Expand Down
28 changes: 24 additions & 4 deletions ufunc.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,22 +167,42 @@ func (a *Array) Floor() *Array {
if a.dtype != Float64 {
return a.exactUnary(uFloor, (*Array).Floor)
}
return a.Map(math.Floor)
return a.unary(kernels.FloorP)
}

// Ceil returns the elementwise ceiling (least integer >= x).
func (a *Array) Ceil() *Array {
if a.dtype != Float64 {
return a.exactUnary(uCeil, (*Array).Ceil)
}
return a.Map(math.Ceil)
return a.unary(kernels.CeilP)
}

// Round returns the elementwise round-half-away-from-zero, matching math.Round.
// Round returns the elementwise rounding to the nearest integer, a half going
// to the even neighbour (2.5 gives 2, 3.5 gives 4, -0.5 gives -0), as
// np.round(a) with no decimals does and as math.RoundToEven. Float32 and
// complex elements round the same way (each part of a complex number), and
// integers and bools are returned unchanged. Before v0.43.0 Round rounded halves
// away from zero; that is RoundHalfAway.
//
// A Float64 array runs on the go-simd/floats RoundEven kernel.
func (a *Array) Round() *Array {
if a.dtype != Float64 {
return a.exactUnary(uRound, (*Array).Round)
}
return a.unary(kernels.RoundEvenP)
}

// RoundHalfAway returns the elementwise rounding to the nearest integer, a half
// going away from zero (2.5 gives 3, -2.5 gives -3, 0.5 gives 1), as math.Round
// does and as Round did before v0.43.0. It differs from Round, and from
// np.round, only on exact halves: Round sends those to the even neighbour.
// The dtypes are the same as for Round (integers and bools unchanged, float32
// and complex rounded part by part). It runs on the scalar path.
func (a *Array) RoundHalfAway() *Array {
if a.dtype != Float64 {
return a.exactUnary(uRoundHalfAway, (*Array).RoundHalfAway)
}
return a.Map(math.Round)
}

Expand All @@ -192,7 +212,7 @@ func (a *Array) Square() *Array {
if a.dtype != Float64 {
return a.intUnary(uSquare, (*Array).Square)
}
return a.Map(func(x float64) float64 { return x * x })
return a.unary(kernels.SquareP)
}

// Power returns the elementwise a**p (every element raised to p).
Expand Down
7 changes: 4 additions & 3 deletions ufunc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,11 @@ func TestMathUfuncs(t *testing.T) {
cc := mustArr(t, ok(FromData([]float64{1.2, -1.7}, 2)))
eqFloats(t, cc.Ceil().materialize(), []float64{2, -1})

// Round here is math.Round (half away from zero); this intentionally differs
// from numpy's banker's rounding, so 0.5 -> 1 and 2.5 -> 3.
// Round is half to even, as np.round: 0.5 -> 0 and 2.5 -> 2. RoundHalfAway
// is the old math.Round: 0.5 -> 1 and 2.5 -> 3.
rc := mustArr(t, ok(FromData([]float64{0.5, 1.5, 2.5, -0.5}, 4)))
eqFloats(t, rc.Round().materialize(), []float64{1, 2, 3, -1})
eqFloats(t, rc.Round().materialize(), []float64{0, 2, 2, 0})
eqFloats(t, rc.RoundHalfAway().materialize(), []float64{1, 2, 3, -1})

sq := mustArr(t, ok(FromData([]float64{2, -3}, 2)))
eqFloats(t, sq.Square().materialize(), []float64{4, 9})
Expand Down
Loading
Loading