Advertisement
Guest User

Untitled

a guest
Aug 26th, 2016
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.23 KB | None | 0 0
  1. package test;
  2.  
  3. import java.text.NumberFormat;
  4. import java.text.DecimalFormat;
  5.  
  6. public class NewtonRaphson {
  7.     static final double DIFFERENCE = 0.00005;
  8.     double n;
  9.     double x;
  10.     double derivative;
  11.     double function;
  12.     double xold;
  13.     double xnew;
  14.     int i;
  15.  
  16.     public NewtonRaphson(double n2, int x2) {
  17.         n=n2;
  18.         x=x2;
  19.         function = Math.pow(n, 2)-x;
  20.         derivative = 2*n;
  21.         xnew=n-function/derivative;
  22.         xold=0;
  23.     }
  24.  
  25.     boolean positive() {
  26.         return (n >= 0);
  27.     }
  28.  
  29.     public double findXNew(double xold2) {
  30.         function = Math.pow(xold2, 2)-x;
  31.         derivative = 2*xold2;
  32.         return xold2-function/derivative;
  33.     }
  34.  
  35.     public void findSqRtA() {
  36.         i=0;
  37.         while(Math.abs(xnew-xold)> DIFFERENCE) {
  38.             xold=xnew;
  39.             xnew=findXNew(xold);
  40.             i++;
  41.             System.out.println(this);
  42.         }
  43.         System.out.println("\nIteration completed, difference is less than 0.00005");
  44.     }
  45.  
  46.     public String toString() {
  47.         NumberFormat nf = NumberFormat.getInstance(); DecimalFormat df = (DecimalFormat)nf;
  48.         df.applyPattern("0.00000000");
  49.  
  50.         return "The approximate value of the square root of "+x+" is " + xnew + "\n" +
  51.  
  52.         "The number of iterations is " + i;
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement