]> Cypherpunks repositories - gostls13.git/commitdiff
math/big: add example for RoundingMode
authorKonstantin Shaposhnikov <k.shaposhnikov@gmail.com>
Mon, 7 Sep 2015 14:31:04 +0000 (22:31 +0800)
committerRobert Griesemer <gri@golang.org>
Thu, 10 Sep 2015 19:58:29 +0000 (19:58 +0000)
Updates #11241

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

index 358776e948721fd1a399cf0fe945b34856a50556..d135243b82e0e7f164ba5e07e48895d5fd9d65e0 100644 (file)
@@ -109,3 +109,34 @@ func ExampleFloat_Cmp() {
        // +Inf   1.2    1
        // +Inf  +Inf    0
 }
+
+func ExampleRoundingMode() {
+       operands := []float64{2.6, 2.5, 2.1, -2.1, -2.5, -2.6}
+
+       fmt.Printf("x   ")
+       for mode := big.ToNearestEven; mode <= big.ToPositiveInf; mode++ {
+               fmt.Printf(" %s", mode)
+       }
+       fmt.Println()
+
+       for _, f64 := range operands {
+               fmt.Printf("%4g", f64)
+               for mode := big.ToNearestEven; mode <= big.ToPositiveInf; mode++ {
+                       // sample operands above require 2 bits to represent mantissa
+                       // set binary precision to 2 to round them to integer values
+                       f := new(big.Float).SetPrec(2).SetMode(mode).SetFloat64(f64)
+                       format := fmt.Sprintf(" %%%dg", len(mode.String()))
+                       fmt.Printf(format, f)
+               }
+               fmt.Println()
+       }
+
+       // Output:
+       // x    ToNearestEven ToNearestAway ToZero AwayFromZero ToNegativeInf ToPositiveInf
+       //  2.6             3             3      2            3             2             3
+       //  2.5             2             3      2            3             2             3
+       //  2.1             2             2      2            3             2             3
+       // -2.1            -2            -2     -2           -3            -3            -2
+       // -2.5            -2            -3     -2           -3            -3            -2
+       // -2.6            -3            -3     -2           -3            -3            -2
+}