1

I want to detect if a double, like 6.25 is a perfect square or not.

To detect perfect squares for those numbers whose square root is an integer, I would do something like

public boolean isPerfectDouble( double i )
    {
        if (Double.isInfinite(i)) {
            return false;
        }
        double sqrt = Math.sqrt(i);
        return sqrt == Math.floor(sqrt) && sqrt*sqrt == i;
    }

However, this would not work for numbers like 6.25, which is indeed a perfect square.

tubby
  • 2,074
  • 3
  • 33
  • 55
  • 2
    What is a "perfect square" in terms of decimal fractions? A square of a finite decimal fraction? In binary? Note that in floating point numbers, `0.1*0.1` results in `0.010000000000000002` as `0.1` can not be exactly represented. – Lutz Lehmann Jun 25 '17 at 19:05

2 Answers2

1

First of all, you would need exact representation of such numbers. Probably you would want to truncate after certain decimal places. Then multiply the number by integer power of 100 until you get an integer. Check it the integer is square or not.

S L
  • 14,262
  • 17
  • 77
  • 116
1

I'm going to interpret your assertion that 6.25 is a perfect square because it is the square of a rational number (numbers of the form p/q where p and q are both integer numbers).

This differs from Santosh Linkhas solution where a perfect square is take to be a square of an integer times a negative power of 10.

The key difference is that I would consider 1/9 = 0.111111... to be a perfect square since it is 1/3 = 0.33333... squared.

The interesting part of this problem is that all doubles are rationals, but not all rationals are expressible as doubles.

What I suggest is the following: Find out if there is a good rational approximation to the square-root of the value - Algorithm for simplifying decimal to fractions is a really good starting point.

Michael Anderson
  • 70,661
  • 7
  • 134
  • 187