python中的平方根
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15391748/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Square roots in python
提问by confused
>>> import math
>>> math.sqrt(4)
2.0
Why does Python not give the negative square roots (as -2 is also a square root of 4)?
And how can I make Python to give out negative square roots?
为什么 Python 不给出负平方根(因为 -2 也是 4 的平方根)?
我怎样才能让 Python 给出负平方根?
采纳答案by mgilson
How about:
怎么样:
def my_sqrt(x):
root1 = math.sqrt(x)
root2 = -root1
return root1,root2
回答by Abhijit
If you need all the roots of a number, you can use numpy.root
如果你需要一个数字的所有根,你可以使用numpy.root
>>> import numpy
>>> def root(n, r):
p = [1] + [0] * (r - 1) + [-n]
return numpy.roots(p)
>>> root(4, 2)
array([ 2., -2.])
>>> root(-4, 2)
array([ 0.+2.j, 0.-2.j])
>>> root(1, 3)
array([-0.5+0.8660254j, -0.5-0.8660254j, 1.0+0.j ])
Another option is to use Sympy Polynomial Module
另一种选择是使用Sympy Polynomial Module
>>> from sympy import symbols, solve
>>> solve(x**2 - 4)
[-2, 2]
>>> from sympy import symbols, solve
>>> solve(x**2 - 4)
[-2, 2]
>>> solve(x**3 - 1)
[1, -1/2 - sqrt(3)*I/2, -1/2 + sqrt(3)*I/2]
>>> solve(x**2 + 4)
[-2*I, 2*I]
回答by Stuart
This is not something that's unique to Python, or to the square root function. This is an issue that comes up any time we are dealing with the inverse of a function that is not "injective". See http://en.wikipedia.org/wiki/Injective_function
这不是 Python 或平方根函数独有的东西。每当我们处理非“内射”函数的反函数时,都会出现这个问题。见http://en.wikipedia.org/wiki/Injective_function
That is, the inverse of any function in which more than one value of x the maps to the same value of y, y=x**2 being just one example.
也就是说,任何函数的反函数,其中多个 x 值映射到相同的 y 值,y=x**2 只是一个例子。
You could make the same complaint about many other functions, inverse sin (arcsin) for example. What is the value of "x" that make sin(x)=0.5? Even if we only consider a span of +/- 180 degrees (+/- pi) then there are two solutions, x=30 degrees and x=150 degrees. But implementations of inverse sin will always return only 30 degrees (pi/6). If we want the "other inverse" then we usually just use our knowledge of the particular function to obtain it.
您可以对许多其他函数提出同样的抱怨,例如 inverse sin (arcsin)。使 sin(x)=0.5 的“x”的值是多少?即使我们只考虑 +/- 180 度 (+/- pi) 的跨度,也有两种解决方案,x=30 度和 x=150 度。但是逆罪的实现将始终只返回 30 度 (pi/6)。如果我们想要“另一个逆”,那么我们通常只使用我们对特定函数的知识来获得它。
For inverse square (sqrt) it's as simple as slapping a unary minus in front of it. For inverse sin, its taking the supplementary angle, pi-arcsin(0.5) for example.
对于平方反比 (sqrt),它就像在它前面打一个一元减号一样简单。对于反sin,以补角pi-arcsin(0.5)为例。

