Alberto Donizetti uploaded a change:
https://go-review.googlesource.com/11245
math/big: Add small complete example of big.Float usage
Updates #11241
Change-Id: I573be85d0cfcf410f6125ecd2be8a3d292c40bbb
---
M src/math/big/example_test.go
1 file changed, 45 insertions(+), 0 deletions(-)
diff --git a/src/math/big/example_test.go b/src/math/big/example_test.go
index 37b1bd0..4fa4fa4 100644
--- a/src/math/big/example_test.go
+++ b/src/math/big/example_test.go
@@ -7,6 +7,7 @@
import (
"fmt"
"log"
+ "math"
"math/big"
)
@@ -83,3 +84,47 @@
//
1344719667586153181419716641724567886890850696275767987106294472017884974410332069524504824747437757
// false
}
+
+// Example_sqrt2 shows how to use big.Float to compute the square root of
2 with
+// a precision of 200 binary digits, and print it as a decimal number.
+func Example_sqrt2() {
+ // we'll do computations with 200 binary digits of precision in the
mantissa
+ prec := uint(200)
+
+ // Compute the square root of 2 using Newton's Method. We start with
+ // an initial guess for sqrt(2), and then iterate:
+ // x_{n+1} = 1/2 * ( x_n + (2.0 / x_n) )
+
+ // we need at least log_2(prec) iterations
+ steps := math.Log2(float64(prec))
+
+ // initialize Floats with precision prec from int64 and float64 values
+ two := new(big.Float).SetPrec(prec).SetInt64(2)
+ half := new(big.Float).SetPrec(prec).SetFloat64(0.5)
+
+ // use 1 as the initial estimate
+ x := new(big.Float).SetPrec(prec).SetInt64(1)
+
+ t := new(big.Float)
+
+ // Newton's Method iterations
+ for i := 0; i <= int(steps); i++ {
+ t.Quo(two, x) // t = 2.0 / x_n
+ t.Add(x, t) // t = x_n + (2.0 / x_n)
+ x.Mul(half, t) // x_{n+1} = 0.5 * t
+ }
+
+ // Use Text to convert the Float to a String and print it.
+ // 'f' formats the Float as a decimal number, no exponent.
+ // The precision parameter controls the number of digits after the
decimal point.
+ // 200 binary digits of mantissa are enough to give us at least 50
correct decimal digits.
+ fmt.Println(x.Text('f', 50))
+
+ // verify that x * x = 2
+ z := new(big.Float).Mul(x, x)
+ fmt.Println(two.Cmp(z) == 0)
+
+ // Output:
+ // 1.41421356237309504880168872420969807856967187537695
+ // true
+}
--
https://go-review.googlesource.com/11245