标签归档:sqrt

如何在Python中计算平方根?

问题:如何在Python中计算平方根?

为什么Python会给出“错误”的答案?

x = 16

sqrt = x**(.5)  #returns 4
sqrt = x**(1/2) #returns 1

是的,我知道import math并使用sqrt。但我正在寻找以上答案。

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.


回答 0

sqrt=x**(1/2)在做整数除法。1/2 == 0

因此,您在第一个实例中计算x (1/2),在第二个实例中计算x (0)

没错,这是对其他问题的正确答案。

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.


回答 1

您必须编写:sqrt = x**(1/2.0),否则将执行整数除法并1/2返回表达式0

此行为是在Python 2.x的“正常”,而在Python 3.x的1/2计算结果为0.5。如果您希望Python 2.x代码的行为类似于3.x wrt除法写入from __future__ import division-那么1/2将评估0.5为并向后兼容,1//2评估为0

作为记录,计算平方根的首选方法是:

import math
math.sqrt(x)

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 w.r.t. division write from __future__ import division – then 1/2 will evaluate to 0.5 and for backwards compatibility, 1//2 will evaluate to 0.

And for the record, the preferred way to calculate a square root is this:

import math
math.sqrt(x)

回答 2

import math
math.sqrt( x )

这是对答案链的琐碎补充。但是,由于该主题在Google上非常普遍,因此我认为值得添加。

import math
math.sqrt( x )

It is a trivial addition to the answer chain. However since the Subject is very common google hit, this deserves to be added, I believe.


回答 3

/ 在Python 2中执行整数除法:

>>> 1/2
0

如果其中一个数字是浮点数,则按预期方式工作:

>>> 1.0/2
0.5
>>> 16**(1.0/2)
4.0

/ 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

回答 4

您所看到的是整数除法。要默认获得浮点除法,

from __future__ import division

或者,您可以将1/2的1或2转换为浮点值。

sqrt = x**(1.0/2)

What you’re seeing is integer division. To get floating point division by default,

from __future__ import division

Or, you could convert 1 or 2 of 1/2 into a floating point value.

sqrt = x**(1.0/2)

回答 5

这可能有点迟了,但是计算平方根的最简单,最准确的方法是牛顿法。

您有一个要计算其平方根的数字,(num)并且猜出了其平方根(estimate)。估计可以是大于0的任何数字,但是有意义的数字会大大缩短递归调用的深度。

new_estimate = (estimate + num / estimate) / 2

该行使用这两个参数计算出更准确的估算值。您可以将new_estimate值传递给该函数,然后计算另一个比上一个更准确的new_estimate,也可以像这样进行递归函数定义。

def newtons_method(num, estimate):
    # Computing a new_estimate
    new_estimate = (estimate + num / estimate) / 2
    print(new_estimate)
    # Base Case: Comparing our estimate with built-in functions value
    if new_estimate == math.sqrt(num):
        return True
    else:
        return newtons_method(num, new_estimate)

例如,我们需要找到30的平方根。我们知道结果在5到6之间。

newtons_method(30,5)

数字是30,估计是5。每个递归调用的结果是:

5.5
5.477272727272727
5.4772255752546215
5.477225575051661

最后的结果是最精确的数字平方根计算。它与内置函数math.sqrt()的值相同。

This might be a little late to answer but most simple and accurate way to compute square root is newton’s method.

You have a number which you want to compute its square root (num) and you have a guess of its square root (estimate). Estimate can be any number bigger than 0, but a number that makes sense shortens the recursive call depth significantly.

new_estimate = (estimate + num / estimate) / 2

This line computes a more accurate estimate with those 2 parameters. You can pass new_estimate value to the function and compute another new_estimate which is more accurate than the previous one or you can make a recursive function definition like this.

def newtons_method(num, estimate):
    # Computing a new_estimate
    new_estimate = (estimate + num / estimate) / 2
    print(new_estimate)
    # Base Case: Comparing our estimate with built-in functions value
    if new_estimate == math.sqrt(num):
        return True
    else:
        return newtons_method(num, new_estimate)

For example we need to find 30’s square root. We know that the result is between 5 and 6.

newtons_method(30,5)

number is 30 and estimate is 5. The result from each recursive calls are:

5.5
5.477272727272727
5.4772255752546215
5.477225575051661

The last result is the most accurate computation of the square root of number. It is the same value as the built-in function math.sqrt().


回答 6

可能是一种简单的记住方式:在分子(或分母)后添加点

16 ** (1. / 2)   # 4
289 ** (1. / 2)  # 17
27 ** (1. / 3)   # 3

Perhaps a simple way to remember: add a dot after the numerator (or denominator)

16 ** (1. / 2)   # 4
289 ** (1. / 2)  # 17
27 ** (1. / 3)   # 3

回答 7

您可以使用NumPy计算数组的平方根:

 import numpy as np
 np.sqrt([1, 4, 9])

You can use NumPy to calculate square roots of arrays:

 import numpy as np
 np.sqrt([1, 4, 9])

回答 8

我希望下面提到的代码能够回答您的问题。

def root(x,a):
    y = 1 / a
    y = float(y)
    print y
    z = x ** y
    print z

base = input("Please input the base value:")
power = float(input("Please input the root value:"))


root(base,power) 

I hope the below mentioned code will answer your question.

def root(x,a):
    y = 1 / a
    y = float(y)
    print y
    z = x ** y
    print z

base = input("Please input the base value:")
power = float(input("Please input the root value:"))


root(base,power)