The power operator ( ** ) has a higher priority than division ( / ). So you need to set the parentheses:
f = lambda x: x ** (1./3)
However, floating point operations are not accurate, so you need to compare with some slight uncertainty:
def is_cardano_triplet(a, b, c): f = lambda x: x ** (1. / 2) g = lambda x: x ** (1. / 3) return abs(g(a + b*f(c)) + g(a - b*f(c)) - 1) < 1e-10
Now you get the problem that negative numbers are only allowed for the roots of odd numbers, but floating points are not exact, so you have to manually handle the negative numbers:
def is_cardano_triplet(a, b, c): f = lambda x: x ** (1. / 2) g = lambda x: (-1 if x<0 else 1) * abs(x) ** (1. / 3) return abs(g(a + b*f(c)) + g(a - b*f(c)) - 1) < 1e-10
Now
print is_cardano_triplet(2,1,5)
leads to True .
source share