AmidamaruZXC

Untitled

Oct 25th, 2020
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.73 KB | None | 0 0
  1. package root.sqrt;
  2.  
  3. /**
  4.  * @author Victor Kuliamin
  5.  */
  6. public class AdvSqrt extends Sqrt {
  7.     private static double eps = 2.25e-16;
  8.     private static long dgmask = 0x7FF0000000000000L;
  9.     private static long mtmask = 0x000FFFFFFFFFFFFFL;
  10.     private static int dgshift = 52;
  11.     private static int sqdgadd = 0x1FF;
  12.     private static double dnrbnd = Double.longBitsToDouble(0x0010000000000000L);
  13.     private static long odddeg = 0x3FF0000000000000L;
  14.     private static long evndeg = 0x3FE0000000000000L;
  15.  
  16.     public double sqrt(double x) {
  17.         if (Double.isNaN(x) || x < 0) return Double.NaN;
  18.         if (x == -0) return -0.0;
  19.         else if (x == 0 || x == 1 || Double.isInfinite(x)) return x;
  20.         else {
  21.             boolean dnr = false;
  22.             if (x < dnrbnd) {
  23.                 x = x * Math.pow(2, dgshift);
  24.                 dnr = true;
  25.             }
  26.  
  27.             long b = Double.doubleToLongBits(x);
  28.             int d = (int) ((b & dgmask) >> dgshift);
  29.             double res, tmp;
  30.             int i = 0;
  31.  
  32.             if ((d & 1) != 0)
  33.                 b = (b & mtmask) | odddeg;
  34.             else
  35.                 b = (b & mtmask) | evndeg;
  36.  
  37.             x = Double.longBitsToDouble(b);
  38.             res = x;
  39.  
  40.             while (Math.abs(x - res * res) / x > eps && i < 6) {
  41.                 i++;
  42.                 tmp = res;
  43.                 res = (tmp + x / tmp) / 2;
  44.             }
  45.             res = (res + x / res) / 2;
  46.             b = Double.doubleToLongBits(res);
  47.             d = (int) Math.ceil((double) d / 2) + sqdgadd;
  48.             if (dnr) d -= dgshift / 2;
  49.  
  50.             b = (b & mtmask) | ((long) d << dgshift);
  51.             res = Double.longBitsToDouble(b);
  52.             return res;
  53.         }
  54.     }
  55.  
  56. }
Add Comment
Please, Sign In to add comment