math

package
v0.2.14 Latest Latest
Warning

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

Go to latest
Published: Jul 6, 2026 License: MIT Imports: 1 Imported by: 0

README

math

import "github.com/gechr/x/math"

Package math provides numeric helpers.

Index

func Clamp

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

Clamp restricts v to the [lo, hi] range. NaN clamps to lo; infinities clamp to the nearest bound. Unlike min(max(v, lo), hi), NaN does not propagate.

Example
fmt.Println(xmath.Clamp(5, 0, 10))
fmt.Println(xmath.Clamp(-3, 0, 10))
fmt.Println(xmath.Clamp(42, 0, 10))

Output:

5
0
10
Example (Nan)

Unlike min(max(v, lo), hi), NaN does not propagate - it clamps to lo.

fmt.Println(xmath.Clamp(math.NaN(), 1.0, 2.0))
fmt.Println(min(max(math.NaN(), 1.0), 2.0))

Output:

1
NaN
Example (Strings)

Clamp works with any ordered type, including strings.

fmt.Println(xmath.Clamp("a", "b", "d"))
fmt.Println(xmath.Clamp("c", "b", "d"))
fmt.Println(xmath.Clamp("z", "b", "d"))

Output:

b
c
d

func Clamp01

func Clamp01(v float64) float64

Clamp01 restricts v to the [0, 1] range. NaN clamps to 0.

Example
fmt.Println(xmath.Clamp01(0.5))
fmt.Println(xmath.Clamp01(-0.1))
fmt.Println(xmath.Clamp01(1.1))

Output:

0.5
0
1

Documentation

Overview

Package math provides numeric helpers.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Clamp

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

Clamp restricts `v` to the [`lo`, `hi`] range. NaN clamps to `lo`; infinities clamp to the nearest bound. Unlike `min(max(v, lo), hi)`, NaN does not propagate.

Example
package main

import (
	"fmt"

	xmath "github.com/gechr/x/math"
)

func main() {
	fmt.Println(xmath.Clamp(5, 0, 10))
	fmt.Println(xmath.Clamp(-3, 0, 10))
	fmt.Println(xmath.Clamp(42, 0, 10))
}
Output:
5
0
10
Example (Nan)

Unlike min(max(v, lo), hi), NaN does not propagate - it clamps to `lo`.

package main

import (
	"fmt"
	"math"

	xmath "github.com/gechr/x/math"
)

func main() {
	fmt.Println(xmath.Clamp(math.NaN(), 1.0, 2.0))
	fmt.Println(min(max(math.NaN(), 1.0), 2.0))
}
Output:
1
NaN
Example (Strings)

Clamp works with any ordered type, including strings.

package main

import (
	"fmt"

	xmath "github.com/gechr/x/math"
)

func main() {
	fmt.Println(xmath.Clamp("a", "b", "d"))
	fmt.Println(xmath.Clamp("c", "b", "d"))
	fmt.Println(xmath.Clamp("z", "b", "d"))
}
Output:
b
c
d

func Clamp01

func Clamp01(v float64) float64

Clamp01 restricts `v` to the [0, 1] range. NaN clamps to 0.

Example
package main

import (
	"fmt"

	xmath "github.com/gechr/x/math"
)

func main() {
	fmt.Println(xmath.Clamp01(0.5))
	fmt.Println(xmath.Clamp01(-0.1))
	fmt.Println(xmath.Clamp01(1.1))
}
Output:
0.5
0
1

Types

This section is empty.

Jump to

Keyboard shortcuts

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