2021年11月10日(水) [長年日記]
■ [go] big.Rat
Goで有理数を扱えるbig.Ratを使ったのでちょっとメモ。Goのバージョンは1.17.3。
package main
import (
"fmt"
"math/big"
)
func printRat(r *big.Rat, text string) {
fmt.Println(text, r.FloatString(20), r.String())
}
func main() {
a := big.NewRat(-11, 10)
b := new(big.Rat).SetFloat64(-1.1)
c, _ := new(big.Rat).SetString("-1.1")
printRat(a, "NewRat(-11, 10) : ")
printRat(b, "SetFloat64(-1.1) : ")
printRat(c, `SetString("-1.1") : `)
}
NewRat(-11, 10) : -1.10000000000000000000 -11/10
SetFloat64(-1.1) : -1.10000000000000008882 -2476979795053773/2251799813685248
SetString("-1.1") : -1.10000000000000000000 -11/10
- SetFloat64() で値をセットすると誤差が入る可能性があることに注意。SetString() を使う場合は大丈夫そう。
- 値をコピーするときは Set() を使うようマニュアルに書かれている。
To "copy" a Rat value, an existing (or newly allocated) Rat must be set to a new value using the Rat.Set method; shallow copies of Rats are not supported and may lead to errors.
[ツッコミを入れる]
