Python的pow函数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python的pow函数相关的知识,希望对你有一定的参考价值。
为何pow(-2,1/3)的结果是个奇怪的虚数: (0.6299605249474367+1.0911236359717214j)
而pow(2,1/3)的结果是正确的:
1.2599210498948732
pow(-8,1/3)也是如此:
(1.0000000000000002+1.7320508075688772j)
如果用math.pow,直接提示:
ValueError: math domain error
没看懂啊
洗洗睡了去吧,别在这里复制粘贴了
参考技术A 结果都是正确的啊,如果觉得不对请去补补数学? 既然负数开根号自然会有虚部出现以(-2)**(1/3)为例,这个复数的实部=cos(1/3*pi)*2**(1/3),虚部=sin(1/3*pi)*2**(1/3)。追问
-2开三次方根没有实数解?-8开三次方根没有实数解?
(-1.26)^3 ≈ -2 手算都能算出来
(-2)^3 = 8 这个算都不用算吧
我已经找到答案了,百度知道的人都是些答非所问,自以为是的傻X
“计算机中浮点数储存皆有精度限制,1/3算完后temp实为0.33333333333333再换成十进制后分母为偶数,因此样例56开出来为复数”
如果你对函数是这样理解的话,那还学什么py,拿个mathematica用得多开心。根本原因也并不在于精度,因为你只要用计算机就该有精度有限的准备
幂函数不单是用来算三次方根的,并不在乎特例,用复数实现无疑是最佳之选。只算三次方根请找cbrt
只能送你7个字:自以为是的傻屌
参考技术B别用函数,直接 ** 简洁明了
-256**(1/4)本回答被提问者采纳
一个数number的n次幂 python的pow函数
@
实现 pow(x, n),即计算 x 的 n 次幂函数。其中n为整数。
链接: pow函数的实现——leetcode.
解法1:暴力法
不是常规意义上的暴力,过程中通过动态调整底数的大小来加快求解。代码如下:
def my_pow(number, n):
judge = True
if n < 0:
n = -n
judge = False
if n == 0:
return 1
result = 1
count = 1
temp = number
while n > 0:
if n >= count:
result *= temp
temp = temp * number
n -= count
count += 1
else:
temp /= number
count -= 1
return result if judge else 1/judge
解法2:根据奇偶幂分类(递归法,迭代法,位运算法)
如果n为偶数,则pow(x,n) = pow(x^2, n/2);
如果n为奇数,则pow(x,n) = x*pow(x^2, (n-1)/2)。
class MyPow:
def my_pow(self, number, n):
if n < 0:
n = -n
return 1/self.help_(number, n)
return self.help_(number, n)
def help_(self, number, n):
if n == 0:
return 1
if n%2 == 0:
return self.help_(number*number, n//2)
return self.help_(number*number, (n-1)//2)*number
迭代代码如下:
class MyPow:
def my_pow(self, number, n):
judge = True
if n < 0:
n = -n
judge = False
result = 1
while n > 0:
if n%2 == 0:
number *= number
n //= 2
result *= number
n -= 1
return result if judge else 1/result
其实跟上面的方法类似,只是通过位运算符判断奇偶性并且进行除以2的操作(移位操作)。代码如下:
class Solution:
def myPow(self, x: float, n: int) -> float:
judge = True
if n < 0:
n = -n
judge = False
final = 1
while n>0:
if n & 1: #代表是奇数
final *= x
x *= x
n >>= 1 # 右移一位
return final if judge else 1/final
以上是关于Python的pow函数的主要内容,如果未能解决你的问题,请参考以下文章