📅  最后修改于: 2023-12-03 14:38:52.529000             🧑  作者: Mango
这是一个简单的程序,用于计算给定数字的平方根。我们将使用Python作为示例编程语言来实现算法。
我们将使用二分查找算法来确定给定数字的平方根。该算法中,我们从数字的一半开始,逐渐逼近其平方根。我们将使用epsilon变量来指定数字和平方根之间的误差水平。
def square_root(number, epsilon):
"""Return the square root of the given number with the specified degree of precision."""
low = 0.0
high = max(1.0, number)
guess = (low + high) / 2.0
while abs(guess ** 2 - number) > epsilon:
if guess ** 2 < number:
low = guess
else:
high = guess
guess = (low + high) / 2.0
return guess
number = 400
epsilon = 0.01
root1 = square_root(number, epsilon)
root2 = -1 * root1
print(f"The square roots of {number} are {root1:.2f} and {root2:.2f}")
代码片段返回如下markdown:
#### 代码:
```python
def square_root(number, epsilon):
"""Return the square root of the given number with the specified degree of precision."""
low = 0.0
high = max(1.0, number)
guess = (low + high) / 2.0
while abs(guess ** 2 - number) > epsilon:
if guess ** 2 < number:
low = guess
else:
high = guess
guess = (low + high) / 2.0
return guess
number = 400
epsilon = 0.01
root1 = square_root(number, epsilon)
root2 = -1 * root1
print(f"The square roots of {number} are {root1:.2f} and {root2:.2f}")