double/float precision question

Nick Craig-Wood nick at craig-wood.com
Wed Apr 1 22:30:05 CEST 2009


TP <Tribulations at Paralleles.invalid> wrote:
>  Hi everybody,
> 
>  Try the following python statements:
> 
> >>> "%.40f" % 0.2222222222222222222222222222222
>  '0.2222222222222222098864108374982606619596'
> >>> float( 0.2222222222222222222222222222222)
>  0.22222222222222221
> 
>  It seems the first result is the same than the following C program:
>  ################
>  #include <stdio.h>
> 
>  int main(void)
>  {
>      double a = 0.2222222222222222222222222222222;
> 
>      printf( "%.40f\n", a );
>      return 0;
>  }
>  #################
> 
>  My problem is the following:
>  * the precision "40" (for example) is given by the user, not by the
>  programmer.
>  * I want to use the string conversion facility with specifier "e", that
>  yields number is scientific format; so I cannot apply float() on the result
>  of "%.40e" % 0.2222222222222222222222222222222, I would lost the scientific
>  format.
> 
>  Is there any means to obtain the full C double in Python, or should I limit
>  the precision given by the user (and used in "%.*e") to the one of a Python
>  float?

Python floats are actually C doubles (as you proved yourself with your
little test program).

Eg

>>> 1.+2.**-52
1.0000000000000002

>>> 1.+2.**-53
1.0

Indicating that python floats have about 52 bits of precision, so are
definitely what C calls doubles.

When you do

>>> float( 0.2222222222222222222222222222222)
0.22222222222222221

Python prints as many decimal places as are significant in the answer.

This is covered in the FAQ

http://www.python.org/doc/faq/general/#why-are-floating-point-calculations-so-inaccurate

If you want more precision use the built in decimal module or the
third party gmpy module.

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list