Skip to content

math/big: Float.Rat() does not return the same number as Float.String() #66209

@tux21b

Description

@tux21b

Go version

go version go1.22.0 windows/amd64

Output of go env in your module/workspace:

set GO111MODULE=on
set GOARCH=amd64
set GOBIN=
set GOCACHE=C:\Users\Christoph\AppData\Local\go-build
set GOENV=C:\Users\Christoph\AppData\Roaming\go\env
set GOEXE=.exe
set GOEXPERIMENT=
set GOFLAGS=
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOINSECURE=
set GOMODCACHE=C:\Users\Christoph\go\pkg\mod
set GONOPROXY=
set GONOSUMDB=
set GOOS=windows
set GOPATH=C:\Users\Christoph\go
set GOPRIVATE=
set GOPROXY=https://proxy.golang.org,direct
set GOROOT=C:/Users/Christoph/go/pkg/mod/golang.org/toolchain@v0.0.1-go1.22.0.windows-amd64
set GOSUMDB=sum.golang.org
set GOTMPDIR=
set GOTOOLCHAIN=auto
set GOTOOLDIR=C:\Users\Christoph\go\pkg\mod\golang.org\toolchain@v0.0.1-go1.22.0.windows-amd64\pkg\tool\windows_amd64
set GOVCS=
set GOVERSION=go1.22.0
set GCCGO=gccgo
set GOAMD64=v1
set AR=ar
set CC=gcc
set CXX=g++
set CGO_ENABLED=0
set GOMOD=NUL
set GOWORK=
set CGO_CFLAGS=-O2 -g
set CGO_CPPFLAGS=
set CGO_CXXFLAGS=-O2 -g
set CGO_FFLAGS=-O2 -g
set CGO_LDFLAGS=-O2 -g
set PKG_CONFIG=pkg-config
set GOGCCFLAGS=-m64 -fno-caret-diagnostics -Qunused-arguments -Wl,--no-gc-s
ections -fmessage-length=0 -ffile-prefix-map=C:\Users\CHRIST~1\AppData\Local\Temp\go-build3241685064=/tmp/go-build -gno-record-gcc-switches

What did you do?

func TestBug1(t *testing.T) {
	f, ok := new(big.Float).SetString("0.025")
	require.True(t, ok)
	require.Equal(t, "0.025", f.String())

	r, exact := f.Rat(nil)
	require.Equal(t, big.Exact, exact)
	require.Equal(t, "1/40", r.String()) // fails with: 14757395258967641293/590295810358705651712
}

func TestBug2(t *testing.T) {
	f := new(big.Float).SetPrec(53).SetMode(big.ToNearestEven).SetFloat64(0.025)
	require.Equal(t, "0.025", f.String())

	r, exact := f.Rat(nil)
	require.Equal(t, big.Exact, exact)
	require.Equal(t, "1/40", r.String()) // fails with: 3602879701896397/144115188075855872
}

playground: https://go.dev/play/p/2xDuiRHMJgn

What did you see happen?

A big.Float with the value "0.025" returns a rational number of 14757395258967641293/590295810358705651712 or 3602879701896397/144115188075855872

What did you expect to see?

I expected that a big.Float with the value of "0.025" (according to its precision and rounding mode) to have a rational number representation of "1/40".

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeNeedsDecisionFeedback is required from experts, contributors, and/or the community before a change can be made.

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions