Python undesirable complex numbers [duplicate] - python

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)

Related

Why does Python return a complex number for operation x**x if -1 < x < 0?

I am on Windows 10 (64-Bit machine with 32-Bit Python 3.7).
In IDLE, if I type:
>>> -0.001**-0.001
-1.0069316688518042
But if I do:
>>> x = -0.001
>>> x**x
(1.006926699847276 -0.0031633639300006526j)
Interestingly, the magnitude of this complex number is the same as the actual answer.
As a proof, I've attached screenshot of the same.
What could be causing this?
In the first case, you are not getting a complex number because ** has higher precedence than - (both in Python and in math), so you are actually doing -(0.001 ** -0.001). Try (-0.001) ** -0.001.
The complex number is the "correct" answer by the mathematical definition of the power operation.
in Python, operator ** means to the power of, a negative number taking a negative power shall create an imaginary number, as just like sqrt(-1)=i.
if you meant for multiplication, you should use x*x instead of x**x

Python mathematical operators sequence [duplicate]

This question already has answers here:
Operator precedence in Python -PEMDAS
(2 answers)
Closed 6 years ago.
a=0
b=5
And when we try to get result of this:
print str((23-11)/a*b)
We get the divide by zero error.
Traceback (most recent call last): File "", line 1, in
print str((23-11)/a*b) ZeroDivisionError: integer division or modulo by zero
But if we change positions:
print str((23-11)/b*a)
The result is zero:
0
Should we get always divide y zero error (because (b*a) is zero)?
((23-11)/a*b) becomes
((23-11)/b*a) becomes
In print str((23-11)/a*b) this is what happens
1.Calculate 23-11
2.Divide step by a(0)
3.Multiply step 2 by b(5)
It is step 2 which gives the zero division error
However in print str((23-11)/b*a) this is what happens
1.Calculate 23-11
2.Divide step 2 by 5
3.Multiply step 3 by 0.
There is no ZeroDivisonError because the computer divides by 5 then multiplies by 0, not divides by 0*5. This is because in order of operations Multiplication and Division are of equal priority so they are just executed left to right.
The evaluation of (23-11)/a*b is decomposed as follow: ((23 - 11) / a) * b
See: Operator precedence
It's giving you a zero rather than an error because it's dividing by the first variable and multiplying by the second.
Like, if you change it to ((23-11)/(ba)) or((23-11)/(ab)) it will return the divide by 0 error, too. But at the moment it's calculating (23-11)/5 * 0, I think.

why ~9 returns -10 in Python [duplicate]

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.

Strange behaviour when raising numbers to the power of zero in Python [duplicate]

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.

Conditional for negative integer

I'm defining a function that calculates the standard deviation of a list. Sometimes the mean of this list is negative and so my function can't take the square root of a negative, returning me with an error.
This seems simple, I just can't think of it. I want to write a conditional for my function saying that if there is a negative number, to multiply by -1 since the square root of a negative number cannot be taken.
How can I write this statement?
def stdevValue(lst):
"""calculates the standard deviation of a list of numbers
input: list of numbers
output: float that is the standard deviation
"""
stdev = 0
stdevCalc = (((sum(lst) - (meanValue(x)))/(len(lst)-1)))**0.5
stdev += stdevCalc
return stdev
You appear to have misapplied the formula for standard deviation. You shouldn't need to handle the case of square root of negative numbers at all. You need to square each difference between the value and the mean before summing, like this:
def stdevValue(lst):
m = meanValue(x) # wherever this comes from
return (sum((x - m) ** 2 for x in lst) / len(lst)) ** 0.5
This ensures that the sum is nonnegative, so you can take the square root without being concerned about negative values. (If you want sample standard deviation, divide by (len(lst) - 1)).
See the Wikipedia article on Standard Deviation for more information and examples.
Ignoring the context of the question, the answer is to use the built-in abs. But if you have a mathematical expression of type y = sqrt(x), and y cannot be complex, then x cannot be negative. Any negative x denotes a problem, which could be rounding, wrapping, or, as in your case, an incorrect formula. Simply multiplying by -1, or taking the abs, will not fix the problem, it will give you the wrong answer. You should maybe consider how to deal with these cases (although I appreciate that for the case of standard deviation these errors are unlikely to arise).
If you want to really get creative, you can square and square-root:
>>> import math
>>> x = -5
>>> math.sqrt((-5)**2)
5.0
Cheers

Categories