How to calc square root in python?
Why does python give the "wrong" answer?
x= 16
sqrt= x**(.5)
returns 4
sqrt= x**(1/2)
returns 1
Yes, I know import math
and use sqrt
. But I'm looking for an answer to the above.
sqrt=x**(1/2)
is doing integer division. 1/2 == 0
.
So you're computing x(1/2) in the first instance, x(0) in the second.
So it's not wrong, it's the right answer to a different question.
You have to write: sqrt = x**(1/2.0)
, otherwise an integer division is performed and the expression 1/2
returns 0
.
This behavior is "normal" in Python 2.x, whereas in Python 3.x 1/2
evaluates to 0.5
. If you want your Python 2.x code to behave like 3.x wrt division write from __future__ import division
- then 1/2
will evaluate to 0.5
and for backwards compatibility, 1//2
eill evaluate to 0
.
And for the record, the preferred way to calculate a square root is this:
import math
math.sqrt(x)
/
performs an integer division in Python 2:
>>> 1/2
0
If one of the numbers is a float, it works as expected:
>>> 1.0/2
0.5
>>> 16**(1.0/2)
4.0
链接地址: http://www.djcxy.com/p/86634.html
上一篇: 在python中的整数平方根
下一篇: 如何计算python的平方根?