1

Let's say I have operator A and operator B which act on f(x) = 2x for example. How do I create a function that says whether A(B(f(x))) == B(A(f(x))) in python?

Here is my attempt:

#Commutation: Creating a function that checks whether operators A and B commutate on some dummy function f(x) = 2*x
#[A,B](2x) =?= 0

def commutate(A,B):
    f = lambda x: 2*x
    if lambda x: A(B(f)) - B(A(f)) == 0:
        print('A and B commute!')
    else:
        print('A and B do not commute!')
         
A = lambda x: f(x)**2

B = lambda x: np.log(f(x))


commutate(A,B)

The issue is that I'm always getting that the operators A and B commute, even when giving Operators that don't. I suspect this might have to do with the fact that I can't Define operators like that in python?

2
  • 6
    You're just checking to see if a lambda expression is truthy, so the answer is always yes. The thing that I think you're trying to do (subtract a function from another) doesn't work; if your order of operations was correct for what you're trying to do, you'd see ` TypeError` telling you that you can't subtract functions from each other. Commented Mar 31, 2021 at 20:40
  • 1
    Numerically you could check if A(B(x)) and B(A(x)) produce the same result for different x values. But this way you can only prove that they are different, for equality you will need actual algebra. Commented Mar 31, 2021 at 20:43

2 Answers 2

3

In general, it is not possible, based on Rice theorem. Because you desire to check a non-trivial property for two pieces of code, i.e., the property is commutativeness and piece of code here means functions. Hence, it proves that deciding that "any given f and g functions are commutative" is undecidable. Therefore, you can't write such a function to check the commutativeness for two functions.

Sign up to request clarification or add additional context in comments.

Comments

1

In your code you have the line

if lambda x: A(B(f)) - B(A(f)) == 0:

In this line you are generating a lambda that is calling the operators on the address of f rather than a result of calling f. Also, you are not calling the lambda that you define in the if statement, so you are checking if the address of the lambda function is True/False which is not what you are looking for.

Lambdas are just functions, but you could test if the operators are commutative on a specific value:

def commutate(A, B, value):
    f = lambda x: 2 * x
    if A(B(f(value))) == B(A(f(value))):
        print(f"A and B commute on value {value}!")
    else:
        print(f"A and B do not commute on value {value}!")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.