Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #10013 > unrolled thread

Re: Convert '165.0' to int

Started byLeo Jay <python.leojay@gmail.com>
First post2011-07-21 17:47 +0800
Last post2011-07-25 10:19 +0200
Articles 20 on this page of 50 — 15 participants

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Convert '165.0' to int Leo Jay <python.leojay@gmail.com> - 2011-07-21 17:47 +0800
    Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-21 04:05 -0700
      Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-21 04:23 -0700
    Re: Convert '165.0' to int Web Dreamer <webdreamer@nospam.fr> - 2011-07-21 14:46 +0200
      Re: Convert '165.0' to int Billy Mays <81282ed9a88799d21e77957df2d84bd6514d9af6@myhashismyemail.com> - 2011-07-21 09:27 -0400
        Re: Convert '165.0' to int Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2011-07-22 04:40 +0200
          Re: Convert '165.0' to int Billy Mays <noway@nohow.com> - 2011-07-22 00:45 -0400
            Re: Convert '165.0' to int Grant Edwards <invalid@invalid.invalid> - 2011-07-22 14:21 +0000
              Re: Convert '165.0' to int Billy Mays <81282ed9a88799d21e77957df2d84bd6514d9af6@myhashismyemail.com> - 2011-07-22 10:49 -0400
                Re: Convert '165.0' to int Grant Edwards <invalid@invalid.invalid> - 2011-07-22 14:58 +0000
                  Re: Convert '165.0' to int Billy Mays <81282ed9a88799d21e77957df2d84bd6514d9af6@myhashismyemail.com> - 2011-07-22 11:06 -0400
                    Re: Convert '165.0' to int Grant Edwards <invalid@invalid.invalid> - 2011-07-22 15:44 +0000
            Re: Convert '165.0' to int Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2011-07-24 10:03 +0200
        Re: Convert '165.0' to int Web Dreamer <webdreamer@nospam.fr> - 2011-07-25 10:23 +0200
          Re: Convert '165.0' to int Web Dreamer <webdreamer@nospam.fr> - 2011-07-25 11:00 +0200
      Re: Convert '165.0' to int Grant Edwards <invalid@invalid.invalid> - 2011-07-21 14:13 +0000
        Re: Convert '165.0' to int Terry Reedy <tjreedy@udel.edu> - 2011-07-21 16:00 -0400
          Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-21 22:55 -0700
            Re: Convert '165.0' to int Hrvoje Niksic <hniksic@xemacs.org> - 2011-07-22 14:42 +0200
              Re: Convert '165.0' to int rantingrick <rantingrick@gmail.com> - 2011-07-22 12:32 -0700
                Re: Convert '165.0' to int rantingrick <rantingrick@gmail.com> - 2011-07-22 12:34 -0700
                Re: Convert '165.0' to int Chris Angelico <rosuav@gmail.com> - 2011-07-23 06:06 +1000
            Re: Convert '165.0' to int Terry Reedy <tjreedy@udel.edu> - 2011-07-22 15:59 -0400
              Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-22 23:53 -0700
                Re: Convert '165.0' to int Chris Angelico <rosuav@gmail.com> - 2011-07-23 17:42 +1000
                  Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-23 02:03 -0700
                  Re: Convert '165.0' to int Billy Mays <noway@nohow.com> - 2011-07-23 11:12 -0400
                    Re: Convert '165.0' to int Chris Angelico <rosuav@gmail.com> - 2011-07-24 01:20 +1000
                    Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-23 23:53 -0700
                      Re: Convert '165.0' to int Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-07-24 17:34 +1000
                        Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-24 00:58 -0700
                          Re: Convert '165.0' to int Chris Angelico <rosuav@gmail.com> - 2011-07-24 18:07 +1000
                            Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-24 01:21 -0700
                              Re: Convert '165.0' to int Chris Angelico <rosuav@gmail.com> - 2011-07-24 18:28 +1000
                Re: Convert '165.0' to int Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-07-23 18:23 +1000
                  Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-23 02:08 -0700
                Re: Convert '165.0' to int rantingrick <rantingrick@gmail.com> - 2011-07-23 11:28 -0700
                  Re: Convert '165.0' to int Billy Mays <noway@nohow.com> - 2011-07-23 23:53 -0400
                    Re: Convert '165.0' to int Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2011-07-24 17:21 +1000
                      Re: Convert '165.0' to int Ben Finney <ben+python@benfinney.id.au> - 2011-07-24 17:43 +1000
                  Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-24 01:36 -0700
                    Re: Convert '165.0' to int Ben Finney <ben+python@benfinney.id.au> - 2011-07-24 18:53 +1000
                      Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-24 02:01 -0700
                        Re: Convert '165.0' to int Ben Finney <ben+python@benfinney.id.au> - 2011-07-24 19:25 +1000
                      Re: Convert '165.0' to int Chris Angelico <rosuav@gmail.com> - 2011-07-24 19:42 +1000
                    Re: Convert '165.0' to int Gregory Ewing <greg.ewing@canterbury.ac.nz> - 2011-07-25 12:04 +1200
                      Re: Convert '165.0' to int Frank Millman <frank@chagford.com> - 2011-07-24 22:50 -0700
                        RE: Convert '165.0' to int "Prasad, Ramit" <ramit.prasad@jpmorgan.com> - 2011-08-01 20:42 -0400
                      RE: Convert '165.0' to int "Prasad, Ramit" <ramit.prasad@jpmorgan.com> - 2011-08-01 20:32 -0400
              Re: Convert '165.0' to int Web Dreamer <webdreamer@nospam.fr> - 2011-07-25 10:19 +0200

Page 1 of 3  [1] 2 3  Next page →


#10013 — Re: Convert '165.0' to int

FromLeo Jay <python.leojay@gmail.com>
Date2011-07-21 17:47 +0800
SubjectRe: Convert '165.0' to int
Message-ID<mailman.1317.1311241673.1164.python-list@python.org>
On Thu, Jul 21, 2011 at 5:31 PM, Frank Millman <frank@chagford.com> wrote:
>
> Hi all
>
> I want to convert '165.0' to an integer.
>
> The obvious method does not work -
>
>>>> x = '165.0'
>>>> int(x)
>
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> ValueError: invalid literal for int() with base 10: '165.0'
>
> If I convert to a float first, it does work -
>
>>>> int(float(x))
>
> 165
>>>>
>
> Is there a short cut, or must I do this every time (I have lots of them!) ? I know I can write a function to do this, but is there anything built-in?
>
> Thanks
>
> Frank Millman
>

How about int(x[:-2])?

--
Best Regards,
Leo Jay

[toc] | [next] | [standalone]


#10016

FromFrank Millman <frank@chagford.com>
Date2011-07-21 04:05 -0700
Message-ID<d4a7f101-ad65-422f-8926-8a345d303ea2@b2g2000vbo.googlegroups.com>
In reply to#10013
On Jul 21, 11:47 am, Leo Jay <python.leo...@gmail.com> wrote:
> On Thu, Jul 21, 2011 at 5:31 PM, Frank Millman <fr...@chagford.com> wrote:
>
> > Hi all
>
> > I want to convert '165.0' to an integer.
>
> > The obvious method does not work -
>
> >>>> x = '165.0'
> >>>> int(x)
>
> > Traceback (most recent call last):
> >  File "<stdin>", line 1, in <module>
> > ValueError: invalid literal for int() with base 10: '165.0'
>
> > If I convert to a float first, it does work -
>
> >>>> int(float(x))
>
> > 165
>
> > Is there a short cut, or must I do this every time (I have lots of them!) ? I know I can write a function to do this, but is there anything built-in?
>
> > Thanks
>
> > Frank Millman
>
> How about int(x[:-2])?
>
> --
> Best Regards,
> Leo Jay- Hide quoted text -
>
> - Show quoted text -

Nice idea, but it seems to be marginally slower[1] than int(float(x)),
so I think I will stick with the latter.

Frank

[1] See separate thread on apparent inconsisteny in timeit timings.

[toc] | [prev] | [next] | [standalone]


#10018

FromFrank Millman <frank@chagford.com>
Date2011-07-21 04:23 -0700
Message-ID<188f71c7-7743-418f-ade2-6c40cdd24cd2@v7g2000vbk.googlegroups.com>
In reply to#10016
>
> [1] See separate thread on apparent inconsisteny in timeit timings.- Hide quoted text -
>

I must have done something wrong - it is consistent now.

Here are the results -

C:\Python32\Lib>timeit.py "int(float('165.0'))"
100000 loops, best of 3: 3.51 usec per loop

C:\Python32\Lib>timeit.py "int('165.0'[:-2])"
100000 loops, best of 3: 4.63 usec per loop

Frank

[toc] | [prev] | [next] | [standalone]


#10019

FromWeb Dreamer <webdreamer@nospam.fr>
Date2011-07-21 14:46 +0200
Message-ID<4e281f97$0$16404$426a74cc@news.free.fr>
In reply to#10013
Leo Jay a écrit ce jeudi 21 juillet 2011 11:47 dans 
<mailman.1317.1311241673.1164.python-list@python.org> :

> On Thu, Jul 21, 2011 at 5:31 PM, Frank Millman <frank@chagford.com> wrote:
>>
>> Hi all
>>
>> I want to convert '165.0' to an integer.
>>
>> The obvious method does not work -
>>
>>>>> x = '165.0'
>>>>> int(x)
>>
>> Traceback (most recent call last):
>> File "<stdin>", line 1, in <module>
>> ValueError: invalid literal for int() with base 10: '165.0'
>>
>> If I convert to a float first, it does work -
>>
>>>>> int(float(x))
>>
>> 165
>>>>>
>>
>> Is there a short cut, or must I do this every time (I have lots of them!)
>> ? I know I can write a function to do this, but is there anything
>> built-in?
>>
>> Thanks
>>
>> Frank Millman
>>
> 
> How about int(x[:-2])?

The problem about this is "what happens if the string represents a float 
with more than 'one' number after the decimal point"?
i.e.: imagine you have '3.14159', '3.14159'[:-2] gives '3.141' so you would 
still get a "ValueError: invalid literal for int()"
If you do not want to use 'float()' try:

int(x.split('.')[0])

But, the problem is the same as with int(float(x)), the integer number is 
still not as close as possible as the original float value.

I would in fact consider doing this:

int(round(float(x)))

example:
>>> int(round(float('165.4')))
165
>>> int(round(float('165.6')))
166

166 is closer to 165.6 than is 165

-- 
Web Dreamer

[toc] | [prev] | [next] | [standalone]


#10024

FromBilly Mays <81282ed9a88799d21e77957df2d84bd6514d9af6@myhashismyemail.com>
Date2011-07-21 09:27 -0400
Message-ID<j099fu$7kv$1@speranza.aioe.org>
In reply to#10019
On 07/21/2011 08:46 AM, Web Dreamer wrote:
> If you do not want to use 'float()' try:
>
> int(x.split('.')[0])
>

This is right.

> But, the problem is the same as with int(float(x)), the integer number is
> still not as close as possible as the original float value.
>
> I would in fact consider doing this:
>
> int(round(float(x)))

This is wrong, since there is a loss of information in the float cast:

 >>> float('9007199254740993.0')
9007199254740992.0

Notice the last digit switched from a 3 to a 2?  Floats in python don't 
have arbitrary accuracy.  You would need to import decimal and use it 
for rounding to work properly.

--
Bill

[toc] | [prev] | [next] | [standalone]


#10061

FromThomas 'PointedEars' Lahn <PointedEars@web.de>
Date2011-07-22 04:40 +0200
Message-ID<19884639.rsrFWyGXb5@PointedEars.de>
In reply to#10024
Billy Mays wrote:

> On 07/21/2011 08:46 AM, Web Dreamer wrote:
>> If you do not want to use 'float()' try:
>>
>> int(x.split('.')[0])
> 
> This is right.

Assuming that the value of `x' is in the proper format, of course.  Else you 
might easily cut to the first one to three digits of a string representation 
(if `.' is the thousands separator of the locale, e. g.)
 
>> But, the problem is the same as with int(float(x)), the integer number is
>> still not as close as possible as the original float value.
>>
>> I would in fact consider doing this:
>>
>> int(round(float(x)))
> 
> This is wrong, since there is a loss of information in the float cast:
> 
>  >>> float('9007199254740993.0')
> 9007199254740992.0
> 
> Notice the last digit switched from a 3 to a 2?  Floats in python don't
> have arbitrary accuracy.  You would need to import decimal and use it
> for rounding to work properly.

It should be floor() though, for that is what int() does.

-- 
PointedEars

Bitte keine Kopien per E-Mail. / Please do not Cc: me.

[toc] | [prev] | [next] | [standalone]


#10069

FromBilly Mays <noway@nohow.com>
Date2011-07-22 00:45 -0400
Message-ID<j0av9t$32c$1@speranza.aioe.org>
In reply to#10061
On 7/21/2011 10:40 PM, Thomas 'PointedEars' Lahn wrote:
> Billy Mays wrote:
>
>> On 07/21/2011 08:46 AM, Web Dreamer wrote:
>>> If you do not want to use 'float()' try:
>>>
>>> int(x.split('.')[0])
>>
>> This is right.
>
> Assuming that the value of `x' is in the proper format, of course.  Else you
> might easily cut to the first one to three digits of a string representation
> (if `.' is the thousands separator of the locale, e. g.)
>

The point (which was clear to me) was to convert a properly formatted 
string representation of a floating point number to an integer.  We 
might also assume the number could be a hex encoded float or be in 
scientific notation.  If the input is not properly formatted, it is 
unreasonable for us to return a correct value.


>>> But, the problem is the same as with int(float(x)), the integer number is
>>> still not as close as possible as the original float value.
>>>
>>> I would in fact consider doing this:
>>>
>>> int(round(float(x)))
>>
>> This is wrong, since there is a loss of information in the float cast:
>>
>>   >>>  float('9007199254740993.0')
>> 9007199254740992.0
>>
>> Notice the last digit switched from a 3 to a 2?  Floats in python don't
>> have arbitrary accuracy.  You would need to import decimal and use it
>> for rounding to work properly.
>
> It should be floor() though, for that is what int() does.
>
Um, what?

--
Bill

[toc] | [prev] | [next] | [standalone]


#10107

FromGrant Edwards <invalid@invalid.invalid>
Date2011-07-22 14:21 +0000
Message-ID<j0c11b$snt$1@reader1.panix.com>
In reply to#10069
On 2011-07-22, Billy Mays <noway@nohow.com> wrote:
> On 7/21/2011 10:40 PM, Thomas 'PointedEars' Lahn wrote:
>> Billy Mays wrote:
>>
>>> On 07/21/2011 08:46 AM, Web Dreamer wrote:
>>>> If you do not want to use 'float()' try:
>>>>
>>>> int(x.split('.')[0])
>>>
>>> This is right.
>>
>> Assuming that the value of `x' is in the proper format, of course.  Else you
>> might easily cut to the first one to three digits of a string representation
>> (if `.' is the thousands separator of the locale, e. g.)
>
> The point (which was clear to me) was to convert a properly formatted
> string representation of a floating point number to an integer.

While that may be clear to you, that's because you've made some
assumptions.  "Convert a properly formatted string representation of a
floating point number to an integer" is not a rigorous definition.

> We might also assume the number could be a hex encoded float or be in
> scientific notation.  If the input is not properly formatted, it is 
> unreasonable for us to return a correct value.

What does "properly formatted" mean?  Who says that the character
representing the radix is "." rather than ","?

>>> Notice the last digit switched from a 3 to a 2?  Floats in python don't
>>> have arbitrary accuracy.  You would need to import decimal and use it
>>> for rounding to work properly.
>>
>> It should be floor() though, for that is what int() does.
>
> Um, what?

The example given by the OP implied that int(float(s)) did what he
wanted.  That is _not_ rounding the float.  It's the equivalent of
using the floor() function.

-- 
Grant Edwards               grant.b.edwards        Yow! Maybe we could paint
                                  at               GOLDIE HAWN a rich PRUSSIAN
                              gmail.com            BLUE --

[toc] | [prev] | [next] | [standalone]


#10109

FromBilly Mays <81282ed9a88799d21e77957df2d84bd6514d9af6@myhashismyemail.com>
Date2011-07-22 10:49 -0400
Message-ID<j0c2lk$o2d$1@speranza.aioe.org>
In reply to#10107
On 07/22/2011 10:21 AM, Grant Edwards wrote:
> While that may be clear to you, that's because you've made some
> assumptions.  "Convert a properly formatted string representation of a
> floating point number to an integer" is not a rigorous definition.
>
>
> What does "properly formatted" mean?  Who says that the character
> representing the radix is "." rather than ","?
>

Properly formatted means that Python would accept the string as an 
argument to float() without raising an exception.


>>>> Notice the last digit switched from a 3 to a 2?  Floats in python don't
>>>> have arbitrary accuracy.  You would need to import decimal and use it
>>>> for rounding to work properly.
>>>
>>> It should be floor() though, for that is what int() does.
>>
>> Um, what?
>
> The example given by the OP implied that int(float(s)) did what he
> wanted.  That is _not_ rounding the float.  It's the equivalent of
> using the floor() function.
>

int(float(s)) does the "right thing" for short strings.  However, for 
longer strings it loses information due to the way floats are 
implemented in Python.  Python uses the IEEE754 double precision 
datatype(double) to implement floating point numbers.  The floats only 
have 53 bits in the mantissa portion of the number which means python 
can only accurately represent integers up to 2**53 correctly as floats.

Compare this to integers in Python, which are automatically upcast to 
longs if overflow would occur.  The int() call will never lose accuracy 
when converting a properly formatted integer string.  float() will lose 
accuracy, even if the float string is properly formatted.  The is no 
floor() being called or used, this is simply the behavior of the float 
datatype.

You seem to be worrying about python producing invalid output for 
invalid input (period  separated numbers).  You should be worrying if 
valid input (a very long float string) produces invalid output.

--
Bill




[toc] | [prev] | [next] | [standalone]


#10111

FromGrant Edwards <invalid@invalid.invalid>
Date2011-07-22 14:58 +0000
Message-ID<j0c361$t3c$1@reader1.panix.com>
In reply to#10109
On 2011-07-22, Billy Mays <81282ed9a88799d21e77957df2d84bd6514d9af6@myhashismyemail.com> wrote:
> On 07/22/2011 10:21 AM, Grant Edwards wrote:
>> While that may be clear to you, that's because you've made some
>> assumptions.  "Convert a properly formatted string representation of a
>> floating point number to an integer" is not a rigorous definition.
>>
>>
>> What does "properly formatted" mean?  Who says that the character
>> representing the radix is "." rather than ","?
>>
>
> Properly formatted means that Python would accept the string as an 
> argument to float() without raising an exception.

Then you can't assume that '.' is the radix character.

>>>>> Notice the last digit switched from a 3 to a 2?  Floats in python
>>>>> don't have arbitrary accuracy.  You would need to import decimal and
>>>>> use it for rounding to work properly.
>>>>
>>>> It should be floor() though, for that is what int() does.
>>>
>>> Um, what?
>>
>> The example given by the OP implied that int(float(s)) did what he
>> wanted.  That is _not_ rounding the float.  It's the equivalent of
>> using the floor() function.
>>
>
> int(float(s)) does the "right thing" for short strings.  However, for 
> longer strings it loses information due to the way floats are 
> implemented in Python.

True but irrelevent to the point that using a rounding conversion is
_not_ equivelent to the OP's example using int(float()).

> Python uses the IEEE754 double precision datatype(double) to
> implement floating point numbers.  The floats only have 53 bits in
> the mantissa portion of the number which means python can only
> accurately represent integers up to 2**53 correctly as floats.
>
> Compare this to integers in Python, which are automatically upcast to
> longs if overflow would occur.  The int() call will never lose
> accuracy when converting a properly formatted integer string.
> float() will lose accuracy, even if the float string is properly
> formatted.  The is no floor() being called or used, this is simply
> the behavior of the float datatype.
>
> You seem to be worrying about python producing invalid output for 
> invalid input (period separated numbers).  You should be worrying if 
> valid input (a very long float string) produces invalid output.

No, I'm talking about the claim that you should use decmial so that
you can use rounding when the OP's example showed that rounding was
not what he wanted.

-- 
Grant Edwards               grant.b.edwards        Yow! Boys, you have ALL
                                  at               been selected to LEAVE th'
                              gmail.com            PLANET in 15 minutes!!

[toc] | [prev] | [next] | [standalone]


#10112

FromBilly Mays <81282ed9a88799d21e77957df2d84bd6514d9af6@myhashismyemail.com>
Date2011-07-22 11:06 -0400
Message-ID<j0c3l5$qbt$1@speranza.aioe.org>
In reply to#10111
On 07/22/2011 10:58 AM, Grant Edwards wrote:
> On 2011-07-22, Billy Mays<81282ed9a88799d21e77957df2d84bd6514d9af6@myhashismyemail.com>  wrote:
>> Properly formatted means that Python would accept the string as an
>> argument to float() without raising an exception.
>
> Then you can't assume that '.' is the radix character.
>

When you use radix, I assume you mean the grouping separator for large 
numbers, not the base correct?  I have always heard radix used as the 
base (ie base 2) of the number, as in radix sort.

> No, I'm talking about the claim that you should use decmial so that
> you can use rounding when the OP's example showed that rounding was
> not what he wanted.
>

Yes, you are right.  I mistyped what I was thinking.  Let me rephrase:

decimal is needed to preserve the accuracy of the string to `number` 
conversion.

--
Bill

[toc] | [prev] | [next] | [standalone]


#10113

FromGrant Edwards <invalid@invalid.invalid>
Date2011-07-22 15:44 +0000
Message-ID<j0c5s7$hih$1@reader1.panix.com>
In reply to#10112
On 2011-07-22, Billy Mays <81282ed9a88799d21e77957df2d84bd6514d9af6@myhashismyemail.com> wrote:
> On 07/22/2011 10:58 AM, Grant Edwards wrote:
>> On 2011-07-22, Billy Mays<81282ed9a88799d21e77957df2d84bd6514d9af6@myhashismyemail.com>  wrote:
>>> Properly formatted means that Python would accept the string as an
>>> argument to float() without raising an exception.
>>
>> Then you can't assume that '.' is the radix character.
>
> When you use radix, I assume you mean the grouping separator for large 
> numbers, not the base correct?  I have always heard radix used as the 
> base (ie base 2) of the number, as in radix sort.

http://en.wikipedia.org/wiki/Radix_point

>> No, I'm talking about the claim that you should use decmial so that
>> you can use rounding when the OP's example showed that rounding was
>> not what he wanted.
>
> Yes, you are right.  I mistyped what I was thinking.  Let me rephrase:
>
> decimal is needed to preserve the accuracy of the string to `number` 
> conversion.

True.  You shouldn't try to use a float for values not within the
range of a float.

-- 
Grant Edwards               grant.b.edwards        Yow! NANCY!!  Why is
                                  at               everything RED?!
                              gmail.com            

[toc] | [prev] | [next] | [standalone]


#10192

FromThomas 'PointedEars' Lahn <PointedEars@web.de>
Date2011-07-24 10:03 +0200
Message-ID<3863438.KyEDYIHfym@PointedEars.de>
In reply to#10069
Billy Mays wrote:

> On 7/21/2011 10:40 PM, Thomas 'PointedEars' Lahn wrote:
>> Billy Mays wrote:
>>> On 07/21/2011 08:46 AM, Web Dreamer wrote:
>>>> If you do not want to use 'float()' try:
>>>>
>>>> int(x.split('.')[0])
>>>
>>> This is right.
>>
>> Assuming that the value of `x' is in the proper format, of course.  Else
>> you might easily cut to the first one to three digits of a string
>> representation (if `.' is the thousands separator of the locale, e. g.)
> 
> The point (which was clear to me) was to convert a properly formatted
> string representation of a floating point number to an integer.  We
> might also assume the number could be a hex encoded float or be in
> scientific notation.  If the input is not properly formatted, it is
> unreasonable for us to return a correct value.

By "*proper* format" I was not referring to the user input.  It is not up to 
you to define which number formats in the rest of the world can be 
considered proper.  Indeed, Switzerland uses 1'234.56, and I find that quite 
reasonable, even though I am German and in Germany 1.234,56 is used (which I 
was referring to).
 
>>>> But, the problem is the same as with int(float(x)), the integer number
>>>> is still not as close as possible as the original float value.
>>>>
>>>> I would in fact consider doing this:
>>>>
>>>> int(round(float(x)))
>>>
>>> This is wrong, since there is a loss of information in the float cast:
>>>
>>>   >>>  float('9007199254740993.0')
>>> 9007199254740992.0
>>>
>>> Notice the last digit switched from a 3 to a 2?  Floats in python don't
>>> have arbitrary accuracy.  You would need to import decimal and use it
>>> for rounding to work properly.
>>
>> It should be floor() though, for that is what int() does.
>
> Um, what?

_____

>>> print math.floor.__doc__
floor(x)

Return the floor of x as a float.
This is the largest integral value <= x.
_____

The point I was trying to make was that round() would return a different 
result than intended by the OP when the fractional part was greater than
or equal to 0.5.  So it should not be used here.  Instead,

  from math import floor
  int(floor(float(x)))

should be used.  (I assumed before, without testing, that Python had a 
global floor() function.  Sorry.)

There is still the rounding error as there is no arbitrary precision with 
built-in floating-point values indeed – however, is it common that users 
enter such large numbers? I don't think so –, but no rounding error caused 
by programmer error.

>>> int(round(float('9007199254.5')))
9007199255L

>>> int(floor(float('9007199254.5')))
9007199254L

-- 
PointedEars

Bitte keine Kopien per E-Mail. / Please do not Cc: me.

[toc] | [prev] | [next] | [standalone]


#10249

FromWeb Dreamer <webdreamer@nospam.fr>
Date2011-07-25 10:23 +0200
Message-ID<4e2d27ff$0$21340$426a74cc@news.free.fr>
In reply to#10024
Billy Mays a écrit ce jeudi 21 juillet 2011 15:27 dans 
<j099fu$7kv$1@speranza.aioe.org> :

> On 07/21/2011 08:46 AM, Web Dreamer wrote:
>> If you do not want to use 'float()' try:
>>
>> int(x.split('.')[0])
>>
> 
> This is right.
> 
>> But, the problem is the same as with int(float(x)), the integer number is
>> still not as close as possible as the original float value.
>>
>> I would in fact consider doing this:
>>
>> int(round(float(x)))
> 
> This is wrong, since there is a loss of information in the float cast:
> 
>  >>> float('9007199254740993.0')
> 9007199254740992.0
> 
> Notice the last digit switched from a 3 to a 2?  Floats in python don't
> have arbitrary accuracy.  You would need to import decimal and use it
> for rounding to work properly.

Indeed, you are right.

See my reply to Terry Reedy in this thread, for more accuracy we should do 
this:

>>> def strtoint(s):
...     elts = s.split('.')
...     number = int(elts[0])
...     if len(elts)>1:
...         if int(elts[1][0])>=5:
...             number += 1
...     return number

>>> s = '123456789012345678901.987654321'
>>> strtoint(s)
123456789012345678902L
>>> int(round(float(s)))
123456789012345683968L
>>>

-- 
Web Dreamer

[toc] | [prev] | [next] | [standalone]


#10251

FromWeb Dreamer <webdreamer@nospam.fr>
Date2011-07-25 11:00 +0200
Message-ID<4e2d30c3$0$20279$426a74cc@news.free.fr>
In reply to#10249
Web Dreamer a écrit ce lundi 25 juillet 2011 10:23 dans 
<4e2d27ff$0$21340$426a74cc@news.free.fr> :

> Billy Mays a écrit ce jeudi 21 juillet 2011 15:27 dans
> <j099fu$7kv$1@speranza.aioe.org> :
> 
>> On 07/21/2011 08:46 AM, Web Dreamer wrote:
>>> If you do not want to use 'float()' try:
>>>
>>> int(x.split('.')[0])
>>>
>> 
>> This is right.
>> 
>>> But, the problem is the same as with int(float(x)), the integer number
>>> is still not as close as possible as the original float value.
>>>
>>> I would in fact consider doing this:
>>>
>>> int(round(float(x)))
>> 
>> This is wrong, since there is a loss of information in the float cast:
>> 
>>  >>> float('9007199254740993.0')
>> 9007199254740992.0
>> 
>> Notice the last digit switched from a 3 to a 2?  Floats in python don't
>> have arbitrary accuracy.  You would need to import decimal and use it
>> for rounding to work properly.
> 
> Indeed, you are right.
> 
> See my reply to Terry Reedy in this thread, for more accuracy we should do
> this:
> 
>>>> def strtoint(s):
> ...     elts = s.split('.')
> ...     number = int(elts[0])
> ...     if len(elts)>1:
> ...         if int(elts[1][0])>=5:
> ...             number += 1
> ...     return number
> 
>>>> s = '123456789012345678901.987654321'
>>>> strtoint(s)
> 123456789012345678902L
>>>> int(round(float(s)))
> 123456789012345683968L
>>>>

And if one whants to chose ',' as decimal point (in which case '.' becomes a 
seperator) and to remove space seperators, the function can be:

def strtoint(s, decelt='.'):
    decpoint_and_seperator = {
        '.': ',',
        ',': '.'
    }
    s = s.replace(' ', '')
    s = s.replace(decpoint_and_seperator[decelt], '')
    elts = s.split(decelt)
    number = int(elts[0])
    if len(elts)>1:
        if int(elts[1][0])>=5:
            number += 1
    return number

>>> strtoint('123,456,789,012,345,678,901.987,654,321')
123456789012345678902L
>>> strtoint('123 456 789 012 345 678 901.987 654 321')
123456789012345678902L

>>> strtoint('123.145.256.256.259.256.255,586 259 256', ',')
123145256256259256256L

So european notation decimals work.

-- 
Web Dreamer

[toc] | [prev] | [next] | [standalone]


#10025

FromGrant Edwards <invalid@invalid.invalid>
Date2011-07-21 14:13 +0000
Message-ID<j09c5r$sna$1@reader1.panix.com>
In reply to#10019
On 2011-07-21, Web Dreamer <webdreamer@nospam.fr> wrote:
> Leo Jay a ?crit ce jeudi 21 juillet 2011 11:47 dans 

> int(x.split('.')[0])
>
> But, the problem is the same as with int(float(x)), the integer number is
> still not as close as possible as the original float value.

Nobody said that "close as possible to the original float value" was
the goal.  Perhaps the OP just wants it truncated.

-- 
Grant Edwards               grant.b.edwards        Yow! OVER the underpass!
                                  at               UNDER the overpass!
                              gmail.com            Around the FUTURE and
                                                   BEYOND REPAIR!!

[toc] | [prev] | [next] | [standalone]


#10045

FromTerry Reedy <tjreedy@udel.edu>
Date2011-07-21 16:00 -0400
Message-ID<mailman.1333.1311278441.1164.python-list@python.org>
In reply to#10025
On 7/21/2011 10:13 AM, Grant Edwards wrote:
> On 2011-07-21, Web Dreamer<webdreamer@nospam.fr>  wrote:
>> Leo Jay a ?crit ce jeudi 21 juillet 2011 11:47 dans
>
>> int(x.split('.')[0])
>>
>> But, the problem is the same as with int(float(x)), the integer number is
>> still not as close as possible as the original float value.
>
> Nobody said that "close as possible to the original float value" was
> the goal.  Perhaps the OP just wants it truncated.

The OP did not specify the domain of possible inputs nor the desired 
output for all possible inputs. Without that, function design is 
guessing. The appropriate response to the original post would have been 
a request for clarification.

If the domain is strings with and int followed by '.0', then chopping 
off two chars is sufficient. This was sort of implied by the original 
post, since it was the only example, and assumed by the respondant.

If the domain is int literals followed by '.' and some number of zeroes, 
then split works. So does int(float(s)). Split also works for non-digits 
following '.' whereas int(float(s)) does not.

If the domain is all float literals, then ??????.

-- 
Terry Jan Reedy

[toc] | [prev] | [next] | [standalone]


#10073

FromFrank Millman <frank@chagford.com>
Date2011-07-21 22:55 -0700
Message-ID<fc7c6c59-d1ae-4e01-8f62-369f0db1d167@a31g2000vbt.googlegroups.com>
In reply to#10045
On Jul 21, 10:00 pm, Terry Reedy <tjre...@udel.edu> wrote:
> On 7/21/2011 10:13 AM, Grant Edwards wrote:
>
> > On 2011-07-21, Web Dreamer<webdrea...@nospam.fr>  wrote:
> >> Leo Jay a ?crit ce jeudi 21 juillet 2011 11:47 dans
>
> >> int(x.split('.')[0])
>
> >> But, the problem is the same as with int(float(x)), the integer number is
> >> still not as close as possible as the original float value.
>
> > Nobody said that "close as possible to the original float value" was
> > the goal.  Perhaps the OP just wants it truncated.
>
> The OP did not specify the domain of possible inputs nor the desired
> output for all possible inputs. Without that, function design is
> guessing. The appropriate response to the original post would have been
> a request for clarification.
>
> If the domain is strings with and int followed by '.0', then chopping
> off two chars is sufficient. This was sort of implied by the original
> post, since it was the only example, and assumed by the respondant.
>
> If the domain is int literals followed by '.' and some number of zeroes,
> then split works. So does int(float(s)). Split also works for non-digits
> following '.' whereas int(float(s)) does not.
>
> If the domain is all float literals, then ??????.
>
> --
> Terry Jan Reedy

As the OP, I will clarify what *my* requirement is. This discussion
has gone off at various tangents beyond what I was asking for.

As suggested above, I am only talking about a string containing int
literals followed by '.' followed by zero or more zeros.

I think that there is a case for arguing that this is a valid
representation of an integer. It would therefore not be unreasonable
for python to accept int('165.0') and return 165. I would expect it to
raise an exception if there were any non-zero digits after the point.

However, the fact is that python does not accept this, and I am not
asking for a change.

int(float(x)) does the job, and I am happy with that. I was just
asking if there were any alternatives.

Frank

[toc] | [prev] | [next] | [standalone]


#10104

FromHrvoje Niksic <hniksic@xemacs.org>
Date2011-07-22 14:42 +0200
Message-ID<87vcuusd0j.fsf@xemacs.org>
In reply to#10073
Frank Millman <frank@chagford.com> writes:

> int(float(x)) does the job, and I am happy with that. I was just
> asking if there were any alternatives.

int(float(s)) will corrupt integers larger than 2**53, should you ever
need them.  int(decimal.Decimal(s)) works with numbers of arbitrary
size.

[toc] | [prev] | [next] | [standalone]


#10140

Fromrantingrick <rantingrick@gmail.com>
Date2011-07-22 12:32 -0700
Message-ID<a62defdf-e88b-485e-9f7b-47b47624024d@12g2000yqr.googlegroups.com>
In reply to#10104
On Jul 22, 7:42 am, Hrvoje Niksic <hnik...@xemacs.org> wrote:
> Frank Millman <fr...@chagford.com> writes:
> > int(float(x)) does the job, and I am happy with that. I was just
> > asking if there were any alternatives.
>
> int(float(s)) will corrupt integers larger than 2**53, should you ever
> need them.  int(decimal.Decimal(s)) works with numbers of arbitrary
> size.

Correct!

>>> '{0:,.0f}'.format(2**53)
'9,007,199,254,740,992'

That's nine-quadrillion people! Only for galactic measurements or
microscopic reasons would you need such large numbers.

PS: GAWD i love that new string format function!

[toc] | [prev] | [next] | [standalone]


Page 1 of 3  [1] 2 3  Next page →

Back to top | Article view | comp.lang.python


csiph-web