]> Cypherpunks repositories - gostls13.git/commitdiff
math/big: Add small complete example of big.Float usage
authorALTree <alb.donizetti@gmail.com>
Thu, 18 Jun 2015 15:22:25 +0000 (17:22 +0200)
committerRobert Griesemer <gri@golang.org>
Thu, 18 Jun 2015 21:08:41 +0000 (21:08 +0000)
Updates #11241

Change-Id: I573be85d0cfcf410f6125ecd2be8a3d292c40bbb
Reviewed-on: https://go-review.googlesource.com/11245
Reviewed-by: Robert Griesemer <gri@golang.org>
src/math/big/example_test.go

index 37b1bd090ad1179000db309aa69ca979af7fbffb..8cbd379b92810a16a20f6c04c43a10d8bebf6a5b 100644 (file)
@@ -7,6 +7,7 @@ package big_test
 import (
        "fmt"
        "log"
+       "math"
        "math/big"
 )
 
@@ -83,3 +84,49 @@ func Example_fibonacci() {
        // 1344719667586153181419716641724567886890850696275767987106294472017884974410332069524504824747437757
        // false
 }
+
+// This example shows how to use big.Float to compute the square root of 2 with
+// a precision of 200 bits, and how to print the result as a decimal number.
+func Example_sqrt2() {
+       // We'll do computations with 200 bits of precision in the mantissa.
+       const prec = 200
+
+       // Compute the square root of 2 using Newton's Method. We start with
+       // an initial estimate for sqrt(2), and then iterate:
+       //     x_{n+1} = 1/2 * ( x_n + (2.0 / x_n) )
+
+       // Since Newton's Method doubles the number of correct digits at each
+       // iteration, we need at least log_2(prec) steps.
+       steps := int(math.Log2(prec))
+
+       // Initialize values we need for the computation.
+       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)
+
+       // We use t as a temporary variable. There's no need to set its precision
+       // since big.Float values with unset (== 0) precision automatically assume
+       // the largest precision of the arguments when used as the result (receiver)
+       // of a big.Float operation.
+       t := new(big.Float)
+
+       // Iterate.
+       for i := 0; i <= 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
+       }
+
+       // We can use the usual fmt.Printf verbs since big.Float implements fmt.Formatter
+       fmt.Printf("sqrt(2) = %.50f\n", x)
+
+       // Print the error between 2 and x*x.
+       t.Mul(x, x) // t = x*x
+       fmt.Printf("error = %e\n", t.Sub(two, t))
+
+       // Output:
+       // sqrt(2) = 1.41421356237309504880168872420969807856967187537695
+       // error = 0.000000e+00
+}