-
Notifications
You must be signed in to change notification settings - Fork 1
/
NewtonRaphson.java
66 lines (55 loc) · 1.53 KB
/
NewtonRaphson.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Muhammad Naveed.
// https://twitter.com/prog_naveed/
// Finding the square root using newton raphson method.
import java.util.Scanner;
public class NewtonRaphson
{
private int number;
private float[] root;
private int initialGuess;
// Default constructor for initialising variables.
public NewtonRaphson()
{
initialGuess = 1;
number = 0;
root = new float[100];
}
// setter method
public void setNumber(int number)
{
this.number = number;
}
// square root finder method
public void calculateRoot()
{
root[0] = initialGuess;
for (int i = 0; i < root.length; i++)
{
// newton raphson algorithm.
root[i + 1] = (float) (0.5) * (root[i] + (number / root[i]));
if (root[i] == root[i + 1])
{
showResults(root[i], i);
break;
}
else
{
continue;
}
}
}
// Result showing constant method.
public final void showResults(float result, int i)
{
System.out.println("The square root of " + number + " is " + result + " and found in " + i + "th iteration.");
}
public static void main(String[] args)
{
var NewtonRaphson_obj = new NewtonRaphson();
var s = new Scanner(System.in);
System.out.print("Enter the number : ");
NewtonRaphson_obj.setNumber(s.nextInt());
s.close();
NewtonRaphson_obj.calculateRoot();
}
}