Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
648 views
in Technique[技术] by (71.8m points)

python - Different behavior of arithmetics on dtype float 'object' and 'float'

Hi guys im just a rookie in python (even in programming) so my question might sound very basic but i have a hard time to understand this.

Why is the selective behavior on arithmetics on 'float object'?

import numpy as np

a = np.random.normal(size=10)
a = np.abs(a)
b = np.array(a, dtype=object)

np.square(a) # this works
np.square(b) # this works

np.sqrt(a) # this works
np.sqrt(b) # AttributeError: 'float' object has no attribute 'sqrt'

The image link is my run result in local jupyter notebook:

jupyter notebook run result enter image description here

Appreciate useful insights! thanks


edit 050418 09:53 --add a link that i think is similar issue Numpy AttributeError: 'float' object has no attribute 'exp'

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

@Warren points out that square 'delegates' to multiply. I verified this by making an object array that includes a list:

In [524]: arr = np.array([np.arange(3), 3, [3,4]])
In [525]: np.square(arr)
TypeError: can't multiply sequence by non-int of type 'list'

square works on the rest of the array:

In [526]: np.square(arr[:2])
Out[526]: array([array([0, 1, 4]), 9], dtype=object)

sqrt doesn't work on any of these:

In [527]: np.sqrt(arr)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-527-b58949107b3d> in <module>()
----> 1 np.sqrt(arr)

AttributeError: 'numpy.ndarray' object has no attribute 'sqrt'

I can make sqrt work with a custom class:

class Foo(float):
    def sqrt(self):
        return self**0.5

In [539]: arr = np.array([Foo(3), Foo(2)], object)
In [540]: np.square(arr)
Out[540]: array([9.0, 4.0], dtype=object)
In [541]: np.sqrt(arr)
Out[541]: array([1.7320508075688772, 1.4142135623730951], dtype=object)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...