**(1/2),math.sqrt和cmath.sqrt之间的区别? [英] Difference between **(1/2), math.sqrt and cmath.sqrt?

查看:421
本文介绍了**(1/2),math.sqrt和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:

  1. cmath 提供对复数的数学函数的访问"
  2. 数学函数不能与复数一起使用;请使用如果您需要支持复数,则使用cmath模块中的相同名称."
  3. (**)运算符地图pow函数,但重要的区别在于pow将其参数转换为浮点数.
  1. cmath "provides access to mathematical functions for complex numbers"
  2. 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."
  3. The (**) operator maps to the pow function, with the important difference that pow 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆