sandeshMC

CSM RMS

Apr 10th, 2016
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.18 KB | None | 0 0
  1.  
  2. import java.text.NumberFormat;
  3. import java.text.DecimalFormat;
  4.  
  5. public class NewtonRaphson {
  6.  
  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.  
  37.         i = 0;
  38.         while (Math.abs(xnew - xold) > DIFFERENCE) {
  39.             xold = xnew;
  40.             xnew = findXNew(xold);
  41.             i++;
  42.             System.out.println(this);
  43.         }
  44.     }
  45.  
  46.     public String toString() {
  47.         NumberFormat nf = NumberFormat.getInstance();
  48.         DecimalFormat df
  49.                 = (DecimalFormat) nf;
  50.         df.applyPattern("0.00000000");
  51.         return "The approximate value of the square root of " + x + " is "
  52.                 + xnew + "\n";
  53.  
  54.     }
  55. }
  56. import java.io.Console;
  57.  
  58.  
  59. import java.util.Scanner;
  60. public class Newton {
  61.  
  62.     public static void main(String[] args) {
  63.         Scanner reader = new Scanner(System.in);
  64.         System.out.println("Enter a number you would like to find the square root of");
  65.         int a = reader.nextInt();
  66.  
  67.         NewtonRaphson nr = new NewtonRaphson(5.0, a);
  68.  
  69.         nr.findSqRtA();
  70.  
  71.     }
  72. }
  73.  
  74. */
  75. OUTPUT :
  76. Enter a number you would like to find the square root of
  77. 5
  78. The approximate value of the square root of 5.0 is 2.3333333333333335
  79. The number of iterations is 1
  80. The approximate value of the square root of 5.0 is 2.238095238095238
  81. The number of iterations is 2
  82. The approximate value of the square root of 5.0 is 2.2360688956433634
  83. The number of iterations is 3
  84. The approximate value of the square root of 5.0 is 2.236067977499978
  85. The number of iterations is 4
  86.  
  87. Iteration completed, difference is less than 0.00005
  88. */
Add Comment
Please, Sign In to add comment