diff options
| author | Rob Pike <r@golang.org> | 2009-06-09 09:53:44 -0700 |
|---|---|---|
| committer | Rob Pike <r@golang.org> | 2009-06-09 09:53:44 -0700 |
| commit | 7249ea4df2b4f12a4e7ed446f270cea87e4ffd34 (patch) | |
| tree | 7032a11d0cac2ae4d3e90f7a189b575b5a50f848 /src/pkg/math/sqrt.go | |
| parent | acf6ef7a82b3fe61516a1bac4563706552bdf078 (diff) | |
| download | golang-7249ea4df2b4f12a4e7ed446f270cea87e4ffd34.tar.gz | |
mv src/lib to src/pkg
tests: all.bash passes, gobuild still works, godoc still works.
R=rsc
OCL=30096
CL=30102
Diffstat (limited to 'src/pkg/math/sqrt.go')
| -rw-r--r-- | src/pkg/math/sqrt.go | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/src/pkg/math/sqrt.go b/src/pkg/math/sqrt.go new file mode 100644 index 000000000..79384f648 --- /dev/null +++ b/src/pkg/math/sqrt.go @@ -0,0 +1,66 @@ +// Copyright 2009 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package math + +import "math" + +/* + * sqrt returns the square root of its floating + * point argument. Newton's method. + * + * calls frexp + */ + +// Sqrt returns the square root of x. +// +// Special cases are: +// Sqrt(+Inf) = +Inf +// Sqrt(0) = 0 +// Sqrt(x < 0) = NaN +func Sqrt(x float64) float64 { + if IsInf(x, 1) { + return x; + } + + if x <= 0 { + if x < 0 { + return NaN(); + } + return 0; + } + + y, exp := Frexp(x); + for y < 0.5 { + y = y*2; + exp = exp-1; + } + + if exp&1 != 0 { + y = y*2; + exp = exp-1; + } + temp := 0.5 * (1+y); + + for exp > 60 { + temp = temp * float64(1<<30); + exp = exp - 60; + } + for exp < -60 { + temp = temp / float64(1<<30); + exp = exp + 60; + } + if exp >= 0 { + exp = 1 << uint(exp/2); + temp = temp * float64(exp); + } else { + exp = 1 << uint(-exp/2); + temp = temp / float64(exp); + } + + for i:=0; i<=4; i++ { + temp = 0.5*(temp + x/temp); + } + return temp; +} |
