Newton Method

PowerScript

A Classical root-finding method using derivative-based iterative approximation.

main 0 files
Newton Method..js
Newton Method..js 1287 bytes
var $ = {

    "params": {
        "target": 10,
        "x0": 1,
        "error": 1e-6,
        "dx": 1e-6,

        "iteration": 0,
        "maxIteration": 1000
    },

    "newtonMethod": function (func) {
        this.params.iteration = 0;
        var target = this.params.target;
        var error = this.params.error;
        var dx = this.params.dx;
        var x = this.params.x0;

        while (this.params.iteration < this.params.maxIteration) {
            this.params.iteration += 1;

            var y = func(x) - target;

            if (Math.abs(y) < error) {
                break;
            }

            var derivative = (func(x + dx) - func(x - dx)) / (2 * dx);

            if (Math.abs(derivative) < error) {
                break;
            }

            x = x - y / derivative;
        }

        this.params.x0 = x;

        return x;
    }
};

// Example Given

function testFunc(x) {
    return x*x ;
}

var result = $.newtonMethod(testFunc);

var target = $.params.target;
var estimate = testFunc(result);
var error = target - estimate;

print("result :" + result);
print("estimate :" + estimate);
print("target :" + target);
print("error :" + error);
print("iteration :" + $.params.iteration);
Comments (0)

No comments yet. Be the first to comment!

Snippet Information
Author: jungyu.lee
Language: PowerScript
Created: May 11, 2026
Updated: 0 minutes ago
Views: 2
Stars: 0