Go Math Package
The math package provides standard mathematical constants and functions. It works primarily with the float64 type.
1. Common Constants
2. Basic Functions
math.Abs(x): Absolute value.math.Max(x, y): Maximum of two numbers.math.Min(x, y): Minimum of two numbers.math.Sqrt(x): Square root.math.Pow(x, y): x to the power of y.
3. Rounding
math.Floor(x): Rounds down to nearest integer.math.Ceil(x): Rounds up to nearest integer.math.Round(x): Rounds to the nearest integer (0.5 rounds away from zero).
4. Special Values
Go treats things like "Not a Number" (NaN) and Infinity as valid float64 values.
Best Practices
- Floating-Point Accuracy: Remember that
0.1 + 0.2might not exactly equal0.3due to how computers store decimals. For money, use anint(cents) or a specialized decimal library. - Explicit Conversion: If you have an
int, you must convert it tofloat64before using math functions:math.Sqrt(float64(myInt)). - Trigonometry: Functions like
math.Sinandmath.Cosexpect radians, not degrees.