【问题标题】:Programming Secant Method into Python将割线方法编程到 Python 中
【发布时间】:2019-02-12 07:33:33
【问题描述】:

两个数字的和是 20。如果每个数字都加到它的平方根上,两个和的乘积是 155.55。使用正割法将两个数的值近似到 10^(-4) 以内。

【问题讨论】:

  • 祝你作业顺利。
  • 我不需要也不想要整个问题的代码。我想帮助尝试将割线方法编程到 Python 中。我想出了如何使用牛顿法解决这个问题,但我想将它与割线法进行比较。我知道我需要两个不同的初始猜测,但我不确定如何创建包含这两个猜测的 for 循环。

标签: python-3.x jupyter-notebook


【解决方案1】:

基于http://campus.murraystate.edu/academic/faculty/wlyle/420/Secant.htm

#inital guess
x1 = 10

x2 = 50
Epsilon = 1e-4
#given function
def func(x): 
    return abs(x)**0.5 * (abs(x)+20)**0.5 - 155.55

y1 = func(x1)
y2 = func(x2)

#loop max 20 times
for i in range(20):
    ans = x2 - y2 * (x2-x1)/(y2-y1)
    y3 = func(ans)
    print("Try:{}\tx1:{:0.3f}\tx2:{:0.3f}\ty3:{:0.3f}".format(i,x1, x2, y3))
    if (abs(y3) < Epsilon):
        break

    x1, x2 = x2, ans
    y1, y2 = y2, y3

print("\n\nThe numbers are: {:0.3f} and {:0.3f}".format(ans, ans+20))

【讨论】:

    【解决方案2】:

    根据您的标题

    此代码在大多数情况下都能正常工作。取自Secant Method Using Python (Output Included)

    # Defining Function
    def f(x):
        return x**3 - 5*x - 9
    
    # Implementing Secant Method
    
    def secant(x0,x1,e,N):
        print('\n\n*** SECANT METHOD IMPLEMENTATION ***')
        step = 1
        condition = True
        while condition:
            if f(x0) == f(x1):
                print('Divide by zero error!')
                break
    
            x2 = x0 - (x1-x0)*f(x0)/( f(x1) - f(x0) ) 
            print('Iteration-%d, x2 = %0.6f and f(x2) = %0.6f' % (step, x2, f(x2)))
            x0 = x1
            x1 = x2
            step = step + 1
    
            if step > N:
                print('Not Convergent!')
                break
    
            condition = abs(f(x2)) > e
        print('\n Required root is: %0.8f' % x2)
    
    
    # Input Section
    x0 = input('Enter First Guess: ')
    x1 = input('Enter Second Guess: ')
    e = input('Tolerable Error: ')
    N = input('Maximum Step: ')
    
    # Converting x0 and e to float
    x0 = float(x0)
    x1 = float(x1)
    e = float(e)
    
    # Converting N to integer
    N = int(N)
    
    
    #Note: You can combine above three section like this
    # x0 = float(input('Enter First Guess: '))
    # x1 = float(input('Enter Second Guess: '))
    # e = float(input('Tolerable Error: '))
    # N = int(input('Maximum Step: '))
    
    # Starting Secant Method
    secant(x0,x1,e,N)
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-09
      • 2016-05-27
      • 2019-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-27
      相关资源
      最近更新 更多