求一个非负数算术平方根的函数***为sqrt(x))。
时间: 2023-12-04 12:03:01 浏览: 35
以下是使用牛顿迭代法实现求一个非负数算术平方根的函数sqrt(x)的Python代码:
```python
def sqrt(x):
if x == 0:
return 0
else:
last = 0.0
current = 1.0
while last != current:
last = current
current = (current + x / current) / 2
return current
```
该函数使用了牛顿迭代法,通过不断逼近平方根的值,最终得到一个精确的结果。在函数中,我们首先判断输入的数是否为0,如果是,则直接返回0;否则,我们初始化两个变量last和current,分别表示上一次和当前的逼近值。然后,我们进入一个while循环,不断更新last和current的值,直到它们相等为止。在每次更新current的值时,我们使用牛顿迭代公式:current = (current + x / current) / 2。
相关问题
matlab算术平方根函数
MATLAB中的算术平方根函数是sqrt()。它可以用于计算一个数的平方根,也可以用于计算矩阵的每个元素的平方根。例如,sqrt(4)将返回2,sqrt([1 4 9])将返回[1 2 3]。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
用python写求x的算术平方根
可以使用math模块中的sqrt函数来求解x的算术平方根,代码如下:
import math
x = 16
result = math.sqrt(x)
print(result)
输出结果为:4.0
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)