Are there any alternatives to using Math.sqrt()
to get the square root of an unknown value?
For example:
var random = (Math.random() * (999 - 1)) + 1;
var sqrt = Math.sqrt(random);
I've heard that using Math.sqrt()
to get the square root of a number is a very slow operation, I'm just wondering if there are any faster ways I can get the square root of a random number. Any help with this would be greatly appreciated.
It turns out that the sqrt() function from the standard Python math module is about seven times faster than the corresponding sqrt() function from numpy. As a side note, I learned that it is slightly faster (5-10%) to use the form “from math import sqrt” than it is to use “import math” and “math. sqrt()”.
The square root function uses Newton's method to iteratively calculate the square root. It converges quadratically. Nothing will speed that up.
Find the square of midvalue and compare it with n. If midvalue * midvalue = n, the midvalue is the square root of the given number. Compare the square of midvalue with n (up to n decimal places) if the difference is minor, the midvalue will be the square root of the number.
You can be sure that the fastest algorithm you will write your self is already implemented within Math.sqrt if not better .
There is an algorithm to go through the numbers till the middle (with some simply calculation) : Writing your own square root function
but as I said, it's probably implemented if not better.
You can try to look for some specific business/domain logic in order to reduce numbers range .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With