Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!sdd.hp.com!wuarchive!uunet!convex!usenet From: tchrist@convex.COM (Tom Christiansen) Newsgroups: comp.lang.perl Subject: Re: Addition of floating point problem Message-ID: <1991May07.202640.21635@convex.com> Date: 7 May 91 20:26:40 GMT References: <1991May07.174519.13307@dircon.co.uk> Sender: usenet@convex.com (news access account) Reply-To: tchrist@convex.COM (Tom Christiansen) Organization: CONVEX Software Development, Richardson, TX Lines: 51 Nntp-Posting-Host: pixel.convex.com From the keyboard of uaa1006@dircon.co.uk (Peter Miles): : :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. What's going is that your floating point hardware is giving you a value that isn't getting rounded enough for your tastes. Even though you say .7 and .2, you can't represent these values precisely in the internal floating point notation. Remember: God created the integers; and all else is the work of Man (and it shows :-). You could set $# to something like '%.1g' to change the default output format or better yet use a printf. (From the man page:) $# The output format for printed numbers. This vari- able is a half-hearted attempt to emulate awk's OFMT variable. There are times, however, when awk and perl have differing notions of what is in fact numeric. Also, the initial value is %.20g rather than %.6g, so you need to set $# explicitly to get awk's value. (Mnemonic: # is the number sign.) On a Convex, this statement: perl -e 'print .7, "\n"' yields 0.7 but on a Sun, I get this: .69999999999999995559 --tom -- Tom Christiansen tchrist@convex.com convex!tchrist "So much mail, so little time."