tubby
tubby

Reputation: 2144

Detect if a double is a perfect square in Java

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.

Upvotes: 1

Views: 878

Answers (2)

Michael Anderson
Michael Anderson

Reputation: 73530

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.

Upvotes: 1

S L
S L

Reputation: 14318

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.

Upvotes: 1

Related Questions