【问题标题】:Secant Method in PythonPython中的正割方法
【发布时间】:2017-04-25 12:37:47
【问题描述】:

这是我关于割线法的代码:

#initialization for x0, x1, n
raw_input1 = input("Please enter an integer:\n")
raw_input2 = input("Please enter an integer:\n")
raw_input3 = input("Please enter an integer:\n")
x0 = int(raw_input1)
x1 = int(raw_input2)
n  = int(raw_input3)
print(f'You entered {x0} as x0 & {x1} as x0')
print(f'You entered {n} as n for iteration number')


#coeffecients 
G = 6.674*(10**-11) ; M = 5.974*(10**24) ; m = 7.348*(10**22) ; R= 7.348*(10**22) ; w = 2.662*(10**-6)

#secant function
def secant(x0,x1,n):
    for i in range(n):
        if f(x1)-f(x0) == 0:
            return x1
        else:
            r = ((x1-((f(x1)*(x1-x0))))/(f(x1)-f(x0)))*1.0
            x0 = x1
            x1 = r
    return x1


#f(r) function
def f(r) :                      
    return r+((G*M)/((R**2)-(r**2))*(w**2))-((G*M)/(R**2)*(w**2))

似乎没有语法错误,但我认为我没有正确编写它,因为它没有给我任何答案。如果有人可以帮助解决错误并告诉我我做错了什么以及如何解决这个问题,那就太好了。

【问题讨论】:

  • 请修正问题中代码的缩进。
  • “它没有给我任何答案”是什么意思?你期望得到什么答案?您如何使用此代码?您收到任何错误消息吗?
  • 我将修复缩进。就像我说的,没有任何错误消息。我个人认为我没有正确循环它。
  • Secant Method已经有很好的pythonic实现来找到非线性方程的真正根。请查看here

标签: python math iteration


【解决方案1】:

这是完整的代码吗?如果是这样,那么您没有“得到任何答案”,因为您还没有运行任何功能。您的代码所做的只是获取输入并定义两个函数。如果你想让割线实际运行,你需要调用它。只需添加以下行:

secant(x0,x1,n)

但首先要确保你给 x1 一个值。

【讨论】:

  • 在我的实际代码中是这样的,所以缩进没有错。
  • @HiIsuckatcoding 我更新了我的答案。如果有帮助,请告诉我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-12
  • 1970-01-01
  • 2016-05-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多