Python mathematical operators sequence [duplicate] - python

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.

Related

Python undesirable complex numbers [duplicate]

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)

Python: 4/5=0.0. Float declaration missing? [duplicate]

This question already has answers here:
Why does the division get rounded to an integer? [duplicate]
(13 answers)
Closed 6 years ago.
Apologies if this has already been asked but why does this:
a=4
b=5
c=float(a/b)
print c
Gives
>>>>
0.0
rather than 0.8?
That's because this is an integer division:
>>> 4/5
0
if you want to get 0.8, cast one of the two to float before the division:
>>> 4/float(5)
0.8
In Python 2, division between 2 integers will return an integer (rounding to the closest integer to 0), in this case, 0. Your code is basically float(0) which is 0.0.
You would need to change one of your values to a float first if you want to return a float.
This behavior is changed in Python 3, where division between 2 integers will return a float, 0.8 in this case.
If you do not want to introduce float in one of the variables. You could do this:
from __future__ import division
4/5
This will give what you are looking for 0.8, without having to introduce floating.
In Python 2 / returns only integer part if you use two integers - like int(0.8). You have to use float ie. float(a) or 4.0 (shortly 4.) or * 1.0
print float(4)/5
print 4/float(5)
print 4.0/5
print 4/5.0
print 4./5
print 4/5.
print a*1.0/b # sometimes you can see this method
print a/(b*1.0) # this version need () - without () you get (a/b)*1.0
4/5 will return 0 because it's an int division, then you cast float on 0
Because of integer division....dividing two integers will return and integer. The value of 0.8 is truncated to 0.
You need to elevate one of your integers to a float if you want a floating point answer.
E.G.
c = float(a) / b

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.

Difference between / in C++ and Python

Using Python 2.7
I was trying to solve the Reverse Polish Notation problem on LeetCodeOJ.
RPN on LeetCodeOJ
I wrote my straightforward solution in Python as follows:
class Solution:
# #param tokens, a list of string
# #return an integer
def evalRPN(self, tokens):
stack = []
for token in tokens:
if token in ["+" , "-" ,"*", "/"]:
op1 = stack.pop()
op2 = stack.pop()
if token == "+":
stack.append(op2+op1)
elif token == "-":
stack.append(op2-op1)
elif token == "*":
stack.append(op2*op1)
elif token == "/":
stack.append(op2/op1)
else:
stack.append(int(token))
if len(stack) == 1:
return stack.pop()
else:
return 0
This gets rejected on a test case:
Input: ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 12
Expected: 22
But if I modify the application of '/' operation to stack.append(int(op2 / (op1*1.0))), it succeeds.
The / operation is performed once on this input calculating 6/-132 which results in -1 using either of two ways.
Strangely, despite the fact that both evaluations result in -1, the program as a whole differs in its output. As shown above, using the first way gives 12 as the RPNEval while using the second would give 22.
What causes this?
I visited this link, but it only says that there is some difference in the / operator in Python and C++. What is the difference?
If you are on Python 2, / does integer division (meaning, it drops the remainder and just gives you the rounded-down result) unless at least one of the operands is of type float rather than int. You fix this by multiplying with 1.0, but you could also call float(...) on one of the operands. This is similar to C++, however, in C++ the result is rounded towards zero rather than down, meaning that you will receive different results with one negative operand:
C++:
1 / 2 // gives 0
(-1) / 2 // also gives 0
Python 2:
1 / 2 # gives 0
(-1) / 2 # gives -1 (-0.5 rounded down)
Python 3:
On Python 3, / always does proper floating point division, meaning that you always get a float back, you can use // to restore the old behaviour
1 / 2 # gives 0.5
(-1) / 2 # gives -0.5
1 // 2 # gives 0
(-1) // 2 # gives -1
Edited to add:
Since you are on Python 2.7 (see the edited question), it indeed seems to be the integer division thing you are stuck at. To get the new Python 3-style behaviour in Python 2, you can also run
from __future__ import division
at the beginning of your program (it must be at the very start, or the interpreter will complain)
Yet another edit regarding int(something)
Beware that while integer division rounds down, conversion to integer rounds towards zero, like integer division in C++.
There are only two major differences between Python / and C++ /.
First, for negative numbers, Python rounds toward negative infinity; C++ rounds toward 0. So, -10 / 3 is -4 in Python, -3 (usually) in C++.
Second, in Python 3.x, or Python 2.x with from __future__ import division, diving two integers with / gives you a float, so 9 / 3 is 3.0 in Python 3.x, but 3 in C++ or Python 2.x.
So, what if you want C++ style division in Python? Well, the int function always rounds toward 0, not negative infinity. So, if you force it to do floating-point division, then call int on the result, instead of letting it to integer division, you will get the same results as in C++. That's why the code you're linking to uses int(b/(a*1.0)). I'm not sure that's the best way to write that (especially without even a comment explaining what the point is), but that's what it's there for.
Meanwhile, if you really want to see why things are different, try running your code in the debugger, or an online visualizer, or just adding print calls at each step in the eval loop. Then you can see exactly at which step things go wrong—what the arguments were, what the output was, and what you expected the output to be. Then you can reduce the problem to a much simpler one, like:
a = 4
b = -13
print(b/a)
print(int(b/(a*1.0)))
And then to figure out why those are different, break the int(b/(a*1.0)) down into steps:
print(a*1.0)
print(b/(a*1.0))
print(int(b/(a*1.0)))
In C++ if you divide two integer numbers, you get an integer, rounded towards zero. For example,
1 / 2 = 0
-1 / 2 = 0
But if at least one of the arguments is floating point, the result is floating point.
In python2 for integer arguments / will do integer division, rounded down, for example
1 / 2 = 0
-1 / 2 = -1
In python3 they changed the behavior of /, and not it always does floating point division
1 / 2 = 0.5
If you want integer division in python3, you can use // operator
1 // 2 = 0
-1 // 2 = -1

Python pow ** results [duplicate]

This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
Closed 9 years ago.
Why the build-in operator in this example 4**(1/2) (which is a square root operation) returns as a result 1 and not 2 as it should be expected? If is not going to return an acceptable result it should rise an error, but Python continues working without any crash. At least in Python 2.7.4 64 bit distribution.
It also happens with the math function pow(4,1/2) which returns 1 with no errors.
Instead, when doing 4**(0.5) it returns as a result 2.0 which is correct, although it mixes integers and floats without any warnings. The same happens with pow.
Any explanation for this behaviors? Shall they be considered as bugs?
1/2 uses floor division, not floating point division, because both operands are integers:
>>> 1/2
0
Use floating point values, or use from __future__ import division to switch to the Python 3 behaviour where the / operator always uses floating point division:
>>> 1/2.0
0.5
>>> 4**(1/2.0)
2.0
>>> from __future__ import division
>>> 1/2
0.5
>>> 4**(1/2)
2.0
1/2 gives 0.5 as an answer but since it is an int/int it returns an int hence it truncates the .5 and returns 0. In order to get a float result, either of the numbers must be float . Hence you must do:
>>> 4 ** (1.0/2)
2.0
This works perfectly, you can also try this:
>>> math.pow(4,1.0/2)
2.0
or you can also try this:
>>> math.sqrt(4)
2.0

Categories