我试图把一个三角形矩阵分成几个部分,这些部分包含了大致相同数量的元素。
我编写了下面的代码,它可以很好地工作在大多数输入组合中,并将我的矩阵分割成给定数量的部件,从0到$length。
但是,有一些输入组合,如$length = 2003和$number_of_segments = 50,在输出中缺少最后一个段。我测试了$threshold和$total的值,但即使在那些奇怪的情况下,它们似乎也是正确的。
你有什么想法吗,窃听器在哪里?
#!/usr/bin/perl
use strict; #should always be used
use warnings; #that one too
use autodie; #just in case I forgot to check anything
my $length = shift or die "ERROR: Not enough arguments!\n"; #number of rows in the matrix
my $number_of_segments = shift or die "ERROR: Not enough arguments!\n"; #number of segments we want to get
my @segments = ÷ #array of segment-limits
print "$_\n" foreach @segments;
sub divide {
my @segments = (0); #the first segment starts at 0
my $number_of_pairs = ($length*($length+1))/2; #number of elements in matrix
my $total = 0; #counter for the elements we already visited
my $segment_counter = 1; #we are in the first segment
for (my $i=0; $i<$length; $i++){ #going over the rows of the matrix
$total += $length-$i; #counting the elements in each row
my $threshold = ($number_of_pairs/$number_of_segments)*$segment_counter; #threshold for the next segment
if ($total >= $threshold){ #if our current segment is large enough
push @segments, $i+1; #save the limit
$segment_counter++; #and open the next segment
}
}
return @segments;
}发布于 2015-05-08 08:18:50
问题是,由于浮点数的准确性有限,一般无法比较浮点数的相等性。$threshold的最终值有点高(在32位Perl上是2007006.0000000002),所以您必须考虑到一个误差范围。
如果您将测试更改为
if ( $total + 1E-8 >= $threshold ) { ... }然后你就会得到你期望的结果。您可能需要调整增量值才能得到正确的结果。
注意,这是一种非常缓慢和不准确的做事方式。你真的应该把所有的算术都保持为整数,而不是浮点数,但是我现在没有时间重构你的代码
https://stackoverflow.com/questions/30118604
复制相似问题