Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
121 changes: 121 additions & 0 deletions lib/node_modules/@stdlib/math/base/special/sqrt/scripts/precision.js
Original file line number Diff line number Diff line change
@@ -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<number>} 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();
Loading