in reply to Preferred Methods
I've always wondered why Perl doesn't include a round function, it is something that tends to stump beginners. I also wondered if this was faster than japhy's code.use POSIX; sub round { floor($_[0] + 0.5) }
And it seems to be slightly faster. I think it would also be marginally more understandable from a maintanace standpoint.Benchmark: timing 100000 iterations of round1, round2... round1: 65 wallclock secs (64.59 usr + 0.00 sys = 64.59 CPU) @ 15 +48.23/s (n=100000) round2: 47 wallclock secs (47.78 usr + 0.00 sys = 47.78 CPU) @ 20 +92.93/s (n=100000)
Also remember that if you work with floating point numbers you might get things you don't expect, for example, adding 0.01 to 0 99 times gives you 0.990000000000001.
The module Math::FixedPrecision seems promising, but unfortunatly it rounds 0.50 to 0 rather than 1.
I know I've gone off on a slight tangent here.. but is there some nicer way to deal with this. I haven't used Math::Currency but that does look promising.use Math::FixedPrecision; for (my $i = Math::FixedPrecision->new(0); $i <= 1; $i += 0.01) { print $i, "\t", Math::FixedPrecision->new($i + 0.01, 0), "\n"; }
gav^
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Re: Preferred Methods
by particle (Vicar) on Jan 14, 2002 at 22:10 UTC |