Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Solving SquareRoot Problems

Ranch Hand
Posts: 83
This is the code i copied it .. i understand everything except for the line .>>>     double r1 = (-b + Math.pow(result , 0.5)) / (2.0 * a);
double r2 = (-b - Math.pow(result , 0.5)) / (2.0 * a);   >>>>  why we write 0.5 ... any logic ???

Sheriff
Posts: 11747
191
• 1
Math.pow(result, 0.5) is the same as Math.pow(result, 1.0/2.0) -- when the exponent is a fraction, you are essentially getting a root.  E.g. a power of 1/2 is the square root, a power of 1/3 is a cube root, and so on.

You can also use Math.sqrt(result) to get the same thing.

Ranch Hand
Posts: 83
Thanks mate >>

Marshal
Posts: 58411
178
Welcome to the Ranch

Please always tell us where such code comes from, to avoid copyright problems. It would appear that whoever wrote that code had forgotten about the sqrt method
I added code tags to your post; always use the tags. Doesn't it look better

Ranch Hand
Posts: 83
okay next time i will be careful . Sorry what you mean by code tag ??

Bartender
Posts: 600
9
• 1
Why would you use Math.pow(x,0.5) instead of Math.sqrt(x) to compute a square root? The latter is surely more efficient than the former.
Also why rely on the compiler to optimize the code to eliminate redundant calls? Isn't this easier to understand at a glance:

It is probably a nit for this simple code, but for much more complex code it can be useful to break out out common factors, especially those containing function calls, where the compiler might make redundant calls since the optimizer might not be able to determine whether there are any side effects of the call.

Campbell Ritchie
Marshal
Posts: 58411
178

Saad Zahoor wrote:okay next time i will be careful .

Please tell us where the code came from, as I requested (click on the underlined code).

Sorry what you mean by code tag ??

Click the underlined code and that shou‍ld explain it.