我在 Stackoverflow 上找到了以下答案:
https://stackoverflow.com/a/356187/1829329
但它仅适用于 n 根中的 n 整数:
import gmpy2 as gmpy
result = gmpy.root((1/0.213), 31.5).real
print('result:', result)
结果是:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-14-eb4628226deb> in <module>()
8
----> 9 result = gmpy.root((1/0.213), 31.5).real
10
11 print('result:', result)
TypeError: root() requires 'mpfr','int' arguments
计算这样一个根的好方法是什么?(这是一些公式的python代码表示,我需要在讲座中使用它来计算。)
编辑#1
这是我的解决方案,基于http://math.stackexchange.comSpektre
上人们的回答和信息。
import numpy as np
def naive_root(nth, a, datatype=np.float128):
"""This function can only calculate the nth root, if the operand a is positive."""
logarithm = np.log2(a, dtype=datatype)
exponent = np.multiply(np.divide(1, nth, dtype=datatype), logarithm, dtype=datatype)
result = np.exp2(exponent, dtype=datatype)
return result
def nth_root(nth, a, datatype=np.float128):
if a == 0:
print('operand is zero')
return 0
elif a > 0:
print('a > 0')
return naive_root(nth, a, datatype=datatype)
elif a < 0:
if a % 2 == 1:
print('a is odd')
return -naive_root(nth, np.abs(a))
else:
print('a is even')
return naive_root(nth, np.abs(a))