This saves a great deal of time, as the sqrt() function is relativly expensive.
That used to be the true in the old times, when sqrt was calculated by software and the languages were simple. Well, simple languages still exist, but at least for Perl, the overhead of creating and destroying variables, moving things around and executing the opcodes are more important than what takes your hardware to do the floting point operations. Just see this benchmark for an example:
use Benchmark ':all';
our $a = 347.3;
our $b = 876.1;
our $c;
cmpthese( 5_000_000,
{
'rand' => sub { rand() },
add => sub { $c = $a + $b },
mul => sub { $c = $a * $b },
div => sub { $c = $a / $b },
'sqrt' => sub { $c = sqrt($b) },
}
);
Benchmark: timing 5000000 iterations of add, div, mul, rand, sqrt...
add: 2 wallclock secs ( 1.32 usr + 0.00 sys = 1.32 CPU) @ 3787878.79/s (n=5000000)
div: 1 wallclock secs ( 1.58 usr + 0.00 sys = 1.58 CPU) @ 3164556.96/s (n=5000000)
mul: 2 wallclock secs ( 1.50 usr + 0.00 sys = 1.50 CPU) @ 3333333.33/s (n=5000000)
rand: 1 wallclock secs ( 1.15 usr + 0.00 sys = 1.15 CPU) @ 4347826.09/s (n=5000000)
sqrt: 0 wallclock secs ( 1.18 usr + 0.01 sys = 1.19 CPU) @ 4201680.67/s (n=5000000)
Rate div mul add sqrt rand
div 3164557/s -- -5% -16% -25% -27%
mul 3333333/s 5% -- -12% -21% -23%
add 3787879/s 20% 14% -- -10% -13%
sqrt 4201681/s 33% 26% 11% -- -3%
rand 4347826/s 37% 30% 15% 3% --
Surprise! sqrt and rand may even be faster! The results are not entirely reproducible, but the short answer is: it doesn't really matter. As I said in a previous post, the problem here is the type of algorithm and how it scales.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.