in reply to Bug? 1+1 != 2
This is the classic rounding error. Using printf to display a few more significant digits from the intermediate terms shows up what is happening:
#!/usr/bin/perl use strict; use warnings; my $base = 0.0425; while ( my $line = <DATA>){ chomp $line; my ($z,$c1,$c2,$c3,$c4) = split(/,/,$line); print join("|",$z,$c1,$c2,$c3,$c4),"\n"; my $total = $c1+$c2+$c3; printf '%32.32f + %32.32f ?==? %32.32f'.$/, $base, $total, $total + +$base; print $c4 == ($total + $base) ? "True\n" : "False $c4 != ".($total+ +$base)."\n"; } __DATA__ 00501,0.0000,0.0425,0.0025,0.0875 00544,0.0000,0.0425,0.0025,0.0875 06390,0.0000,0.0425,0.0025,0.0875
Which produces this output
D:\Perl\test>test 00501|0.0000|0.0425|0.0025|0.0875 0.04250000000000000300000000000000 + 0.0450000000000000050000000000000 +0 ?==? 0.08750000000000000800000000000000 False 0.0875 != 0.0875 00544|0.0000|0.0425|0.0025|0.0875 0.04250000000000000300000000000000 + 0.0450000000000000050000000000000 +0 ?==? 0.08750000000000000800000000000000 False 0.0875 != 0.0875 06390|0.0000|0.0425|0.0025|0.0875 0.04250000000000000300000000000000 + 0.0450000000000000050000000000000 +0 ?==? 0.08750000000000000800000000000000 False 0.0875 != 0.0875
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re: Bug? 1+1 != 2
by JamesNC (Chaplain) on Jun 19, 2003 at 10:53 UTC | |
by BrowserUk (Patriarch) on Jun 19, 2003 at 11:52 UTC | |
by Nkuvu (Priest) on Jun 19, 2003 at 18:04 UTC | |
by JamesNC (Chaplain) on Jun 19, 2003 at 13:33 UTC |