簡體   English   中英

如何修復錯誤位置程序

[英]How to Fix False Position Program

因此對於我創建的程序,我運行了調試器,它只是跳過了我創建的函數,不確定為什么...

import numpy as np 
import math
import matplotlib.pyplot as plt 

def f1(x):
    return x*np.tan(x)


def f2(x):
    return np.cos(x)

ub = float(input("Enter a value for the upper bound of the function: "))
lb = float(input("Enter a value for the lower bound of the function: "))
tolf = float(input("Enter the tolerance for this function: "))

def myFP(lb,ub,tolf):
    xc = ((lb*f1(ub))-(ub*f1(lb)))/(f1(ub)-f1(lb))
    while abs(f1(xc)) > tolf:
        if f1(xc)*f1(lb) > 0:
            lb = xc
        else:
            ub = xc
        xc = ((lb * f1(ub)) - (ub * f1(lb))) / (f1(ub) - f1(lb))


print ("The root of the function is ", myFP)

如果您談論myFP ,我想您的調試器將直接進入print行。

這是因為您已經定義了函數,但此時尚未使用它。

您應該使用myFP(arg1,arg2,arg3)調用它。 但是,在定義函數( def行)時,您確實不希望將全局變量的名稱用作參數(因為它是否掩蓋了全局變量可能確實令人困惑……)

因此,您的函數定義應為

def myFP(arg1,arg2,arg3):
    xc = ((arg1*f1(arg2))-(arg2*f1(arg1)))/(f1(arg2)-f1(arg1))
    while abs(f1(xc)) > arg3:
        if f1(xc)*f1(arg1) > 0:
            arg1 = xc
        else:
            arg2 = xc
        xc = ((arg1 * f1(arg2)) - (arg2 * f1(arg1))) / (f1(arg2) - f1(arg1))
        return xc

(請注意最后有return 。)

話雖如此,如果您想在print調用中使用函數,可以通過使用

print ("The root of the function is ", myFP(lb,ub,tolf) )

最后,要在調試器中顯示它,您應該在函數的第一行設置一個斷點,然后在運行print行時進入下一行,或者最好在print行上使用單步執行功能。

由於myFP被稱為whithin的print通話中,“呼叫令”將myFP - > print ,你應該能夠毫無問題地進入你的函數。

順便說一句,您可能會讀過一些有關在python中定義函數的教程,例如教程(或其他教程),以確保您的理解。

將退貨添加到myFP:

import numpy as np 
import math
import matplotlib.pyplot as plt 

def f1(x):
    return x*np.tan(x)


def f2(x):
    return np.cos(x)

ub = float(input("Enter a value for the upper bound of the function: "))
lb = float(input("Enter a value for the lower bound of the function: "))
tolf = float(input("Enter the tolerance for this function: "))

def myFP(lb,ub,tolf):
    xc = ((lb*f1(ub))-(ub*f1(lb)))/(f1(ub)-f1(lb))
    while abs(f1(xc)) > tolf:
        if f1(xc)*f1(lb) > 0:
            lb = xc
        else:
            ub = xc
        xc = ((lb * f1(ub)) - (ub * f1(lb))) / (f1(ub) - f1(lb))
    return xc #add this


print ("The root of the function is ", myFP(lb, ub, tolf)) #and this

我認為涵蓋了它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM