0
Why is 9**(1/2) =3.0 not 3?
3 Answers
+ 3
Because the square root of most numbers is not an integer. For consistency and predictable calculation it makes sense for all results to have a fractional component - even if it's 0.
+ 3
If one of the arguments is a floating-point number, the other argument is converted to a floating-point number. Consequently, the result of raising to a power will also be a floating-point number.
Examples:
9**(1/2) = 9**(0.5) = 3.0
2**2.0 = 4.0
3.0**2 = 9.0
+ 2
Vladimir Honcharenko's right. Python handles ** / pow() and math.pow() differently.
** (which just calls) pow() can calculate exact integer powers, and "...numeric arguments are first converted to a common type. The result type is that of the arguments after coercion..."
https://docs.python.org/2.1/ref/power.html
math.pow() always converts arguments to Float (the only place for my first answer)
https://docs.python.org/2/library/math.html
Here Python converts numeric fractional constants to floats in disassembly (I use 'i' to prevent Python from precomputing numeric constants during compilation):
>>> i=2
>>> 9**(1/2); 9**(1/i)
# Demonstrate: same result for 1/i and 1/2
3.0
3.0
>>> dis.dis("9**(1/2)") # disassemble
1 0 LOAD_CONST 0 (9)
3 LOAD_CONST 3 (0.5)
# note precomputed 0.5 fractional/float "constant"
6 BINARY_POWER
7 RETURN_VALUE
>>> dis.dis("9**(1/i)")
# disassemble - forced evaluation using i
1 0 LOAD_CONST 0 (9)
3 LOAD_CONST 1 (1)
6 LOAD_NAME 0 (i)
9 BINARY_TRUE_DIVIDE
# note below - always returns float
10 BINARY_POWER
11 RETURN_VALUE
From the below source (when dividing by 2 might result in a shift right):
"BINARY TRUE DIVIDE implements true division (the â/â operator), which always yields a floating point number. Therefore floating point division is used and integer operands are cast to floats first. The stack interaction is identical to the other binary operators."
Stella: A Python-based Domain-Specific Language for Simulations - UNM Digital Repository - University of New Mexico: http://digitalrepository.unm.edu/cgi/viewcontent.cgi?article=1011&context=cs_etds&usg=AFQjCNHYSVIRkme5LeCS2gBu53M_CHdpgg&sig2=ND5IVnZ_lZT15GBxAd7KBg
Note this is for Python 3.x. Python 2.x divides differently/returns 1.0 with these tests.