Deneb Deneb - 2 years ago 164
Python Question

How do I write this equation in Python?

Cardano Triplets

I really don't know how to write this correctly. This is how I tried:

def is_cardano_triplet(a, b, c):
f = lambda x: x ** 1. / 2
g = lambda x: x ** 1. / 3
return g(a + b*f(c)) + g(a - b*f(c)) == 1

print is_cardano_triplet(2,1,5) # I should get True

I should get
2, 1, 5
, but I'm not. What's wrong with my function?

Answer Source

Doing a bit of research and calculations, solving the equation for the variable c, I found out that


and therefore


Now, due to floating point arithmetic being imprecise on binary-based systems for known reasons, the first formula is pretty hard to compute precisely. However, the second one is much easier to compute without floating point precision errors since that it doesn't involve irrational functions and a, b and c are integers.

Here's the smart solution:

def is_cardano_triplet(a, b, c):
    return (a + 1)**2 * (8*a - 1) - 27*b**2*c == 0

>>> is_cardano_triplet(2, 1, 5)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download