【问题标题】:Newton Raphson: Can the user input the function?Newton Raphson:用户可以输入函数吗?
【发布时间】:2018-07-16 11:55:47
【问题描述】:

[这里的这张图片是我的 Newton-Raphson 方法的 Python 代码。问题在于数学函数和导数。目前我是指定函数及其导数的人。有没有办法让用户输入他/她想要的功能?

import math

""" f: function, f_ : derivative of function, x0: initial guess, errortolerance: tolerance, maxIter: max number of iterations """

def newtonraphson(f, f_, x0, errortolerance=0.00001, maxIter=100):
    """

    Take a function f, its derivative f_, initial value x0, TOL and NMAX,
    and returns the root(s) of the equation using the NR method

    """

    n = 1 #initial numebr of iterations
    while n<=maxIter: # check while n less than maxIter
        x1 = x0 - (f(x0)/f_(x0)) #newtonraphson formula
        if x1 - x0 < errortolerance: 
            return x1
        else:
            x0 = x1
    return False

if __name__ == "__main__":

    def func(x): #initial function
        return 5*math.pow(x,2) - 8*math.pow(x,1) + 4

    def func_(x): #its derivative
        return 10*math.pow(x,1) - 8

    resNR = newtonraphson(func,func_,3) #result of newtonraphson
    print(resNR)

【问题讨论】:

  • 用户可以做你做的事。你还想到了什么?这就是框架的工作原理。
  • 我认为这个问题是指从标准输入或其他用户界面读取函数。
  • 只有微不足道的功能才可行。没有人愿意从命令行编写一个复杂的函数作为单行 lambda。

标签: python python-3.x python-2.7 math newtons-method


【解决方案1】:

您可以使用lambdaeval 让用户输入函数及其导数。我假设您使用的是 Python 3。如果您使用的是 Python 2,请将 input 替换为 raw_input

if __name__ == '__main__':
    f = lambda x : eval(input())
    f_ = lambda x : eval(input())

    print(newtonraphson(f, f_, 3))

现在,让您的用户在x 中输入一个表达式。请记住,输入中只允许已定义的名称。

【讨论】:

  • 非常感谢您!如果你不介意,你能告诉我 eval 在这种情况下做什么吗?我只使用输入,但它从来没有用过。
  • eval 计算 Python 表达式,即,给定一个表达式(产生值的语句),eval 返回它的值。
猜你喜欢
  • 2017-07-15
  • 2013-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-14
  • 1970-01-01
  • 2013-01-23
相关资源
最近更新 更多