python求平方根的代码_python - New Question.用迭代法计算平方根

问 题

昨天被大神教训说需要帮助就把代码用代码格式写出来,sorry啊,第一次用,刚知道怎么操作,这个project是要用迭代法计算平方根,目的是跟内置数学函数计算的平方根作对比。

professor让用下面这个式子代入计算平方根。

bVDS6d?w=712&h=206

import argparse # Used in main program to get PIN code from command line

from test_harness import testEQ # Used in CIS 210 for test cases

## Constants used by this program

def my_sqrt(number, iterations):

"""

Generate an iterative approximation to the square root of a number

args:

number: positive number to calculate the square root of

iterations: number of iterations to perform

returns:

approximate value of the square root

"""

#FIXME: Your code replaces the next line

value = -12345.0

return value

def run_tests():

"""

This function runs a set of tests to help you debug your

program as you develop it.

"""

print("**** TESTING --- 5 iterations for sqrt of 1, 10, 100, 1000, 10000")

testEQ("1.0", my_sqrt(1.0, 5), 1.0)

testEQ("10.0", my_sqrt(10.0, 5), 3.162277665175675)

testEQ("100.0", my_sqrt(100.0, 5), 10.032578510960604)

testEQ("1000.0", my_sqrt(1000.0, 5), 41.24542607499115)

testEQ("10000.0", my_sqrt(10000.0, 5), 323.0844833048122)

print("*** End of provided test cases. Add some of your own? ****")

def main():

"""

Interaction if run from the command line.

Magic for now; we'll look at what's going on here

in the next week or two.

"""

parser = argparse.ArgumentParser(description="Iterative approximation for pi")

parser.add_argument("Number", type=float, help="number (a float)")

parser.add_argument("-i", "--iterations", type=int, help="iterations (an int)")

args = parser.parse_args() # gets arguments from command line

number = args.Number

iterations = args.iterations

value = my_sqrt(number, iterations)

print("After", iterations, "iterations, sqrt(", number, ") = ", value)

if __name__ == "__main__":

run_tests() #FIXME: Comment this out when your program is working

# main() #FIXME: Uncomment this when your program is working

stater code 就是这样,当然大部分都写好了,只是需要my_sqrt的function,因为没有基础上这个课真的是好难啊。我不是很清楚怎么能把这个式子代入,当然有大神指点一下代入方法让我自己想一下也是可以哟,现在真是没有头绪。

多谢!

抱拳!

解决方案

python3

def my_sqrt(number, iterations):

"""

Generate an iterative approximation to the square root of a number

args:

number: positive number to calculate the square root of

iterations: number of iterations to perform

returns:

approximate value of the square root

"""

#FIXME: Your code replaces the next line

n, itr = number, iterations

x = 1

for i in range(itr):

x = (1/2)*(x+n/x)

value = x

return value

wx.jpg

扫一扫关注IT屋

微信公众号搜索 “ IT屋 ” ,选择关注与百万开发者在一起

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值