|
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ |
|
2 /* This Source Code Form is subject to the terms of the Mozilla Public |
|
3 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
5 |
|
6 //----------------------------------------------------------------------------- |
|
7 var BUGNUMBER = 363040; |
|
8 var summary = 'Array.prototype.reduce application in continued fraction'; |
|
9 var actual = ''; |
|
10 var expect = ''; |
|
11 |
|
12 |
|
13 //----------------------------------------------------------------------------- |
|
14 test(); |
|
15 //----------------------------------------------------------------------------- |
|
16 |
|
17 function test() |
|
18 { |
|
19 enterFunc ('test'); |
|
20 printBugNumber(BUGNUMBER); |
|
21 printStatus (summary); |
|
22 |
|
23 // Print x as a continued fraction in compact abbreviated notation and return |
|
24 // the convergent [n, d] such that x - (n / d) <= epsilon. |
|
25 function contfrac(x, epsilon) { |
|
26 let i = Math.floor(x); |
|
27 let a = [i]; |
|
28 x = x - i; |
|
29 let maxerr = x; |
|
30 while (maxerr > epsilon) { |
|
31 x = 1 / x; |
|
32 i = Math.floor(x); |
|
33 a.push(i); |
|
34 x = x - i; |
|
35 maxerr = x * maxerr / i; |
|
36 } |
|
37 print(uneval(a)); |
|
38 a.push([1, 0]); |
|
39 a.reverse(); |
|
40 return a.reduce(function (x, y) {return [x[0] * y + x[1], x[0]];}); |
|
41 } |
|
42 |
|
43 if (!Array.prototype.reduce) |
|
44 { |
|
45 print('Test skipped. Array.prototype.reduce not implemented'); |
|
46 } |
|
47 else |
|
48 { |
|
49 // Show contfrac in action. |
|
50 for each (num in [Math.PI, Math.sqrt(2), 1 / (Math.sqrt(Math.E) - 1)]) { |
|
51 print('Continued fractions for', num); |
|
52 for each (eps in [1e-2, 1e-3, 1e-5, 1e-7, 1e-10]) { |
|
53 let frac = contfrac(num, eps); |
|
54 let est = frac[0] / frac[1]; |
|
55 let err = num - est; |
|
56 print(uneval(frac), est, err); |
|
57 } |
|
58 print(); |
|
59 } |
|
60 } |
|
61 |
|
62 reportCompare(expect, actual, summary); |
|
63 |
|
64 exitFunc ('test'); |
|
65 } |