【问题标题】:Is there a way to make approximation outputs in to a list?有没有办法将近似值输出到列表中?
【发布时间】:2021-03-13 17:27:15
【问题描述】:

我正在尝试编写一个使用巴比伦平方根方程的代码(python),通过使用 while 循环来近似平方根,直到误差小于 epsilon 值,并且我试图以 [x1] 的形式打印近似值,x2,x3...] 但只设法让近似值在单独的行上垂直向下列出

例如

x1

x2

x3

到目前为止,这是我的代码。我是编码新手,所以任何帮助和建议将不胜感激:)

a= float(input('enter the positive value that you wish to find the babylonian square root of '))
e= float(input('enter a positive value for maxium error '))
x= float(input('enter an arbitrary starting value '))

if a<0 or a==0:
    print(' a must be a positive number')
elif e<0 or e==0:
    print('e must be a positive number')
elif x==0:
    print('starting value cannot be 0 as cant divide by 0!')
else:
 
    
    while abs(x**2-a)>e or abs(x**2-a)==e :
        x=0.5*(x-(a/x))
        xn=0.5*(x-(a/x))
         x=xn 
   
        print(x)

【问题讨论】:

    标签: python list while-loop


    【解决方案1】:

    创建一个列表,然后输出该列表:

    a = float(input('enter the positive value that you wish to find the babylonian square root of '))
    e = float(input('enter a positive value for maxium error '))
    x = float(input('enter an arbitrary starting value '))
    
    if a < 0 or a == 0:
        print(' a must be a positive number')
    elif e < 0 or e == 0:
        print('e must be a positive number')
    elif x == 0:
        print('starting value cannot be 0 as cant divide by 0!')
    else:
        result_list = []
        while abs(x ** 2 - a) > e or abs(x ** 2 - a) == e:
            x = 0.5 * (x - (a / x))
            xn = 0.5 * (x - (a / x))
            x = xn
            result_list.append(x)
        print(result_list)
    

    【讨论】:

    • 感谢您的帮助,我试过了,但它只打印空集 [] 而不是近似值列表
    • 我刚测试,得到了一个列表,你的测试值是多少?
    • 我使用的是 a=64 e=0.5 x0=7(在 jupyter notebook0 上
    • 我用完整的代码更新了我的答案。我用你给我的值对此进行了测试,得到了一个看起来准确的输出
    猜你喜欢
    • 2021-02-09
    • 2010-11-05
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-13
    相关资源
    最近更新 更多