uaa1006@dircon.co.uk (Peter Miles) (05/08/91)
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.
-- Pete
--
Pete Miles uaa1006@dircon.co.uk
...ukc!dircon!uaa1006tchrist@convex.COM (Tom Christiansen) (05/08/91)
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." loren@ural.Eng.Sun.COM (05/09/91)
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