- 論壇徽章:
- 12
|
本帖最后由 523066680 于 2018-03-17 15:32 編輯
- my $A = [3, -1, 4];
- my $B = [
- [1, 1, 1],
- [1,-1, 1],
- [2,-1, 3],
- [1, 1,-1],
- [3, 1, 4]
- ];
- # 估值
- my @esta;
- my @estb;
- my $e_a;
- my $e_b;
- for my $subset ( @$B )
- {
- $e_a = 0;
- $e_b = 0;
- for my $id ( 0 .. $#$A )
- {
- $e_a ++ if ( $subset->[$id] / $A->[$id] < 0 ); # 若正負(fù)相反,估值變大
- $e_b += ($subset->[$id] - $A->[$id])**2; # 分量距離作為估值
- }
- push @esta, $e_a;
- push @estb, sqrt($e_b);
- }
- # 顯示各組估值情況
- for my $id ( 0..$#esta )
- {
- printf "%4.1f %4.1f %4.1f ", @{$B->[$id]};
- printf "esta: %d estb: %.3f\n", $esta[$id], $estb[$id];
- }
- # 分級(jí)排序,正負(fù)估值優(yōu)先,向量距離其次
- my @order=
- sort
- {
- $esta[$a] <=> $esta[$b] ||
- $estb[$a] <=> $estb[$b]
- } ( 0 .. $#esta );
- my $best = $order[0];
- # 結(jié)果
- printf "\nBest: %s\n", join(", ", @{ $B->[$best] } );
復(fù)制代碼
2, -1, 3 是自己加上去的。
1.0 1.0 1.0 esta: 1 estb: 4.123
1.0 -1.0 1.0 esta: 0 estb: 3.606
2.0 -1.0 3.0 esta: 0 estb: 1.414
1.0 1.0 -1.0 esta: 2 estb: 5.745
3.0 1.0 4.0 esta: 1 estb: 2.000
Best: 2, -1, 3
|
|