Why math.sqrt returns a float to a decimal and not just the wo value the decimal point?

advertisements

I'm not sure if this question has been answered(couldn't find it when I did a google search). I saw http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html that the math class square root method returns a double. I experimented with it in eclipse with some ints that have whole square roots - 4, 9 and found that the square root with those always returned a floating point value with one decimal - 4.0, 9.0. I was curious as to why it even returned that extra decimal? I thought that ints could be considered as double values too. To me returning just 1 makes more sense cause you conserve more memory(i guess more memory is needed to store that extra decimal point) I even tested it out

public static double control(){
    return 1;
}

and saw it was valid to just return 1.


[I] found that [Math.sqrt(x) where x is a perfect square] always returned a floating point value with one decimal.

You are mistaking a particular printed representation of a double value with the value itself. A double does not have a decimal point. A double is a bit pattern that represents a particular real number (4 for example).

Decimal points only appear in a particuular decimal representation of real numbers. If I write "0.25", that obviously has a decimal point. If I write "1/4", there is no decimal point. But those are just two different representations of the same real number. So is the particular bit pattern that represents the double value returned by the Java expression, 1.0/4.0.

I don't know why Double.toString(4) returns the string, "4.0" instead of returning "4", but I'm guessing that somebody wanted to make it consistent with numeric literals in the Java language. When a "4" appears in your program, that's an int literal, and when "4.0" appears in your program, that's a double literal.