UNPKG

@polkassembly/util

Version:

Set of utility functions for Polkassembly and more.

54 lines (53 loc) 2.59 kB
"use strict"; // Copyright 2019-2020 @paritytech/polkassembly authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); // forked from https://github.com/scijs/newton-raphson-method var bn_js_1 = __importDefault(require("bn.js")); /** * @name newtonRaphson * @summary Returns the root of a polynomial function of degree 3 using the Newton Raphson algorithm. * @param f function that taxes x as parameter and returns the polynomial function of degree 3. * @param fp the derivative of f * @param x0 the starting point of the iteration. * @param options optional options to specify the `tolerance`, `epsilon`, macIterations` or `verbose`. **/ function newtonRaphson(f, fp, x0, options) { var x1, y, yp, tol, maxIter, iter, verbose, eps; tol = (options === null || options === void 0 ? void 0 : options.tolerance) === undefined ? new bn_js_1.default(1e-7) : options.tolerance; eps = (options === null || options === void 0 ? void 0 : options.epsilon) === undefined ? new bn_js_1.default(2.220446049250313e-16) : options.epsilon; maxIter = (options === null || options === void 0 ? void 0 : options.maxIterations) === undefined ? 20 : options.maxIterations; verbose = (options === null || options === void 0 ? void 0 : options.verbose) === undefined ? false : options.verbose; iter = 0; while (iter++ < maxIter) { // Compute the value of the function: y = f(x0); yp = fp(x0); if (yp.abs().lte(eps.mul(y.abs()))) { if (verbose) { console.log('Newton-Raphson: failed to converged due to nearly zero first derivative'); } return { foundRoot: false }; } // Update the guess: x1 = x0.sub(y.div(yp)); // Check for convergence: if (x1.sub(x0).abs().lte(tol.mul(x1.abs()))) { if (verbose) { console.log('Newton-Raphson: converged to x = ' + x1.toString() + ' after ' + iter + ' iterations'); } return { foundRoot: true, result: x1 }; } // Transfer update to the new guess: x0 = x1; } if (verbose) { console.log('Newton-Raphson: Maximum iterations reached (' + maxIter + ')'); } return { foundRoot: false }; } exports.newtonRaphson = newtonRaphson;