Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.text.NumberFormat;
- import java.text.DecimalFormat;
- public class NewtonRaphson {
- static final double DIFFERENCE = 0.00005;
- double n;
- double x;
- double derivative;
- double function;
- double xold;
- double xnew;
- int i;
- public NewtonRaphson(double n2, int x2) {
- n = n2;
- x = x2;
- function = Math.pow(n, 2) - x;
- derivative = 2 * n;
- xnew = n - function / derivative;
- xold = 0;
- }
- boolean positive() {
- return (n >= 0);
- }
- public double findXNew(double xold2) {
- function = Math.pow(xold2, 2) - x;
- derivative = 2 * xold2;
- return xold2 - function / derivative;
- }
- public void findSqRtA() {
- i = 0;
- while (Math.abs(xnew - xold) > DIFFERENCE) {
- xold = xnew;
- xnew = findXNew(xold);
- i++;
- System.out.println(this);
- }
- }
- public String toString() {
- NumberFormat nf = NumberFormat.getInstance();
- DecimalFormat df
- = (DecimalFormat) nf;
- df.applyPattern("0.00000000");
- return "The approximate value of the square root of " + x + " is "
- + xnew + "\n";
- }
- }
- import java.io.Console;
- import java.util.Scanner;
- public class Newton {
- public static void main(String[] args) {
- Scanner reader = new Scanner(System.in);
- System.out.println("Enter a number you would like to find the square root of");
- int a = reader.nextInt();
- NewtonRaphson nr = new NewtonRaphson(5.0, a);
- nr.findSqRtA();
- }
- }
- */
- OUTPUT :
- Enter a number you would like to find the square root of
- 5
- The approximate value of the square root of 5.0 is 2.3333333333333335
- The number of iterations is 1
- The approximate value of the square root of 5.0 is 2.238095238095238
- The number of iterations is 2
- The approximate value of the square root of 5.0 is 2.2360688956433634
- The number of iterations is 3
- The approximate value of the square root of 5.0 is 2.236067977499978
- The number of iterations is 4
- Iteration completed, difference is less than 0.00005
- */
Add Comment
Please, Sign In to add comment