| 1 |
// Copyright 2015 The Go Authors. All rights reserved. |
| 2 |
// Use of this source code is governed by a BSD-style |
| 3 |
// license that can be found in the LICENSE file. |
| 4 |
|
| 5 |
package big_test |
| 6 |
|
| 7 |
import ( |
| 8 |
"fmt" |
| 9 |
"math/big" |
| 10 |
) |
| 11 |
|
| 12 |
// Use the classic continued fraction for e |
| 13 |
// e = [1; 0, 1, 1, 2, 1, 1, ... 2n, 1, 1, ...] |
| 14 |
// i.e., for the nth term, use |
| 15 |
// 1 if n mod 3 != 1 |
| 16 |
// (n-1)/3 * 2 if n mod 3 == 1 |
| 17 |
func recur(n, lim int64) *big.Rat { |
| 18 |
term := new(big.Rat) |
| 19 |
if n%3 != 1 { |
| 20 |
term.SetInt64(1) |
| 21 |
} else { |
| 22 |
term.SetInt64((n - 1) / 3 * 2) |
| 23 |
} |
| 24 |
|
| 25 |
if n > lim { |
| 26 |
return term |
| 27 |
} |
| 28 |
|
| 29 |
// Directly initialize frac as the fractional |
| 30 |
// inverse of the result of recur. |
| 31 |
frac := new(big.Rat).Inv(recur(n+1, lim)) |
| 32 |
|
| 33 |
return term.Add(term, frac) |
| 34 |
} |
| 35 |
|
| 36 |
// This example demonstrates how to use big.Rat to compute the |
| 37 |
// first 15 terms in the sequence of rational convergents for |
| 38 |
// the constant e (base of natural logarithm). |
| 39 |
func Example_eConvergents() { |
| 40 |
for i := 1; i <= 15; i++ { |
| 41 |
r := recur(0, int64(i)) |
| 42 |
|
| 43 |
// Print r both as a fraction and as a floating-point number. |
| 44 |
// Since big.Rat implements fmt.Formatter, we can use %-13s to |
| 45 |
// get a left-aligned string representation of the fraction. |
| 46 |
fmt.Printf("%-13s = %s\n", r, r.FloatString(8)) |
| 47 |
} |
| 48 |
|
| 49 |
// Output: |
| 50 |
// 2/1 = 2.00000000 |
| 51 |
// 3/1 = 3.00000000 |
| 52 |
// 8/3 = 2.66666667 |
| 53 |
// 11/4 = 2.75000000 |
| 54 |
// 19/7 = 2.71428571 |
| 55 |
// 87/32 = 2.71875000 |
| 56 |
// 106/39 = 2.71794872 |
| 57 |
// 193/71 = 2.71830986 |
| 58 |
// 1264/465 = 2.71827957 |
| 59 |
// 1457/536 = 2.71828358 |
| 60 |
// 2721/1001 = 2.71828172 |
| 61 |
// 23225/8544 = 2.71828184 |
| 62 |
// 25946/9545 = 2.71828182 |
| 63 |
// 49171/18089 = 2.71828183 |
| 64 |
// 517656/190435 = 2.71828183 |
| 65 |
} |