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?
lambdaexpression 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.A(B(x))andB(A(x))produce the same result for differentxvalues. But this way you can only prove that they are different, for equality you will need actual algebra.