double/float precision question
Dave Angel
davea at ieee.org
Wed Apr 1 14:48:34 EDT 2009
It's not at all clear what you really want. You say you want to "use"
the %e format, but then imply you're then going to turn it back into a
float. Since I don't know what the end goal is, I'll just comment
generally.
All Python floating point is equivalent to the 'double' type of the C
implementation. That may vary by C compiler, or by processor, but what
you see is typical of an 8 byte double type. I don't really remember my
values, but it's around 16 digits of precision. Anything displayed
beyond those digits is noise, and shouldn't be considered reproducible.
In other words, those two results are the same, the rounding is just
different.
To put it simply, in Python, float() on a floating point number does
not reduce the precision in the least.
As for having the user specify the number of digits he/she wants, that
just means you have to construct the format string in a variable.
Something like:
digits = 14 (this you'd have gotten from a user)
format = "%." + str(digits) + "e"
result = format % number #this does the formatting
TP 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?
>
> Thanks in advance
>
> Julien
>
>
More information about the Python-list
mailing list