我有一个混合值(正值和负值)的PDL (double类型)。我想把每一个条目都四舍五入到零。所以+1.2变成+1,+1.7变成+1,-1.2变成-1,-1.7变成-1,
我曾想过使用int(),但它不适用于PDL类型。
我也可以使用round(abs($x) - 0.5) * ($x <=> 0),但不确定如何在PDL上使用这个逻辑。
指针?
发布于 2017-06-20 11:42:34
rint函数在PDL::数学中的文档说明:
如果要将半整数与零相交,请尝试
floor(abs($x)+0.5)*($x<=>0)。
只需稍微修改一下,让它按照您想要的方式工作:
#!/usr/bin/perl
use warnings;
use strict;
use PDL;
my $pdl = 'PDL'->new(
[ 1, 1.3, 1.9, 2, 2.1, 2.7 ],
[ -1, -1.3, -1.9, -2, -2.1, -2.7 ]
);
$pdl = floor(abs($pdl)) * ($pdl <=> 0);
print $pdl;输出:
[
[ 1 1 1 2 2 2]
[-1 -1 -1 -2 -2 -2]
]发布于 2017-06-20 11:23:18
PDL::数学有floor,ceil和rint。所有这些职能都已到位。
因此,下面这样的内容应该能起作用:
#!/usr/bin/env perl
use warnings;
use strict;
use PDL;
my $pdl = 'PDL'->new(
[ 1, 1.3, 1.9, 2, 2.1, 2.7 ],
[ -1, -1.3, -1.9, -2, -2.1, -2.7 ]
);
print $pdl;
floor(inplace $pdl->where($pdl >= 0));
ceil (inplace $pdl->where($pdl < 0));
print $pdl;输出:
[
[ 1 1.3 1.9 2 2.1 2.7]
[ -1 -1.3 -1.9 -2 -2.1 -2.7]
]
[
[ 1 1 1 2 2 2]
[-1 -1 -1 -2 -2 -2]
]PS:@choroba的答案在非线程perl 5.24的一个古老的MacBook Pro上的基准测试中似乎快了20%
#!/usr/bin/env perl
use warnings;
use strict;
use constant N_ELEMS => $ARGV[0] || 100_000;
use Dumbbench;
use PDL;
sub one_scan {
my $pdl = 100 * grandom(N_ELEMS);
$pdl = floor(abs($pdl)) * ($pdl <=> 0);
return;
}
sub two_scans {
my $pdl = 100 * grandom(N_ELEMS);
floor(inplace $pdl->where($pdl >= 0));
ceil (inplace $pdl->where($pdl < 0));
return;
}
sub baseline {
my $pdl = 100 * grandom(N_ELEMS);
return;
}
my $bench = Dumbbench->new;
$bench->add_instances(
Dumbbench::Instance::PerlSub->new(code => \&baseline, name => 'Baseline'),
Dumbbench::Instance::PerlSub->new(code => \&one_scan, name => 'One Scan'),
Dumbbench::Instance::PerlSub->new(code => \&two_scans, name => 'Two Scans'),
);
$bench->run;
$bench->report;https://stackoverflow.com/questions/44651640
复制相似问题