Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This is a fun numpy quirk:

    >>> 'x'*3.5
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: can't multiply sequence by non-int of type 'float'
    >>> import numpy as np 
    >>> print 'x'*np.float64(3.5) 
    xxx


As an occasional numpy contributor, I would call this a bug.


Yes, the expected output is xx›


  xxx›


xxxₓ


xxxv, actually.

(it makes sense if you know why Roman numerals look the way they do)


Good point - I found it after it caused a really weird bug in a library I use. I'll open an issue on github...


Turns out it's deprecated:

    >>> import warnings
    >>> warnings.simplefilter('always')
    >>> 'x'*np.float64(3.5)
    __main__:1: DeprecationWarning: using a non-integer number instead of an integer will result in an error in the future
    'xxx'


I get no such warning with 2.7.9 on linux.


It would be a warning from numpy, not Python. That comes from numpy/core/src/multiarray/conversion_utils.c and was added 2013-04-13 , which would be for NumPy 1.8, I believe.


I use R predominantly, so forgive the lack of adequate Python-ese.

Is this behavior because numpy overloads the multiplication operation with a string as string repetition and then implicitly casts the float64 down to an integer of 3? I'm curious why this behavior manifests. When I get a chance I'll test 'xyz'*np.float(3.5)


It's "normal" in python for this to work with integers:

    >>> "x" * 3
    xxx
The only weird part (and it's not that weird IMO) is that numpy's "float" can be implicitly coerced to integer.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: