#!/usr/bin/perl -w
$bigtwo = 2**32; while ($a = <DATA>) { $b = (sprintf "%.0f", $a * $bigtwo)/$bigtwo; $up_or_down = $b >= $a ? "round up" : "round down"; print "$a $up_or_down\n"; }
__END__ 1.655 1.755
The output of this script is 1.655 round up 1.755 round down
=== Here is what is going on.
The 32-bit floating point number $b closest to $a = 1.655 is greater than 1.655. This number $b is the computer representation of 1.655; consequently the instruction
sprintf "%.2f", $a;
rounds $b up to 1.66.
On the other hand, 32-bit floating point number $b closest to $a = 1.755 is less than 1.755. This number $b is the computer representation of 1.755; consequently the instruction
sprintf ".2f", $a;
rounds $b down to 1.75.
Regards,
Vic
At 1:49 PM -0500 10/13/03, Bill Stephenson wrote:
I've got a script that takes numbers similar to those below and then rounds them and adds them together using code similar to what is below.
#!/usr/bin/perl -w use strict; my $item_1 = "1.655"; my $item_2 = "1.755"; my $rnd_1 = (sprintf qq~%.2f~, $item_1); my $rnd_2 = (sprintf qq~%.2f~, $item_2); print "$rnd_1, $rnd_2";
The code above prints this result (system 10.1.5, perl 5.6.0):
1.66, 1.75
But shouldn't it be:
1.66, 1.76
or:
1.65, 1.75
I'm no math wizard, so if someone could please take the time and tell what I'm missing here I would very much appreciate it!
--
Bill Stephenson www.PerlHelp.com 1-417-546-5593
-- *---* mailto:[EMAIL PROTECTED] | Victor Thane Norton, Jr. | Mathematician and Motorcyclist | phone: 419-353-3399 *---* http://vic.norton.name