michael@0: /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: //----------------------------------------------------------------------------- michael@0: var BUGNUMBER = 363040; michael@0: var summary = 'Array.prototype.reduce application in continued fraction'; michael@0: var actual = ''; michael@0: var expect = ''; michael@0: michael@0: michael@0: //----------------------------------------------------------------------------- michael@0: test(); michael@0: //----------------------------------------------------------------------------- michael@0: michael@0: function test() michael@0: { michael@0: enterFunc ('test'); michael@0: printBugNumber(BUGNUMBER); michael@0: printStatus (summary); michael@0: michael@0: michael@0: // Print x as a continued fraction in compact abbreviated notation and return michael@0: // the convergent [n, d] such that x - (n / d) <= epsilon. michael@0: function contfrac(x, epsilon) { michael@0: let i = Math.floor(x); michael@0: let a = [i]; michael@0: x = x - i; michael@0: let maxerr = x; michael@0: while (maxerr > epsilon) { michael@0: x = 1 / x; michael@0: i = Math.floor(x); michael@0: a.push(i); michael@0: x = x - i; michael@0: maxerr = x * maxerr / i; michael@0: } michael@0: print(uneval(a)); michael@0: return a.reduceRight(function (x, y) {return [x[0] * y + x[1], x[0]];}, [1, 0]); michael@0: } michael@0: michael@0: if (!Array.prototype.reduceRight) michael@0: { michael@0: print('Test skipped. Array.prototype.reduceRight not implemented'); michael@0: } michael@0: else michael@0: { michael@0: // Show contfrac in action on some interesting numbers. michael@0: for each (num in [Math.PI, Math.sqrt(2), 1 / (Math.sqrt(Math.E) - 1)]) { michael@0: print('Continued fractions for', num); michael@0: for each (eps in [1e-2, 1e-3, 1e-5, 1e-7, 1e-10]) { michael@0: let frac = contfrac(num, eps); michael@0: let est = frac[0] / frac[1]; michael@0: let err = num - est; michael@0: print(uneval(frac), est, err); michael@0: } michael@0: print(); michael@0: } michael@0: } michael@0: michael@0: reportCompare(expect, actual, summary); michael@0: michael@0: exitFunc ('test'); michael@0: }