-
Notifications
You must be signed in to change notification settings - Fork 18.6k
Description
Proposal Details
Abstract
This proposal suggests extending the existing math package to include generic versions of core mathematical functions such as Abs, Pow, Log, and Sin, leveraging Go’s type parameters (generics) introduced in Go 1.18.
The goal is to make the math package more expressive and reusable for different numeric types while maintaining full backward compatibility with existing float64-specific APIs.
Background
Currently, the math package only supports float64 operations. While this design has served well historically, it limits flexibility for developers working with other numeric types such as float32, int, or complex.
For example, if a developer needs to compute an absolute value or a power function for integers, they must either:
- convert values to
float64, risking precision loss, or - reimplement basic logic (e.g.,
if x < 0 { return -x }).
With the advent of generics and the availability of the constraints package, it’s now possible to define type-safe, efficient, and reusable versions of mathematical functions that work across numeric types without reflection or unsafe casting.
Proposal
Extend the existing math package by introducing generic equivalents for certain mathematical functions, while keeping the existing ones intact for backward compatibility.
For example:
package math
import "golang.org/x/exp/constraints"
// Abs returns the absolute value of x.
func Abs[T constraints.Signed | constraints.Float](x T) T {
if x < 0 {
return -x
}
return x
}
// Pow returns x raised to the power y.
func Pow[T constraints.Float](x, y T) T {
// Generic version can delegate to existing math.Pow for float64
// or provide type-specific behavior for float32.
return T(math.Pow(float64(x), float64(y)))
}
// Log returns the natural logarithm of x.
func Log[T constraints.Float](x T) T {
return T(math.Log(float64(x)))
}
// Sin returns the sine of the radian argument x.
func Sin[T constraints.Float](x T) T {
return T(math.Sin(float64(x)))
}