Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!swrinde!cs.utexas.edu!sun-barr!newstop!grapevine!male!jethro!exodus!ural.Eng.Sun.COM!loren From: loren@ural.Eng.Sun.COM Newsgroups: comp.lang.perl Subject: Re: Addition of floating point problem Message-ID: <13012@exodus.Eng.Sun.COM> Date: 8 May 91 21:22:40 GMT References: <1991May07.174519.13307@dircon.co.uk> Sender: news@exodus.Eng.Sun.COM Organization: Sun Microsystems, Mt. View, Ca. Lines: 26 In article <1991May07.174519.13307@dircon.co.uk> uaa1006@dircon.co.uk (Peter Miles) writes: > >Hi...I'm trying to write some maths scripts for perl and have >been have a major problem. This is best summed up by the following: > >$ perl -e 'print 0.5 + 0.2,"\n"' >0.6999999999999996 >$ > >What's going on? I'm running perl verion 4.0.1.1 patchlevel 3 on >SCO UNIX 386 v 3.2.2. It's the version from comp.sources.misc. This is exactly what the %g in printf is for. Try the following: $ perl -e 'printf "%g\n", 0.5 + 0.2' 0.7 The problem you have is because there is no *exact* representation for .2 in most floating point systems. The %g format specifier is designed to take care of exactly this problem. ----------------------------------------------------------------------------- Mr Loren L. Hart The Ada Ace Group, Inc loren@cup.portal.com P.O. Box 36195 San Jose, CA 95158