http://qs1969.pair.com?node_id=338745

Ryszard has asked for the wisdom of the Perl Monks concerning the following question:

I realise this is more than an algorithmic question, but figured someone here has a higher level of math geekyness than i.

What i want to do is round an integer to the closest unit.

In this specific case, i'm running a cronjob every five mins, and putting the data into a database for later processing.

What i'm after is rounding the timestamp from the database to the nearest 5 mins. I've come up with something, which seems to work, however i'm wondering if this is the most efficient way to do it.

#!/usr/bin/perl -w use strict; my @time = localtime(time); my $prec = 5; my $number = 52; $\="\n"; my $div = $number%$prec; $div = 1 if ($div == 0); my $num = sprintf("%.1f", $number/$div ); my $intnum = int sprintf("%.1f", $number/$div ); if ( ($num-$intnum) >= .5) { print $prec-($number%$prec)+$number; } else { print $number-($number%$prec); }

Replies are listed 'Best First'.
Re: OT: Integer rounding?
by Roy Johnson (Monsignor) on Mar 22, 2004 at 20:21 UTC
    You might get some help from this Q&A.

    Update:
    Doing it by hand, I'd do:

    sub round_to_nearest { my ($n, $scale) = @_; int(($n + $scale/2)/$scale) * $scale; }

    The PerlMonk tr/// Advocate
      A few sources:

      perlfaq4

      sub round { my($number) = shift; return int($number + .5); }

      perldoc -f int

      int Returns the integer portion of EXPR. If EXPR is omitted, uses "$_". You should not use this function for rounding: one because it truncates towards "0", and two because machine representations of floating point numbers can sometimes produce counterintuitive results. For example, "int(-6.725/0.025)" produces -268 rather than the correct -269; that's because it's really more like -268.99999999999994315658 instead. Usually, the "sprintf", "printf", or the "POSIX::floor" and "POSIX::ceil" functions will serve you better than will int().
Re: OT: Integer rounding?
by Ryszard (Priest) on Mar 23, 2004 at 19:13 UTC
    After a bit more googling i found the answer:
    dataless <dataless767@hotmail.com> wrote in article <a8liar$m91$1@helle.btinternet.com>... > Hi all, > Can anyone recommend an algorithm to round an integer to the nearest + 5 or > 10? Let's round n to the nearest five first: Divide n by 5 Add 0.5 to n Discard the fractional part of n Multiply n by 5 Now let's round to the nearest ten: Divide n by 10 Add 0.5 to n Discard the fractional part of n Multiply n by 10 Now let's round to the nearest seven: Divide n by 7 Add 0.5 to n Discard the fractional part of n Multiply n by 7 Do you see a pattern? -- Bringing you today's technology tomorrow...
    or in perl
    #!/usr/bin/perl -w use strict; my $prec = 5; my $number = 32; $\="\n"; print int(($number/$prec)+.5)*$prec;
    smaller, anyone?