Mod Versus Remainder Float Semantics

Compare math.Mod and math.Remainder on the same operands: truncated division keeps the dividend sign, IEEE 754 remainder rounds to the nearest quotient.

GoData Integrity

Code

gosnippet
22 lines
package main

import (
	"fmt"
	"math"
)

func main() {
	// Mod:截断除法的余数,符号跟随被除数
	fmt.Println("mod(5,3):", math.Mod(5, 3), " mod(-5,3):", math.Mod(-5, 3))

	// Remainder:IEEE 754 就近舍入求余,|结果| <= 除数的一半
	fmt.Println("rem(5,3):", math.Remainder(5, 3), " rem(-5,3):", math.Remainder(-5, 3))

	// 周期回绕:把任意角度规范回 (-π, π] 区间
	angle := 9.0
	wrapped := math.Remainder(angle, 2*math.Pi)
	fmt.Println("9 rad wrapped:", wrapped/math.Pi, "π")

	// Mod(-6,3) 的结果是 -0:与 0 相等但符号位为负
	fmt.Println("mod(-6,3)==0:", math.Mod(-6, 3) == 0, " signbit:", math.Signbit(math.Mod(-6, 3)))
}

How it works

Mod Versus Remainder Float Semantics comes down to the function main.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.

Using it

Signature: func main()

Running the file prints labeled results such as mod(5,3):, rem(5,3):, 9 rad wrapped: — each operation’s effect is visible in the output.

Key statements

wrapped := math.Remainder(angle, 2*math.Pi)

Interactive Tools for This Topic

FAQ

What does Mod Versus Remainder Float Semantics print when run?
Execute the whole file; each printed line is prefixed with a label like `mod(5,3):`, `rem(5,3):`, `9 rad wrapped:`.