How to write this equation in Python?

Cardano triplets

I really don't know how to write it down 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 have to get True for 2, 1, 5 , but it is not. What is wrong with my function?

+5
source share
2 answers

By doing a bit of research and calculation, solving the equation for the variable c , I found out that

lolz

and therefore

lolzz

Now, due to the oddness of floating point arithmetic in binary systems for well-known reasons , the first formula is quite difficult to accurately calculate. However, the second one is much simpler to calculate floating point accuracy without errors, since it does not include 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) True 
+6
source

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 .

+1
source

Source: https://habr.com/ru/post/1247469/


All Articles