[FRPythoneers] Numerical Accuracy

Sean Reifschneider jafo at tummy.com
Sat May 18 13:39:10 MDT 2002


On Sat, May 18, 2002 at 12:25:17PM -0700, Keith Hellman wrote:
>point me to documentation concerning why this is?  Particularly, I'm
>curious why the identical parsing and computation yields an accurate 38.3
>in both /usr/bin/bc and a simple C program.

Does it?  In Python:

   >>> print '%f' % (29.8+2.5+(4*1.5))
   38.300000

In C:

   guin:tmp$ cat foo.c
   main() { printf("%.15f\n", 29.8+2.5+4*1.5); }
   guin:tmp$ cc -o fm foo.c
   guin:tmp$ ./fm
   38.299999999999997

If you simply type the value in at the command-line, you are getting full
precision output, where "%f" in C is truncating the precision way down.  If
we do the equivalent in python (using %f), or the equivalent in C, we get
the same results...

>Do I need additional syntax to reduce error for floating calculations?

Well, if you don't want 15 digits of precision, specify something less.

Sean
-- 
 Canadian phone sex: What kind of hockey jersey are you wearing?
Sean Reifschneider, Inimitably Superfluous <jafo at tummy.com>
tummy.com - Linux Consulting since 1995. Qmail, KRUD, Firewalls, Python



More information about the FRPythoneers mailing list