-
-
Notifications
You must be signed in to change notification settings - Fork 31.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Let bin/oct/hex show floats #47258
Comments
Let bin() show floating point values. This would contribute quite a def vis(f):
""" Show binary representation of a floating point number: >>> vis(math.pi)
'0b11.001001000011111101101010100010001000010110100011'
>>> vis(-0.375)
'-0b0.011'
"""
f, sign = (f, '') if f >= 0 else (-f, '-')
n, d = f.as_integer_ratio() if isinstance(f, float) else (f, 1)
n, d = map(lambda x: bin(x)[2:], (n, d))
n = n.rjust(len(d), '0')
s = list(n)
s.insert(len(n) - len(d) + 1, '.')
return sign + '0b' + ''.join(s) |
I'm not sure about the educational value of letting obscure bugs |
Or, if you want to educate people at all cost, the TypeError raised by |
I like the idea in general. It is way too common for people to be I don't think a promiscuous bin() will lead to obscure bugs. Antoine As far as the proposed implementation goes, I don't like the fact that If bin() is extended to floats, it may become confusing that hex() and |
Well it's quite simple. Imagine you have a function f() which takes an Right now, if you call f(1.0) instead of f(1), you will get a TypeError, With Raymond's suggestion, if you call f(1.0) instead of f(1), no There is a reason Python recently introduced a stronger distinction And it's not like printing the bin() representation of a float has any |
On Fri, May 30, 2008 at 10:52 AM, Antoine Pitrou <report@bugs.python.org> wrote:
This is too abstract. Depending on what f() is designed to do,
There is no "right now". Builtin bin is new in 2.6.
I think you are mistaken. Python always distinguished between floats Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: list indices must be integers
>>> int.__index__
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: type object 'int' has no attribute '__index__' __index__ was introduced in order to allow user-defined class
That's exactly my point. Builtin bin being new, I cannot comment on BTW, google code search quickly revealed the following antipattern: log.msg("real checksum: %s"%hex(hdr[19])) (twisted-Zope-3.2.2/twisted/words/protocols/toc.py) Surely "real checksum: %x" % hdr[19] would be a better choice. (The |
While writing my previous comments I did not realize that '%x' % accepts >>> "%x" % 3.1415
'3' Float support has been even improved somewhat since 2.5: Python 2.5 (r25:51908, Nov 24 2006, 11:03:50)
>>> '%x' % 1e10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int argument required The new stile formatting, however does not allow floats with either :x >>> "{0:x}".format(1.)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown conversion type x
>>> "{0:b}".format(1.)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown conversion type b I don't think anything needs to be done about it given that % formatting |
Sorry, my bad.
First I'm not sure bizarre log output should be considered "more I still find this proposal undesirable, for several reasons:
One related feature, though, would be to know whether a string
And witness how it does something rather intuitive (convert the argument |
On Fri, May 30, 2008 at 1:47 PM, Antoine Pitrou <report@bugs.python.org> wrote:
I fail to see how the proposed bin(..) can produce '0b11.00100..' from |
On Fri, May 30, 2008 at 1:47 PM, Antoine Pitrou <report@bugs.python.org> wrote:
You may have misunderstood the proposal. I read the proposal as |
What would you say to adding float-capable bin/oct/hex (+ maybe tobase) |
The term "layout" was probably badly chosen.
Oops, you are right. bin(3.0) would produce '0b11.', which is indeed |
Why not indeed. |
Better to just build-out bin() and be done with it. FWIW, the action on ints and floats is similar to how str() handles |
Ok, someone has to take a decision anyway. However, if you do that, it should be probably decided first what |
AFAICT, there is no good use case for showing floats in in hex or oct, |
Another problem with bin() on floats is that it will be a one-way street My last thought on this issue is that it will be helpful to add |
On Fri, May 30, 2008 at 2:32 PM, Antoine Pitrou <report@bugs.python.org> wrote:
.. because you rarely want to make your functions accept 1.0, but |
It is my impression that hexadecimal is more common than binary, in the For example: "Hexadecimal floating-point representations are especially important Or course, without hex float literals or an equivalent function for |
No need to conquer the whole world. Start with bin(1.1). If requests |
Kind of a cool hack. I am not sure how useful it is though. Personally, And if you allow bin() to accept floats, will you make Python accept |
Saving this for after the first beta goes out. |
To address the ideas brought-up so far, here's a new version that can def newbin(f):
"""
>>> newbin(3.125)
'0b11001 * 2.0 ** -3'
"""
n, d = f.as_integer_ratio()
s = '%s * 2.0 ** %d' % (bin(n), -math.log(d, 2.0))
return s |
The other reviewers asked for:
Attaching a patch with tests. |
I don't like this modification of a PyString object: + n = PyString_GET_SIZE(conv); The string may have other references (ex: all single-char strings are Also, tests should check if negative numbers have the same |
The patch looks good to me. It's a bit unfortunate that -0.0 doesn't round-trip correctly (the sign >>> eval(bin(-0.0))
0.0 I don't know whether it's worth special-casing this; the output would |
Hmm, I don't see a way to preserve -0.0 without varying from the Attaching an updated patch for Amaury's comments. |
I'm looking forward to your C implementation. |
Raymond, Mark? Is a new patch with tests and docs forthcoming? Have |
Mark, I'm tied-up with EuroPython until the 14th. Do you have time to |
I'm working on it. I expect to have something ready by the end of this |
BTW couldn't you use the %a feature built into C99 to implement this? |
Sure. What about non-C99 machines? I thought Python code was only |
On Fri, Jul 4, 2008 at 7:12 AM, Mark Dickinson <report@bugs.python.org> wrote:
I'm pretty sure that's a thing of the past. Ask MvL. |
Microsoft compilers implement %a since VS8.0. |
In the interests of getting early feedback, here's half a patch, Still to come: float.hex and documentation. I'll ask on python-dev about C99 and %a. |
That should be 'float.fromhex', not 'from.fromhex'. |
Here's an updated patch, complete with both float methods and |
Add updated patch with expanded documentation. |
Here's a slightly more polished version of the previous patch; no Let me know if there's anything I can do to help get this in before next |
Minor modifications to the previous patch, mostly to the docs. Setting priority to critical, since this really needs to go in before the |
Here's an updated patch that makes the trailing 'p123' exponent optional I'm beginning to wonder whether the '0x' shouldn't also be optional on >>> int('0x45', 16)
69
>>> int('45', 16)
69 This would then allow, e.g., >>> float.fromhex('45')
69.0 |
In the spirit of being "liberal in what you accept, but strict in what you Note that this version is still perfectly interoperable with C99 and Java |
Some final tinkering:
|
So far this looks good. Will complete the review on the next leg of my |
The patch looks good. I would coded hex_from_char() using a lookup Question: are the ("0x0p+0") and ("-0x0p+0") special cases standard? The docs need a "new in py2.6" Coding style: move the inner si++ to a separate line so there are no Question: should the "inf" string checks be made case sensitive on |
Here's an updated patch that addresses Raymond's concerns.
Done.
Not entirely. Java outputs "0x0.0p0" and "-0x0.0p0". The C99 standard I can change '0x0p+0' to '0x0.0p+0' if people think this looks prettier.
Fixed.
Done. (And the same with s++ in float_fromhex.)
Everything I've seen, except Java, seems to like case-insensitivity. (Java insists on infinity being spelt "Infinity", and nan being spelt Thank you for reviewing this, Raymond! I aim to check this in when (if?) I get approval from Barry. |
If you two can agree that this code is good, I'm ok with the API. I would emphasize in the docs and NEWS entry though that .hex() is an |
Mark, please go ahead and apply so the buildbots will have time to give |
Committed, r64974 |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: