Skip to content

Commit c500e8a

Browse files
Add Newton Raphson method (TheAlgorithms#3224)
1 parent 2ffcff1 commit c500e8a

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.thealgorithms.maths;
2+
3+
import java.util.Scanner;
4+
5+
/*
6+
*To learn about the method, visit the link below :
7+
* https://en.wikipedia.org/wiki/Newton%27s_method
8+
*
9+
* To obtain the square root, no built-in functions should be used
10+
*
11+
* The formula to calculate the root is : root = 0.5(x + n/x),
12+
* here, n is the no. whose square root has to be calculated and
13+
* x has to be guessed such that, the calculation should result into
14+
* the square root of n.
15+
* And the root will be obtained when the error < 0.5 or the precision value can also
16+
* be changed according to the user preference.
17+
*/
18+
19+
public class SquareRootWithNewtonRaphsonMethod {
20+
21+
public static double squareRoot (int n) {
22+
23+
double x = n; //initially taking a guess that x = n.
24+
double root = 0.5 * (x + n/x); //applying Newton-Raphson Method.
25+
26+
while (Math.abs(root - x) > 0.0000001) { //root - x = error and error < 0.0000001, 0.0000001 is the precision value taken over here.
27+
28+
x = root; //decreasing the value of x to root, i.e. decreasing the guess.
29+
root = 0.5 * (x + n/x);
30+
}
31+
32+
return root;
33+
}
34+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.thealgorithms.maths;
2+
3+
4+
import org.junit.jupiter.api.Assertions;
5+
import org.junit.jupiter.api.Test;
6+
7+
public class SquareRootWithNewtonRaphsonTestMethod
8+
{
9+
@Test
10+
void testfor1(){
11+
Assertions.assertEquals(1,SquareRootWithNewtonRaphsonMethod.squareRoot(1));
12+
}
13+
14+
@Test
15+
void testfor2(){
16+
Assertions.assertEquals(1.414213562373095,SquareRootWithNewtonRaphsonMethod.squareRoot(2));
17+
}
18+
19+
@Test
20+
void testfor625(){
21+
Assertions.assertEquals(25.0,SquareRootWithNewtonRaphsonMethod.squareRoot(625));
22+
}
23+
}

0 commit comments

Comments
 (0)