**(1/2),math.sqrt和cmath.sqrt之间的区别? [英] Difference between **(1/2), math.sqrt and cmath.sqrt?
问题描述
x**(1/2)
,math.sqrt()
和cmath.sqrt()
有什么区别?
为什么cmath.sqrt()
仅凭二次就得到复数的根?我应该专门用于平方根吗?他们在后台有何不同之处?
Why does cmath.sqrt()
get complex roots of a quadratic right alone? Should I use that for my square roots exclusively? What do they do in the background differently?
推荐答案
如果分别查看cmath和math的文档,您会发现:
If you look at the documentation for cmath and math respectively, you will find that:
- cmath 提供对复数的数学函数的访问"
- 数学函数不能与复数一起使用;请使用如果您需要支持复数,则使用cmath模块中的相同名称."
-
(**)
运算符地图到pow
函数,但重要的区别在于pow
将其参数转换为浮点数.
- cmath "provides access to mathematical functions for complex numbers"
- math "functions cannot be used with complex numbers; use the functions of the same name from the cmath module if you require support for complex numbers."
- The
(**)
operator maps to thepow
function, with the important difference thatpow
converts its arguments to float.
因此,对于三个参数使用相同的参数,您可能会看到不同的结果,如此处所示.请注意,如果表达式具有实数解,则math.sqrt
返回的值与cmath.sqrt
返回的实数部分之间将没有区别.但是,如果没有可用的实际解决方案,则会出现math.sqrt
错误.
Hence, you may see different results with the three functions for same arguments, as demonstrated here. Please note that if the expression has a real solution, there will be no difference between the value returned by math.sqrt
and the real part of the value returned by cmath.sqrt
. However, you will get an error with math.sqrt
if no real solution is available.
正如@jermenkoo指出的那样,由于/
运算符的工作方式不同,因此Python 2和3之间(**)
返回的值会有差异.但是,如果直接使用0.5而不是1/2,那应该不会引起问题.
As @jermenkoo points out, there will be a difference in the value returned by (**)
between Python 2 and 3 due to the difference in how the /
operator works. However, if you directly use 0.5 instead of 1/2, that should not cause issues.
这篇关于**(1/2),math.sqrt和cmath.sqrt之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!