2

so I've got some fairly large numbers to work with, and I need a way to calculate the square root of a given "long".

I cannot use Math.sqrt(x) as it is only for doubles

JHelpPlz
  • 21
  • 1
  • 2
  • 3
    Hmm. So you are worried about the loss of precision? How significant would that be? – Thilo Mar 15 '16 at 04:13
  • 2
    Did you try using `Math.sqrt(x)`? What happened? – ajb Mar 15 '16 at 04:15
  • Related (about BigInteger): http://stackoverflow.com/questions/4407839/how-can-i-find-the-square-root-of-a-java-biginteger – Thilo Mar 15 '16 at 04:15
  • 2
    I suppose you could use the [Babylonian method](https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) and calculate it yourself. – Elliott Frisch Mar 15 '16 at 04:15
  • 3
    Over here, they say that the loss of precision is insignificant: http://stackoverflow.com/a/18501209/14955 – Thilo Mar 15 '16 at 04:16
  • Hello, use this Math.sqrt((double)x); – Avanish Kumar Mar 15 '16 at 04:38
  • Use binary search. – MrGreen Mar 15 '16 at 07:32
  • you can use mine [sqrt by binary search without multiplication in C++](http://stackoverflow.com/a/34657972/2521214) just change the variable names, iterations count and LUT to your `bitcount/2` – Spektre Mar 15 '16 at 07:41
  • @AvanishKumar the cast is unnecessary. And the problem here is `long` has far more precision than `double` (64 vs 53). Some adjustment is needed to get the correct result as in Thilo's link – phuclv Apr 07 '16 at 05:53

2 Answers2

0

You can extract one bit at a time, as demonstrated withthis C program: http://www.realitypixels.com/turk/opensource/index.html#FractSqrt This assumes that you have a fixed-point number with 30 fractional bits. If you have 0 fractional bits, then a 2N bit number would have an N bit square root, achieved by setting count to 15.

Reality Pixels
  • 346
  • 2
  • 6
-4

go cast it:

Math.sqrt((double)x)
Floern
  • 31,495
  • 23
  • 98
  • 115
Jacob
  • 15
  • 4
  • 1
    You don't need a cast. Java will cast `long` to `double` without being told to. – ajb Mar 15 '16 at 04:39