我喜欢将Python集成到函数的探索中,但是我遇到了一种行为,这是我所不希望或不希望看到的。
>>> def h(x):
... return -1 / x**(1/3)
...
>>> h(-343)
(-0.07142857142857145 + 0.12371791482634838j)我想要一个与以下函数相反的事实:
>>> def f(x):
... return x**3
...
>>> f(-7)
-343使:
>>> def h(x):
... return -1/inverse_f(x)
...
>>> h(-343)
0.14285714285714285有什么毕达通的方法可以得到这种行为吗?
发布于 2017-01-04 07:35:58
如果您只想在整数中工作(并忽略函数的复杂解决方案),这可能是一种方法。至少对于标题中的例子来说,它可以做你想做的事情。(因此,这只是针对你问题的标题;由于其他问题已经改变,它将无助于.Nayuki的回答会)
gmpy2有一个iroot方法:
import gmpy2
print(gmpy2.iroot(343, 3)) # -> (mpz(7), True)从那里开始,您应该能够组合您的功能。
import gmpy2
from fractions import Fraction
def h(x):
sign = 1 if x >= 0 else -1
root, is_int = gmpy2.iroot(abs(x), 3)
if not is_int:
return None # the result is not an integer
root = int(root)
return -sign * Fraction(1, root)
print(h(-343)) # -> 1/7反之亦然:
def g(x):
return -Fraction(1, x**3)
print(g(h(-343))) # -> -343https://stackoverflow.com/questions/41458263
复制相似问题