]> Cypherpunks repositories - gostls13.git/commitdiff
math: handle exponent separately in Log2
authorRuss Cox <rsc@golang.org>
Thu, 20 Dec 2012 17:23:27 +0000 (12:23 -0500)
committerRuss Cox <rsc@golang.org>
Thu, 20 Dec 2012 17:23:27 +0000 (12:23 -0500)
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

src/pkg/math/all_test.go
src/pkg/math/log10.go

index cdea8035f9ab33423c4566f8860005d4159c3edb..0d8b10f67fa0125aec765ae1378a610d67106cd5 100644 (file)
@@ -2281,6 +2281,13 @@ func TestLog2(t *testing.T) {
                        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) {
index 67c163a490dd806b44b9cf9af0fb24e03afdf650..95cfbf47ce9de2acf1b74013a94780f574b73ada 100644 (file)
@@ -17,5 +17,6 @@ func log10(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)
 }