[New-bugs-announce] [issue16609] random.random() / float() loses precision when passed to str()

Cal Leeming report at bugs.python.org
Tue Dec 4 20:03:07 CET 2012


New submission from Cal Leeming:

Hello,

Today I came up against a strange problem where collisions were being encountered after less than 1mil iterations when attempting to use random.random().

After much digging, the problem was because I was casting my float to a string, and this was automatically rounding it.

Some explanation is given [1], but it still leaves me with questions.

>>> import random
>>> random.random()
0.33885573194811902
>>> x = random.random()
>>> x
0.88022393777095409
>>> print x
0.880223937771
>>> str(x)
'0.880223937771'
>>> print str(x)
0.880223937771
>>> repr(x)
'0.88022393777095409'
>>> str(repr(x))
'0.88022393777095409'

After painstakingly searching through documentation (including the lengthy one about floating points arithmetic), I was unable to find any explanation behind why the float is automatically rounded if str() is called on it.

Although I doubt this behavior would ever be changed, it would be nice to update the documentation to reflect this. I'm thinking a note underneath random.random() explaining that you have to use repr() and not str() in order to maintain floating point precision.

Thoughts?

Cal

[1] http://stackoverflow.com/questions/3481289/converting-a-python-float-to-a-string-without-losing-precision

----------
components: Interpreter Core
messages: 176930
nosy: sleepycal
priority: normal
severity: normal
status: open
title: random.random() / float() loses precision when passed to str()
versions: Python 2.7

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue16609>
_______________________________________


More information about the New-bugs-announce mailing list