[Tutor] list output -- float output

spir denis.spir at free.fr
Fri Nov 14 20:07:01 CET 2008


Thank you for the advice.
Actually, what annoys me is that list textual output, either with print or 
str(), calls repr() for each item of the list, instead of str(). That's why I 
had these strange things with floats, as illustrated in my first post on the topic:

class Seq(list):
	''' sequence for proper output of items '''
	def __str__(self):
		if len(self) == 0:
			return '[]'
		text = str(self[0])
		for item in self[1:]:
			if isinstance(item, list):
				item = Seq(item)
			text += " ,%s" %item
		return "[%s]" %text

l = [1, 1.1, [1, 1.1]]
s= Seq(l)
print "repr:%s str:%s\nl: %s\ns:%s" %(repr(1.1), str(1.1), l, s)

==>
repr:1.1000000000000001 str:1.1
l: [1, 1.1000000000000001, [1, 1.1000000000000001]]
s:[1 ,1.1 ,[1 ,1.1]]

Lie Ryan a écrit :
> On Fri, 14 Nov 2008 15:21:17 +0100, spir wrote:
>> Well, actually not really I guess. I asked for rounded floats, not
>> full-precision ones.
>> Now, after more reflexion on the topic, I understand that even rounded
>> floats need to keep full precision internally, because of the 'modular'
>> difference between decimal and binary representations that causes
>> 'epsilon' errors; which still applies on rounded floats, for the
>> rounding operates at the decimal level. In other words, (decimal)
>> rounding does not eliminate the source of 'little errors' -- it should
>> be binary rounding instead, but this is probably not very useful for us
>> in the real world ;-). The reason why repr(), that shows inner
>> representation, is still full of junk digits for rounded floats, while
>> str() shows the expected format. denis
> 
> 
> If you wanted a more controllable precision and can tolerate being a bit 
> slow, you can use the Decimal module instead.
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 




More information about the Tutor mailing list