Exact Ratios With big.Rat

Represent rates as big.Rat rational numbers so one-third stays exact in division, comparison, and re-float, instead of drifting through float64.

GoData Integrity

Code

gosnippet
26 lines
package main

import (
	"fmt"
	"math/big"
)

func main() {
	// 三分之一用有理数保存:分子分母精确,不丢精度
	third := new(big.Rat).SetFrac64(1, 3)

	sum := new(big.Rat).Add(third, third)
	sum.Add(sum, third)
	fmt.Println("1/3*3 =", sum.RatString(), "(exact 1)")

	// float64 路径:三次相加后离 1 差一个 ulp
	f := 1.0 / 3
	fmt.Println("float:", f+f+f)

	// 精确比较:float64 只能靠 epsilon,Rat 用 Cmp 直接判定
	fmt.Println("rat == 1:", sum.Cmp(big.NewRat(1, 1)) == 0)

	// 需要展示时再转 float,误差只发生在展示边界
	price, _ := new(big.Rat).Mul(third, big.NewRat(9999, 1)).Float64()
	fmt.Printf("float of 9999/3: %.2f\n", price)
}

How the snippet works

Structurally, expect the function main and nothing else.

What to watch for

  • The environment needs no preparation beyond having the interpreter or compiler.

Applying it

Look for the 1/3*3 =, float:, rat == 1: prefixes when the file runs; they tie each line to its step.

Statements that matter most here

price, _ := new(big.Rat).Mul(third, big.NewRat(9999, 1)).Float64()

Interactive Tools for This Topic

FAQ

What does Exact Ratios With big.Rat print when run?
Invoke the file as-is — the `1/3*3 =`, `float:`, `rat == 1:` prefixes identify which step printed each line.