Advertisement
AmidamaruZXC

Untitled

Oct 25th, 2020
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.84 KB | None | 0 0
  1. package root.sqrt;
  2.  
  3.  
  4.  
  5. /**
  6.  
  7. * @author Victor Kuliamin
  8.  
  9. */
  10.  
  11. public class AdvSqrt extends Sqrt {
  12.  
  13.    private static double eps = 2.25e-16;
  14.  
  15.    private static long dgmask = 0x7FF0000000000000L;
  16.  
  17.    private static long mtmask = 0x000FFFFFFFFFFFFFL;
  18.  
  19.    private static int dgshift = 52;
  20.  
  21.    private static int sqdgadd = 0x1FF;
  22.  
  23.    private static double dnrbnd = Double.longBitsToDouble(0x0010000000000000L);
  24.  
  25.    private static long odddeg = 0x3FF0000000000000L;
  26.    private static long evndeg = 0x3FE0000000000000L;
  27.  
  28.  
  29.    public double sqrt(double x) {
  30.  
  31.        if (Double.isNaN(x) || x < 0) return Double.NaN;
  32.  
  33.        if (x == -0) return -0.0;
  34.  
  35.        else if (x == 0 || x == 1 || Double.isInfinite(x)) return x;
  36.  
  37.        else {
  38.  
  39.            boolean dnr = false;
  40.  
  41.            if (x < dnrbnd) {
  42.  
  43.                x = x * Math.pow(2, dgshift);
  44.  
  45.                dnr = true;
  46.  
  47.            }
  48.  
  49.  
  50.            long b = Double.doubleToLongBits(x);
  51.  
  52.            int d = (int) ((b & dgmask) >> dgshift);
  53.  
  54.            double res, tmp;
  55.  
  56.            int i = 0;
  57.  
  58.  
  59.            if ((d & 1) != 0)
  60.  
  61.                b = (b & mtmask) | odddeg;
  62.  
  63.            else
  64.  
  65.                b = (b & mtmask) | evndeg;
  66.  
  67.  
  68.            x = Double.longBitsToDouble(b);
  69.  
  70.            res = x;
  71.  
  72.  
  73.            while (Math.abs(x - res * res) / x > eps && i < 6) {
  74.  
  75.                i++;
  76.  
  77.                tmp = res;
  78.  
  79.                res = (tmp + x / tmp) / 2;
  80.  
  81.            }
  82.  
  83.            res = (res + x / res) / 2;
  84.  
  85.            b = Double.doubleToLongBits(res);
  86.  
  87.            d = (int) Math.ceil((double) d / 2) + sqdgadd;
  88.  
  89.            if (dnr) d -= dgshift / 2;
  90.  
  91.  
  92.            b = (b & mtmask) | ((long) d << dgshift);
  93.  
  94.            res = Double.longBitsToDouble(b);
  95.  
  96.            return res;
  97.  
  98.        }
  99.  
  100.    }
  101.  
  102. }
  103.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement