Commit a3677b5f authored by Russ Cox's avatar Russ Cox

math: handle exponent separately in Log2

This guarantees that powers of two return exact answers.

We could do a multiprecision approximation for the
rest of the answer too, but this seems like it should be
good enough.

Fixes #4567.

R=golang-dev, iant, remyoudompheng
CC=golang-dev
https://golang.org/cl/6943074
parent 708db790
...@@ -2281,6 +2281,13 @@ func TestLog2(t *testing.T) { ...@@ -2281,6 +2281,13 @@ func TestLog2(t *testing.T) {
t.Errorf("Log2(%g) = %g, want %g", vflogSC[i], f, logSC[i]) t.Errorf("Log2(%g) = %g, want %g", vflogSC[i], f, logSC[i])
} }
} }
for i := -1074; i <= 1023; i++ {
f := Ldexp(1, i)
l := Log2(f)
if l != float64(i) {
t.Errorf("Log2(2**%d) = %g, want %d", i, l, i)
}
}
} }
func TestModf(t *testing.T) { func TestModf(t *testing.T) {
......
...@@ -17,5 +17,6 @@ func log10(x float64) float64 { ...@@ -17,5 +17,6 @@ func log10(x float64) float64 {
func Log2(x float64) float64 func Log2(x float64) float64
func log2(x float64) float64 { func log2(x float64) float64 {
return Log(x) * (1 / Ln2) frac, exp := Frexp(x)
return Log(frac)*(1/Ln2) + float64(exp)
} }
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment