【问题标题】:How to get both (plus and minus) square roots如何获得(正负)平方根
【发布时间】:2014-07-27 14:27:33
【问题描述】:

我想使用 python 找到一个数字的两个平方根。我的简单代码是:

#!/usr/bin/env python
import numpy as np
x = 4.0
print 'Square roots of',x,'are:',np.sqrt(x)

这给了我以下输出:

Square roots of 4.0 are: 2.0

但我也想在答案中看到-2.0,即 4 的平方根将是 +/- 2,而不仅仅是 +2。

在更广泛的问题中,我想绘制一个函数f(x)=sqrt(x)。我想一次捕捉抛物线的两个分支。现在的代码是:

#!/usr/bin/env python
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0.0, 16.0, 0.2)
f = np.sqrt(x)
plt.plot(x, f)
plt.show()

它不会在负 y 轴上绘制值。是否可以在不玩任何技巧的情况下这样做(例如,第二次为它分配一个减号)?我不必使用numpy

【问题讨论】:

  • 您需要以某种自动化方式获取它吗?说 0 - np.sqrt(x) 很容易。
  • 或者只是-np.sqrt(x)
  • 为什么不x = np.linspace(-4.0, 4.0, 200); plt.plot(x**2, x)
  • 可能你没有得到这个问题。有没有可能把两个根放在一起。假设我有一个函数,它的定义中有几个平方根。不可能为每次出现单独定义它们。人们,除非您确定问题的愚蠢性,否则请不要投反对票。至少等cmets回来吧。
  • @hbaromega:听起来您提出的实际问题与您想要回答的问题不同。 :-)

标签: python python-2.7 numpy sqrt


【解决方案1】:

我认为 OP 对此有点困惑:4 的平方根是 +/-2,为什么 numpy.sqrt 只给出正数?

但是这个在功能描述里有明确定义:

Returns
-------
y : ndarray
    An array of the same shape as `x`, containing the positive
    square-root of each element in `x`.  ...

您可以在 python shell 中使用numpy.info(numpy.sqrt) 看到此消息。

由于每个正数都有一对平方根,如果你想全部打印出来,只需将print语句更改为:

print 'Square roots of',x,'are: +/-',np.sqrt(x)

【讨论】:

  • 对不起,这不是答案。这只是一个技巧。我已经修改了我的问题,以使动机更加清晰。另请参阅上面的我的 cmets。我已经询问了一种可能性,或者某些 python 库中是否存在任何函数。如果答案是,我不介意接受。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 2021-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-11
相关资源
最近更新 更多