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.
Code
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
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.