The expression, total = 2 ^ 1 - 1
, returns 2
.
Could anyone explain why it returns 2
?
Doesn't it suppose to return 1
?
What is the difference between this and using math function?
total = (math.pow(2,1) - 1)
The expression, total = 2 ^ 1 - 1
, returns 2
.
Could anyone explain why it returns 2
?
Doesn't it suppose to return 1
?
What is the difference between this and using math function?
total = (math.pow(2,1) - 1)
That's the "Bitwise Exclusive Or" operator, not the power/exponent operator.
So for your example, it converts the decimal values to binary, and then does XOR on each bit (where matching values are false and contradicting values are true). total = 10
(2decimal) xor 01
(1 decimal) = 11
(3 decimal). Subtract 1 and you get 2, as expected.
The operator your thinking of is "Exponentiation" ie total = 2**1 - 1
If you haven't, you'll learn about this in discrete math.
^
is the bitwise XOR operator in Python, not the power function.
Doing 2 ^ 1
does the following:
10 # 2 in binary
01 # 1 in binary
---
11 # exclusive or
Which results in 3 in decimal, subtracted by 1 gives 2.
The math function is the proper power function. Alternatively, you can use **
for exponentiation, as in 2**1
.