[Israel.pm] floating point curiosity

Peter Gordon peter at pg-consultants.com
Wed Jan 4 22:14:06 PST 2006


$float*1000 ALWAYS gives the right answer: That's because it uses
something equivalent to sprintf("%.f",$float*1000). 

int truncates downwards.

So I don't see any surprise here.



On Wed, 2006-01-04 at 17:54 +0200, Levenglick Dov-RM07994 wrote:
> You are missing the point! 
> Notice that $float*1000 ALWAYS gives the right answer. However when I call int on the result, the answer sometimes gets messed up
> 
>  
> Best Regards,
> Dov Levenglick
> DSP SoC System and Applications Engineer,
> Network and Computing Systems Group
> Freescale Semiconductor Israel
> Tel. +972-9-952-2804
> The information contained in this email is classified as:
> [ ] General Business Information
> [ ] Freescale Internal Use Only
> [ ] Freescale Confidential Propriety
> [x] Personal Memorandum
>  
> 
> -----Original Message-----
> From: perl-bounces at perl.org.il [mailto:perl-bounces at perl.org.il] On Behalf Of Peter Gordon
> Sent: Wednesday, January 04, 2006 2:52 PM
> To: Perl in Israel
> Subject: Re: [Israel.pm] floating point curiosity
> 
> Floats don't get stored exactly. They may be out by a little bit in
> either direction. 
> 
> So 512.05 might get stored as 512.049999999999999
> Multiply by 1000 and you get 512049.9999999
> int truncates, so you get 512049.
> 
> What you need to do is int($float*1000 + 0.5) or 
> sprintf("%.f",$float*1000) 
> 
> Peter
> 
> On Wed, 2006-01-04 at 14:32 +0200, Levenglick Dov-RM07994 wrote:
> > Hi,
> > Can someone please explain what is happening here?
> > 
> > #!/usr/local/bin/perl5.6.1
> > $float1 = 16.05;
> > $float2 = 32.05;
> > $float3 = 512.05;
> > print $float1, " ", $float1*1000, " ", int ($float1*1000), "\n";
> > print $float2, " ", $float2*1000, " ", int ($float2*1000), "\n";
> > print $float3, " ", $float3*1000, " ", int ($float3*1000), "\n";
> > 
> > Produces:
> > 16.05 16050 16050
> > 32.05 32050 32049
> > 512.05 512050 512049
> > 
> > The question has to last printed value.
> > 
> >  
> > Best Regards,
> > Dov Levenglick
> > DSP SoC System and Applications Engineer,
> > Network and Computing Systems Group
> > Freescale Semiconductor Israel
> > Tel. +972-9-952-2804
> > The information contained in this email is classified as:
> > [ ] General Business Information
> > [ ] Freescale Internal Use Only
> > [ ] Freescale Confidential Propriety
> > [x] Personal Memorandum
> >  
> > 
> > 
> > _______________________________________________
> > Perl mailing list
> > Perl at perl.org.il
> > http://perl.org.il/mailman/listinfo/perl
> > 
> > 
> 
> 
> _______________________________________________
> Perl mailing list
> Perl at perl.org.il
> http://perl.org.il/mailman/listinfo/perl
> _______________________________________________
> Perl mailing list
> Perl at perl.org.il
> http://perl.org.il/mailman/listinfo/perl
> 
> 





More information about the Perl mailing list