gpt4 book ai didi

python - 在 Python 中使用 math.sqrt(num) 比 num**0.5 有什么优势吗

转载 作者:行者123 更新时间:2023-11-28 22:52:41 24 4
gpt4 key购买 nike

我看到人们通常使用 math计算平方根的库,我想知道与普通 **0.5 相比是否有优势(matissa 或计算效率) ?

好的也做了快速测试,cpu时间趋于均等

import time 

start_time = time.clock()

i = 0
while i < 10000000:
i ** 0.5
i += 1

elapsed_time = time.clock() - start_time
print ("Time elapsed: {} seconds".format(elapsed_time))

已用时间:7.27 秒

import time 
import math

start_time = time.clock()

i = 0
while i < 10000000:
math.sqrt(i)
i += 1

elapsed_time = time.clock() - start_time
print ("Time elapsed: {} seconds".format(elapsed_time))

耗时:7.109999999999999 秒

最佳答案

他们的行为有细微的差别。 x**n 首先尝试 x.__pow__(n)。如果该调用返回 NotImplemented,则调用 n.__rpow__(x)

>>> (2).__pow__(0.5)
NotImplemented
>>> (0.5).__rpow__(2)
1.4142135623730951

math.sqrt(x) 将 x 转换为 float (幕后的 C double),然后调用 C 数学库。

>>> class F(object):
... def __init__(self, value):
... self.value = value
... def __float__(self):
... print("hi!")
... return float(self.value)
...
>>> a=F(2)
>>> math.sqrt(a)
hi!
1.4142135623730951

对于 Python 中的普通数字类型,这种差异通常并不重要,但其他数字类型的行为可能有所不同。 gmpy2 实现整数和 float 的任意精度算法。导致 math.sqrt() 溢出的值可以由 ** 处理。

>>> import gmpy2
>>> math.sqrt(gmpy2.mpz("1"*999))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: 'mpz' too large to convert to float
>>> gmpy2.mpz("1"*999)**0.5
mpfr('1.0540925533894598e+499')
>>>

关于python - 在 Python 中使用 math.sqrt(num) 比 num**0.5 有什么优势吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20226747/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com