Last active
January 18, 2020 19:43
-
-
Save MaxGraey/4fd05a4143010f117ca624b4b13d55b1 to your computer and use it in GitHub Desktop.
Rational approximation abs with MSE = ~1.6e-7
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const fj = [ 1, 0.01123596, 1, 0.19101124, 0.05617978, 0.39325843, 0.01123596, 0.59550562, 0.21348315] | |
const wj = [-0.232961,-0.1212703, -0.29214973,-0.12772172, 0.21085705, 0.6024462, 0.07024019, 0.3625982, -0.53436423] | |
const zj = [-1, -0.01123596, 1, 0.19101124, -0.05617978, -0.39325843, 0.01123596, 0.59550562, -0.21348315] | |
function approxAbs(x) { | |
const B0 = wj[0] / (x + 1 - 1e-15); | |
const B1 = wj[1] / (x - zj[1]); | |
const B2 = wj[2] / (x - 1 + 1e-15); | |
const B3 = wj[3] / (x - zj[3]); | |
const B4 = wj[4] / (x - zj[4]); | |
const B5 = wj[5] / (x - zj[5]); | |
const B6 = wj[6] / (x - zj[6]); | |
const B7 = wj[7] / (x - zj[7]); | |
const B8 = wj[8] / (x - zj[8]); | |
return ( | |
(B0 + fj[1] * B1 + B2 + fj[3] * B3 + fj[4] * B4 + fj[5] * B5 + fj[6] * B6 + fj[7] * B7 + fj[8] * B8) / | |
(B0 + B1 + B2 + B3 + B4 + B5 + B6 + B7 + B8) | |
); | |
} | |
console.log('~abs(+0.5) =', approxAbs(+0.5)); | |
console.log('~abs(-0.5) =', approxAbs(-0.5)); | |
console.log('~abs(+1.0) =', approxAbs(+1.0)); | |
console.log('~abs(-1.0) =', approxAbs(-1.0)); | |
console.log('~abs(+0.005) =', approxAbs(+0.005)); | |
console.log('~abs(-0.005) =', approxAbs(-0.005)); | |
const length = 1001; | |
const range = Array.from({ length }, (_,i) => 2 * i / (length - 1) - 1); // range = [-1..1] | |
console.log('MSE =', range.reduce((acc, v) => acc + (approxAbs(v) - Math.abs(v)) ** 2, 0) / (range.length - 1)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Result:
~abs(+0.5) = 0.5000962924973791
~abs(-0.5) = 0.49988571537395604
~abs(+1.0) = 0.9999999999999993
~abs(-1.0) = 1.000000000000001
~abs(+0.005) = 0.00726190332319611
~abs(-0.005) = 0.007353169539225273
MSE = 1.577348684371353e-7