diff --git a/lib/node_modules/@stdlib/math/base/special/sqrt/scripts/precision.js b/lib/node_modules/@stdlib/math/base/special/sqrt/scripts/precision.js new file mode 100644 index 000000000000..fa9625335a47 --- /dev/null +++ b/lib/node_modules/@stdlib/math/base/special/sqrt/scripts/precision.js @@ -0,0 +1,121 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2018 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + + +'use strict'; + +// MODULES // + +var log = require( '@stdlib/console/log' ); +var abs = require( '@stdlib/math/base/special/abs' ); +var sqrt = require( './../lib' ); + + +// FUNCTIONS // + +/** +* Computes a rough square root approximation using a small fixed number of Newton iterations. +* +* @private +* @param {number} x - input value +* @returns {number} approximate square root +*/ +function approxSqrt( x ) { + var guess; + var i; + + if ( x < 0.0 ) { + return NaN; + } + if ( x === 0.0 ) { + return 0.0; + } + guess = ( x > 1.0 ) ? x / 2.0 : 1.0; + for ( i = 0; i < 5; i++ ) { + guess = 0.5 * ( guess + ( x / guess ) ); + } + return guess; +} + +/** +* Computes the arithmetic mean. +* +* @private +* @param {Array} values - input array +* @returns {number} mean value +*/ +function mean( values ) { + var sum; + var i; + + if ( values.length === 0 ) { + return NaN; + } + sum = 0.0; + for ( i = 0; i < values.length; i++ ) { + sum += values[ i ]; + } + return sum / values.length; +} + +/** +* Computes the relative error between two numbers. +* +* @private +* @param {number} value - computed value +* @param {number} expected - reference value +* @returns {number} relative error +*/ +function relativeError( value, expected ) { + var denom = ( expected === 0.0 ) ? 1e-16 : expected; + return abs( ( value - expected ) / denom ); +} + + +// MAIN // + +/** +* Evaluate the mean relative error between a simple Newton approximation and `@stdlib`'s sqrt implementation. +* +* @private +*/ +function main() { + var approx; + var errors; + var expected; + var values; + var i; + + values = [ + 0.5, + 1.5, + 2.5, + 10.0, + 25.0, + 100.0 + ]; + errors = []; + for ( i = 0; i < values.length; i++ ) { + expected = sqrt( values[ i ] ); + approx = approxSqrt( values[ i ] ); + errors.push( relativeError( approx, expected ) ); + } + log( 'Mean relative error (approx vs @stdlib sqrt): %d', mean( errors ) ); +} + +main();