简体   繁体   中英

Perl: Fixing Floating Point Incrementation

I'm writing a program where I need to formula a hash where the keys are between a user defined range, and increase at each step be a specific increment. This works fine with values such as 1, 2 etc.. but when I introduce floating point numbers such as 0.1, 0.01, rounding errors accumulate and the keys do not populate in a way that I'd like.

This this the code I'm using at the minute:

my %hash;
for (my $increm = $lowerbound; $increm <= $upperbound; $increm+=$binsize) {

        $hash{$increm} = 0;

}

by default:

$lowerbound = 1000
$upperbound = 1500
$binsize = 1

but I need to allow for decimal values as specified above. Any ideas how I can fix this problem so the hash populates the keys properly? (the values of the keys aren't important at this point)

Thanks!

You could round the keys using sprintf , or use avoid accumulation by incrementing by an integer then adjusting.

for (my $j = $start/$by; $j <= $last/$by; ++$j) {
   my $i = $j*$by;
   ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM