mathutil

package
v0.0.13 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 16, 2026 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package mathutil provides generic numeric utility functions for comparable and ordered types.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Abs

func Abs[T ~int | ~int8 | ~int16 | ~int32 | ~int64 | ~float32 | ~float64](v T) T

Abs returns the absolute value of a signed number.

func Average

func Average[T Number](values []T) float64

Average returns the arithmetic mean of the values. Returns 0 for an empty slice.

func CeilDiv

func CeilDiv[T ~int | ~int32 | ~int64](a, b T) T

CeilDiv performs integer division rounding up (ceiling division). Both a and b must be non-negative (a >= 0, b > 0). For negative values, use standard integer division instead.

func Clamp

func Clamp[T cmp.Ordered](val, lo, hi T) T

Clamp restricts val to the range [lo, hi].

func DivMod

func DivMod[T ~int | ~int32 | ~int64](a, b T) (T, T)

DivMod returns quotient and remainder.

func InRange

func InRange[T cmp.Ordered](val, lo, hi T) bool

InRange checks whether val is within [lo, hi] (inclusive).

func MaxSlice

func MaxSlice[T cmp.Ordered](values []T) T

MaxSlice returns the maximum value in the slice. Panics on empty slice.

func MinSlice

func MinSlice[T cmp.Ordered](values []T) T

MinSlice returns the minimum value in the slice. Panics on empty slice.

func Percentage

func Percentage(part, total float64) float64

Percentage calculates (part / total * 100) safely, returning 0 if total is 0.

func RoundTo

func RoundTo(val float64, places int) float64

RoundTo rounds a float64 to the given number of decimal places.

func SafeDiv

func SafeDiv[T Number](a, b, defaultVal T) T

SafeDiv divides a by b, returning defaultVal if b is zero.

func Sum

func Sum[T Number](values []T) T

Sum returns the sum of all elements in the slice.

Types

type Number

type Number interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr |
		~float32 | ~float64
}

Number is a constraint for all numeric types.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL