This question already has answers here:
what does the '~' mean in python? [duplicate]
(4 answers)
Closed 7 years ago.
I am trying the following code and here are the outputs, anyone have ideas why -10 and -11 are returned?
print ~9
print ~10
-10
-11
BTW, I am using Python 2.7.8.
From:
Python Doc
The unary ~ (invert) operator yields the bitwise inversion of its plain or long integer argument. The bitwise inversion of x is defined as -(x+1). It only applies to integral numbers.
From:
Python Doc
Two's Complement binary for Negative Integers:
Negative numbers are written with a leading one instead of a leading zero. So if you are using only 8 bits for your twos-complement numbers, then you treat patterns from "00000000" to "01111111" as the whole numbers from 0 to 127, and reserve "1xxxxxxx" for writing negative numbers. A negative number, -x, is written using the bit pattern for (x-1) with all of the bits complemented (switched from 1 to 0 or 0 to 1). So -1 is complement(1 - 1) = complement(0) = "11111111", and -10 is complement(10 - 1) = complement(9) = complement("00001001") = "11110110". This means that negative numbers go all the way down to -128 ("10000000").
~x Returns the complement of x - the number you get by switching each 1 for a 0 and each 0 for a 1. This is the same as -x - 1.
Related
I was trying to understand bitwise NOT in python.
I tried following:
print('{:b}'.format(~ 0b0101))
print(~ 0b0101)
The output is
-110
-6
I tried to understand the output as follows:
Bitwise negating 0101 gives 1010. With 1 in most significant bit, python interprets it as a negative number in 2's complement form and to get back corresponding decimal it further takes 2's complement of 1010 as follows:
1010
0101 (negating)
0110 (adding 1 to get final value)
So it prints it as -110 which is equivalent to -6.
Am I right with this interpretation?
You're half right..
The value is indeed represented by ~x == -(x+1) (add one and invert), but the explanation of why is a little misleading.
Two's compliment numbers require setting the MSB of the integer, which is a little difficult if the number can be an arbitrary number of bits long (as is the case with python). Internally python keeps a separate number (there are optimizations for short numbers however) that tracks how long the digit is. When you print a negative int using the binary format: f'{-6:b}, it just slaps a negative sign in front of the binary representation of the positive value (one's compliment). Otherwise, how would python determine how many leading one's there should be? Should positive values always have leading zeros to indicate they're positive? Internally it does indeed use two's compliment for the math though.
If we consider signed 8 bit numbers (and display all the digits) in 2's compliment your example becomes:
~ 0000 0101: 5
= 1111 1010: -6
So in short, python is performing correct bitwise negation, however the display of negative binary formatted numbers is misleading.
Python integers are arbitrarily long, so if you invert 0b0101, it would be 1111...11111010. How many ones do you write? Well, a 4-bit twos complement -6 is 1010, and a 32-bit twos complement -6 is 11111111111111111111111111111010. So an arbitrarily long -6 could ideally just be written as -6.
Check what happens when ~5 is masked to look at the bits it represents:
>>> ~5
-6
>>> format(~5 & 0xF,'b')
'1010'
>>> format(~5 & 0xFFFF,'b')
'1111111111111010'
>>> format(~5 & 0xFFFFFFFF,'b')
'11111111111111111111111111111010'
>>> format(~5 & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFF,'b')
'11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111010'
A negative decimal representation makes sense and you must mask to limit a representation to a specific number of bits.
This question already has answers here:
What are bitwise shift (bit-shift) operators and how do they work?
(10 answers)
Closed 10 months ago.
The expression (8 >> 1) evaluates to 4. Additionally, (8 << 1) evaluates to 16. I have no idea what the double arrow operator does, does anybody know?
Double arrow operation is bit-shift.
Basically, it looks at your number in binary then "shifts" your entire number to one place left, or one place right.
For example:
8 >> 1 ->
8 becomes: 00001000
shifting 1 place right: 00000100
which is 4.
Similarly,
8 << 1 ->
8 becomes: 00001000
shifting 1 place left: 00010000
which is 16.
There are some edge cases here and there such as logical shift versus arithmetic shift.
Usually, you can use them to do a very quick operation to multiply a number by 2 or divide them by 2, but that is language-dependent, and needs more detail to understand perfectly. In Python particularly, not so much as explained by #paxdiablo in the comments as follows:
bit shifting left in Python is not necessarily faster than multiplication, it has optimisations to avoid expanding its arbitrary precision integers in the latter case
More details on here: What are bitwise shift (bit-shift) operators and how do they work?
Shifting operators. These operators accept integers as arguments. They shift the first argument to the left (<<) or right (>>) by the number of bits given by the second argument.
One example would be 0101 << 1 = 1010 etc
Image from wikipedia
Read it here.
These operators shift the bits in the number, right >> or left <<. In binary notation, shifting a number to the left yeilds 2 * that number. For example, 3: 0011, 6: 0110, 12: 1100
This question already has an answer here:
Division by 10 for large values of n in python gives inaccurate answers
(1 answer)
Closed 1 year ago.
In Python, while dividing bigger values I am getting inaccurate output, for example:-
(1227073724601519345/101) = 12149244798034845. But in Python it becomes
(1227073724601519345/101) = 1.2149244798034844e+16 which converted to int is 12149244798034844.
As you can see
( correct_output - approx_output ) = 1
Is there any way I can avoid this? There is no such inaccuracy while multiplying even bigger numbers, for example:-
(123468274768408415066917747313280346049^2) - (56 * (16499142225694642619627981620326144780^2)) = 1
which is accurate.
Computer commonly use IEEE 754 Standard for Floating-Point Arithmetic. That means that floating point numbers have a limited precision of 53 bits (about 15 or 16 decimal digits).
As you have used (x / y) Python has given you a floating point result, and has the result would require more than 15 decimal digit it cannot be accurate.
But Python also have an integer division operator (//). Integers in Python 3 are multi-precision numbers, meaning that they can represent arbitrary large integers (limited only by the available memory...). It is the reason why you have accurate result when multiplying large numbers. So to get the exact integer result, you should use this:
1227073724601519345//101
which gives as expected 12149244798034845
Use integer division, e.g., 1227073724601519345 // 101.
This question already has answers here:
Wrong value for cube root in Python
(3 answers)
Closed 5 years ago.
>>> a = -27
>>> a ** (1/3)
(1.5000000000000004+2.598076211353316j)
>>> -27 ** (1/3)
-3.0
I have to raise numbers of the list to a power 1/3 but when the number is negative I get a complex number. Why is there such difference in results of these two operations and how can I avoid the first one?
When you set a=-27, you are assigning the negative to the value as well. When you just type in -27**(1/3) it computes the exponent first and then the negative sign. This may be the reason for your issue.
A complex number z has 3 roots of z**3 so for z**(1/3) it's necessary to pick one. A conventional choice is the so-called principal value of z**(1/3) which has the least argument (i.e. it is the one which has the smallest angle with respect to the positive real axis). As you have found, that has nonzero imaginary part when z is a negative real number.
My advice is to just have a test such as if (z < 0): -((-z)**(1/3)) else: z**(1/3) (sorry if I got the wrong syntax).
You have a problem with your order of operations; power has precedence over unary minus.
-27 ** (1/3)
evaluates as
- (27 ** (1/3))
not as
(-27) ** (1/3) # gives a complex result
If a is negative, to get a real root, you need to do
-(-a)**(1/3)
This question already has answers here:
Calculation error with pow operator
(4 answers)
Closed 4 years ago.
I am using Python 2.7.5. When raising an int to the power of zero you would expect to see either -1 or 1 depending on whether the numerator was positive or negative.
Typing directly into the python interpreter yields the following:
>>> -2418**0
-1
This is the correct answer. However when I type this into the same interpretter:
>>> result = -2481
>>> result**0
1
the answer is 1 instead of -1. Using the complex builtin as suggested here has no effect on the outcome.
Why is this happening?
Why would you expect it to be -1? 1 is (according to the definition I was taught) the correct answer.
The first gives the incorrect answer due to operator precedence.
(-1)**0 = 1
-1**0 = -(1**0) = -(1) = -1
See Wikipedia for the definition of the 0 exponent: http://en.wikipedia.org/wiki/Exponentiation#Zero_exponent
-2418**0 is interpreted (mathematically) as -1 * (2418**0) so the answer is -1 * 1 = -1. Exponentiation happens before multiplication.
In your second example you bind the variable result to -1. The next line takes the variable result and raises it to the power of 0 so you get 1. In other words you're doing (-1)**0.
n**0 is 1 for any real number n... except 0: technically 0**0 is undefined, although Python will still return 0**0 == 1.
Your maths is wrong. (-2481)**0 should be 1.
According to wikipedia, Any nonzero number raised by the exponent 0 is 1.