Python Pow Results **

Why does the build operator in this example 4**(1/2) (which is the square root operation) return 1 , not 2 , as you would expect? If an acceptable result is not returned, it should receive an error, but Python continues to work without any failure. At least the Python 2.7.4 distribution has 64 bits.

This also happens with the pow(4,1/2) math function, which returns 1 without error.

Instead, when doing 4**(0.5) it returns a 2.0 result, which is correct, although it mixes integers and floats without any warning. The same thing happens with pow.

Any explanation for this behavior? Should they be considered errors?

+4
source share
2 answers

1/2 uses gender separation rather than floating point division, since both operands are integers:

 >>> 1/2 0 

Use floating point values ​​or use from __future__ import division to switch to Python 3 behavior, where the / operator always uses floating point separation:

 >>> 1/2.0 0.5 >>> 4**(1/2.0) 2.0 >>> from __future__ import division >>> 1/2 0.5 >>> 4**(1/2) 2.0 
+9
source

1/2 gives 0.5 as the answer, but since it is int/int , it returns int , so it truncates .5 and returns 0 . To get the result of a float , any of the numbers must be a float . Therefore, you must:

 >>> 4 ** (1.0/2) 2.0 

This works great, you can also try the following:

 >>> math.pow(4,1.0/2) 2.0 

or you can also try the following:

 >>> math.sqrt(4) 2.0 
+1
source

Source: https://habr.com/ru/post/1497212/


All Articles