理解 sqrt 的行为——写不同时给出不同的结果

问题描述

我有以下数字的熊猫系列:

0   -1.309176
1   -1.226239
2   -1.339079
3   -1.298509
...

我正在尝试计算系列中每个数字的平方根。

当我尝试整个系列时:

s**0.5
>>>
0       NaN
1       NaN
2       NaN
3       NaN
4       NaN
         ..
10778   NaN

但如果我取数字就行了:

-1.309176**0.5

我也尝试从系列中切出数字:

b1[0]**0.5
>>>
nan

所以我试图理解为什么它在我写数字时有效,但在我使用系列时无效

*值是浮点型:

s.dtype
>>>dtype('float64')

s.to_frame().info()
>>>
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10783 entries,0 to 10782
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   B1      10783 non-null  float64
dtypes: float64(1)
memory usage: 84.4 KB

解决方法

你不能求负数的平方根(不尝试复数)。

>>> np.sqrt(-1.30)
<stdin>:1: RuntimeWarning: invalid value encountered in sqrt
nan

当您执行 -1.309176**0.5 时,您实际上是在执行 -(1.309176 ** 0.5),这是有效的。

,

这与python中的运算符优先级有关。 ** 的优先级 > 一元运算符 -

负数的平方根应该是复数。但是当您计算 -1.309176**0.5 时,它首先计算 1.309176**0.5,然后减去它,因为 ** 的优先级是 > -

>>>1.309176**0.5
-1.144192291531454

>>> (-1.309176)**0.5
(7.006157137165352e-17+1.144192291531454j)

现在您的系列中的数字已经是负数,这不像您正在对它们进行一元运算 - 因此这些数字的平方根应该是复数系列显示为 nan 因为数据类型为 float

>>> s = pd.Series([-1.30,-1.22])
>>> s
0   -1.30
1   -1.22
dtype: float64

这个系列的平方根给出 nan

>>> s**0.5
0   NaN
1   NaN
dtype: float64

dtype 改为 np.complex

>>> s = s.astype(np.complex)
>>> s
0   -1.300000+0.000000j
1   -1.220000+0.000000j
dtype: complex128

现在你得到了 s 的平方根。

>>> s**0.05
0    1.000730+0.158500j
1    0.997557+0.157998j
dtype: complex128