0

Operators behave differently depending on how I run my sage program. in the notebook:

2^10 
==>1024

running my program with sage -python filename.py:

from sage.all import *
print(2^10)
==> 8

What do I have to import in Python to replicate the behaviour of the Sage notebook?

Edit:

Thanks everyone for the basic Python lessons. DSM answered this question in the comments, turns out sage notebook has a preprocessor.

michaelJohn
  • 679
  • 5
  • 9
  • `^` is bitwise XOR operator in Python. To power, use `**` operator.: `print(2 ** 10)`, or use `pow` function: `pow(2, 10)` – falsetru Dec 27 '14 at 02:33
  • 2
    Aside: this isn't the only subtle change that the preprocessor makes. For example, 2/3 will wind up producing a rational in QQ in Sage, but 0 in Python. It's important to think in terms of Python and not Sage when writing code you intend to import. – DSM Dec 27 '14 at 02:54

1 Answers1

2

In python for Exponentiation we use double asterik **

>>> print (2**10)
1024

OR you can use built-in function pow.

>>> pow(2, 10)
1024

pow

pow(...)
    pow(x, y[, z]) -> number

    With two arguments, equivalent to x**y.  With three arguments,
    equivalent to (x**y) % z, but may be more efficient (e.g. for longs).
enter code here

^ is a bitwise operator for performing XOR(bitwise exclusive or) operation.

For example:

>>> a = [1,2,3]
>>> b = [3,4,5]
>>> a^b
>>> set(a)^set(b)
set([1, 2, 4, 5])

x ^ y

Does a "bitwise exclusive or". 
Each bit of the output is the same as the corresponding bit in x if that bit in y is 0, 
and it's the complement of the bit in x if that bit in y is 1.

Just remember about that infinite series of 1 bits in a negative number, and these 
should all make sense.
Community
  • 1
  • 1
Tanveer Alam
  • 5,185
  • 4
  • 22
  • 43