Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faster Alternative to Math.sqrt()

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.

like image 813
m-byte Avatar asked Jan 01 '17 09:01

m-byte


People also ask

Is math sqrt faster than Numpy sqrt?

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()”.

Why is sqrt so slow?

The square root function uses Newton's method to iteratively calculate the square root. It converges quadratically. Nothing will speed that up.

How can you calculate the square root of any number without using math sqrt ()?

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.


1 Answers

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 .

like image 122
jony89 Avatar answered Sep 23 '22 22:09

jony89