Skip to content

Commit 894aec2

Browse files
committed
[JavaScript] Simple implementation of Newton-Raphson method
1 parent 04b9b57 commit 894aec2

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

JavaScript/newton.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
// Simple Newton-Raphson solution of the equation v(t) = 100/3.6 where v(t) = 54.15*tanh(0.1813*t)
2+
3+
function Newton(f, x0, h, eps) {
4+
function dfdt(f, x, h) {
5+
return (f(x+h) - f(x-h))/(2.0*h);
6+
};
7+
8+
let i = 0;
9+
x_n = x0;
10+
x_old = x0;
11+
12+
while (true) {
13+
df = dfdt(f, x_n, h);
14+
x_old = x_n;
15+
x_n = x_n - f(x_n)/df;
16+
if (Math.abs(x_n - x_old) < eps) {
17+
return {
18+
x: x_n,
19+
iterations: i+1
20+
};
21+
}
22+
if (i > 10) {
23+
return undefined;
24+
}
25+
i++;
26+
}
27+
}
28+
29+
function f(t) {
30+
return 54.16*Math.tanh(0.1813*t) - 100/3.6;
31+
}
32+
33+
const solution = Newton(f, 2, 0.001, 0.001);
34+
35+
console.log(`t = ${solution.x} in ${solution.iterations} iterations`);

0 commit comments

Comments
 (0)