adam-hanna / goal-seek

goal-seek is a javascript library that can be used to solve for the value of an independent variable: "x"; of a function: "f(x)"; such that f(x) equals some defined goal. In other words: do you know the desired output of a function but not the input to yield such an output? If so, then use this goal seek!
MIT License
36 stars 13 forks source link

Convergence error for simple cases. #13

Open mcanyucel opened 2 years ago

mcanyucel commented 2 years ago

Thank you for your work on this free library.. I was doing some tests before implementing it to my project, and I kept getting convergence error for simple quadratic functions. For example, the code below finds the root 10 as expected:

        let x = 20;
        const fn = (x: number): number => Math.pow(x, 2);
        const fnParams = [x];

        try {
            const result = goalSeek({
                fn,
                fnParams,
                percentTolerance: 0.01,
                maxIterations: 1000,
                maxStep: 10,
                goal: 100,
                independentVariableIdx: 0
            });
            console.log("====root: " + result);
            console.log("====fn value: " + fn(result));

        } catch (e) {
            console.log("----" + e.message);

        }

But if I change the goal to 130, I get failed to converge error:

...
    goal: 130,
...

Any ideas or tips for quadratic or higher order polynomials?

adam-hanna commented 2 years ago

Interesting. It gets stuck in an infinite loop between -40 and 250.

EDIT - Decreasing the maxStep and increasing the maxIterations seems to solve it. Maybe the algo could be improved to account for that?

mcanyucel commented 2 years ago

Indeed, setting maxStep to 0.1 solves with the default maxIterations for goal 130 or similar numbers for x^2. Maybe quadratic functions are more susceptible to bouncing back and forth for large steps due to their higher order terms? I am really not that fluent in numerical analysis stuff to offer a lot of help or insight, though :). Possibly decreasing the step size automatically if the result gets stuck bouncing (yeah, that was not a very technical sentence) might help.

rohit-rai-0101rm commented 2 years ago

I am working with react and have a result table. i want to set element of last cell 0 . please guide on the same