Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python pow ** results [duplicate]

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?

like image 754
mll Avatar asked Dec 26 '22 22:12

mll


2 Answers

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
like image 114
Martijn Pieters Avatar answered Jan 04 '23 20:01

Martijn Pieters


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
like image 35
Anshu Dwibhashi Avatar answered Jan 04 '23 21:01

Anshu Dwibhashi