the implementation of math.sqrt could take advantage of anything specific
to **0.5, ,while **0.x would have to be a generalist library. a compiler
optimization could be used, but there would be the SLIGHT overhead of
figuring out if the optimization could be used. if the optimizer even does
it.
a simple test of
> #!/usr/bin/python
>
> import random
> from math import sqrt
>
> randomlist = []
>
> for i in range(0,1000000):
> n = random.randint(1,2**16)
> randomlist.append(n)
>
> newlist = [sqrt(x) for x in randomlist]
>
i see execution time lower than the equivalent of
#!/usr/bin/python
>
> import random
>
> randomlist = []
>
> for i in range(0,1000000):
> n = random.randint(1,2**16)
> randomlist.append(n)
>
> def sqrt(x):
> return x**0.5
>
> newlist = [sqrt(x) for x in randomlist]
>
not by a huge amount, but around .66s as opposed to .73s or so.
Granted, i'm doing far more work than just doing the sqrt, but remove the
sqrt step entirely and execution time are around .63s. So it seems quite a
bit faster.
Anyway, it comes down to there being faster tricks to specific sqrt, while
a generalist library would at BEST have to make a decision to use a trick
and then use it. Since compiling didn't speed anything up, I'm guessing
no. There are even hardware functions that i don't believe python uses (?)
but might not have the properties the language desires.
Totally unrelated, if you want to see how insane people get with this kind
of thing.
https://en.wikipedia.org/wiki/Fast_inverse_square_root
On Thu, Apr 27, 2023 at 1:07 PM trent shipley via PLUG-discuss <
plug-discuss@lists.phxlinux.org> wrote:
> I'm on the bench at work, so I spend my days following along with examples
> in Python books. Whenever there is a choice to use x**0.5 or math.sqrt(x)
> the books opt for the square root option instead of the equivalent
> representation as a fractional power. Is the implementation of math.sqrt()
> more efficient than x**0.5? Is there a numerical shortcut to the value of
> sqrt(x) that will make the sqrt symbol more efficient than the power
> equivalent (x^0.5) in every programming language?
>
> I have a math degree, and sometimes it is irksome since x**(1/2) or
> x^(1/2) is symbolically more elegant in the formula.
>
>
> ---------------------------------------------------
> PLUG-discuss mailing list: PLUG-discuss@lists.phxlinux.org
> To subscribe, unsubscribe, or to change your mail settings:
> https://lists.phxlinux.org/mailman/listinfo/plug-discuss
>
--
James McPhee
jmcphe@gmail.com
---------------------------------------------------
PLUG-discuss mailing list:
PLUG-discuss@lists.phxlinux.org
To subscribe, unsubscribe, or to change your mail settings:
https://lists.phxlinux.org/mailman/listinfo/plug-discuss