UNPKG

psychart

Version:

View air conditions on a psychrometric chart

41 lines (40 loc) 1.22 kB
import * as SMath from 'smath'; /** * Find the solution (zero) of a function. */ export function zero(func, left, right, epsilon = 1e-6, maxIterations = 1e6) { for (let i = 0; i < maxIterations; i++) { const funcLeft = func(left); const funcRight = func(right); if (Number.isNaN(funcLeft)) { throw new Error(`f(${left}) is NaN`); } if (Number.isNaN(funcRight)) { throw new Error(`f(${right}) is NaN`); } const leftSign = Math.sign(funcLeft); const rightSign = Math.sign(funcRight); if (SMath.approx(funcLeft, 0, epsilon)) { return left; } if (SMath.approx(funcRight, 0, epsilon)) { return right; } if (leftSign === rightSign) { throw new Error('A solution cannot be found.'); } const mid = (left + right) / 2; const funcMid = func(mid); const midSign = Math.sign(funcMid); if (SMath.approx(funcMid, 0, epsilon)) { return mid; } if (midSign === leftSign) { left = mid; } else { right = mid; } } return (left + right) / 2; }