Re: Getting fractional part from a float without using stringoperations

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • srinivasan srinivas

    Re: Getting fractional part from a float without using stringoperations

    Yes it works for most of the cases.  But it doesn't for the following case:
    >>str(abs(int(1 234567.89)-1234567.89))
    '0.889999999898 '

    Thanks,
    Srini


    ----- Original Message ----
    From: Tino Wildenhain <tino@wildenhai n.de>
    To: srinivasan srinivas <sri_annauni@ya hoo.co.in>
    Cc: Jeremiah Dodds <jeremiah.dodds @gmail.com>; python-list@python.org
    Sent: Wednesday, 19 November, 2008 7:33:46 PM
    Subject: Re: Getting fractionalpart from a float without using string operations

    srinivasan srinivaswrote:
    Yes. But it didn't give only the expected decimals.
    For ex:
    >  >>a = 1.23
    >  >>abs(int(a) -a)
    0.2299999999999 9998
    >  I would like to get the result '0.23' only.
    well, thats what get stored internally - there
    is no way around it if you are using floating
    point numbers:
    >>0.23
    0.2300000000000 0001

    but str() handles the rounding correctly:
    >>print 0.23
    0.23
    >>print abs(int(a) -a)
    0.23

    See also http://en.wikipedia.org/wiki/Floating_point
    for the problems with FP figures.

    Regards
    Tino



    Get perfect Email ID for your Resume. Grab now http://in.promos.yahoo.com/address
  • James Harris

    #2
    Re: Getting fractional part from a float without using stringoperation s

    On 20 Nov, 06:01, srinivasan srinivas <sri_anna...@ya hoo.co.inwrote:
    Yes it works for most of the cases. But it doesn't for the following case:
    >
    >str(abs(int(12 34567.89)-1234567.89))
    >
    '0.889999999898 '
    Well, that is 0.89 or about as near to it as the calculation can
    represent. Like other numbers 0.89 evidently cannot be exactly
    represented as a float in binary. The nearest number above it is
    >>0.89
    0.8900000000000 0001
    >>>
    This is not a Python issue but a result of storing numbers in floating
    binary form.

    BTW, please post comments below existing ones rather than above them.
    It is more familiar on Usenet and, as a consequence, easier to read.

    James

    Comment

    Working...