JSFiddle - React, Tailwind, and code Playground
JavaScript
function inverse(f, delta = 0.1) {
function pickBoundaries(x, current) {
if (f(current) < x) return pickBoundaries(x, current * 2);
if (current === 1) return [0, 1];
return [current / 2, current];
}
function g(x, min, max) {
const point = (max + min) / 2;
const result = x - f(point);
if (result < 0) return g(x, min, point);
if (result > delta) return g(x, point, max);
return point;
}
return x => g(x, ...pickBoundaries(x, 1));
}
function test(f, x, inversedValue, eps = 0.1) {
const g = inverse(f, eps);
console.log(Math.abs(g(x) - inversedValue) <= eps);
}
test(x => x*10, 200, 20);
test(x => x*x, 169, 13);
test(x => x+20, 30, 10);