posted 1 year ago

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 ???

double r2 = (-b - Math.pow(result , 0.5)) / (2.0 * a); >>>> why we write 0.5 ... any logic ???

I am Noob Looking for Experts for their suggestion and Ideas

posted 1 year ago

- 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.

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

*Practice only makes habit, only perfect practice makes perfect.
Practice mindfully by doing the right things and doing things right.*— Junilu

[How to Ask Questions] [How to Answer Questions]

posted 1 year ago

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

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

posted 1 year ago

- 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.

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.