• Post Reply Bookmark Topic Watch Topic
  • New Topic

Solving SquareRoot Problems  RSS feed

 
Saad Zahoor
Ranch Hand
Posts: 82
Android
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ???


 
Junilu Lacar
Sheriff
Posts: 11477
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Saad Zahoor
Ranch Hand
Posts: 82
Android
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks mate >>
 
Campbell Ritchie
Marshal
Posts: 56527
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Saad Zahoor
Ranch Hand
Posts: 82
Android
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
okay next time i will be careful . Sorry what you mean by code tag ??
 
Fred Kleinschmidt
Bartender
Posts: 571
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: 56527
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!