[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:


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()
>>> x = random.random()
>>> x
>>> print x
>>> str(x)
>>> print str(x)
>>> repr(x)
>>> str(repr(x))

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.



[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>

More information about the New-bugs-announce mailing list