And another one...
use strict;
use warnings;
my @nums = ( 1.3e-3, 3.7e-5, 102, 46, 1e-4, 1e-12);
@nums = sort { $b <=> $a } @nums; # biggest number first
my $exp_max = int log($nums[0]) / log(10); # first=biggest exponent
my $exp = $exp_max; # start exponent
my @res;
while ( @nums ) {
push @res, $nums[0] >= 10**$exp ? shift @nums : 0;
$exp--;
}
printf( "\$res[%2d] = %8g #1e%d\n", $_, $res[$_], $exp_max-$_) for (
+0..$#res);
Result:
$res[ 0] = 102 #1e2
$res[ 1] = 46 #1e1
$res[ 2] = 0 #1e0
$res[ 3] = 0 #1e-1
$res[ 4] = 0 #1e-2
$res[ 5] = 0.0013 #1e-3
$res[ 6] = 0.0001 #1e-4
$res[ 7] = 3.7e-05 #1e-5
$res[ 8] = 0 #1e-6
$res[ 9] = 0 #1e-7
$res[10] = 0 #1e-8
$res[11] = 0 #1e-9
$res[12] = 0 #1e-10
$res[13] = 0 #1e-11
$res[14] = 1e-12 #1e-12
-
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.
|