如何在nthroot函数中请求用户输入?我想要函数要求输入x的幂和下一个项。(我希望程序要求电源和下学期,我只使用3和81分别作为检查)
def derivative(f, x, h):
return (f(x+h) - f(x-h)) / (2.0*h)
def nthroot(x):
return x**3 - 81 # just a function to show it works
def newraph(f, x0, h):
Xold = x0
Xnew = Xold + 10* h
while (abs(Xold - Xnew) > h):
Xold = Xnew
Xnew = Xold - f(Xnew) / derivative(f, Xold, h) #NewtonRaphson formula
return Xnew
trueroot = newraph(nthroot, 1, 0.000001)
print "The root is", trueroot
当我尝试像这样使用int(raw\u input())时:
def derivative(f, x, h):
return (f(x+h) - f(x-h)) / (2.0*h)
def nthroot(x):
root = int(raw_input("Please Enter a nth root (n) : "))
number = int(raw_input("Please Enter a number (x): "))
return x**(root) - (number)
def newraph(f, x0, h):
Xold = x0
Xnew = Xold + 10* h
while (abs(Xold - Xnew) > h):
Xold = Xnew
Xnew = Xold - f(Xnew) / derivative(f, Xold, h) #NewtonRaphson formula
return Xnew
trueroot = newraph(nthroot, 1, 0.000001)
print "The root is", trueroot
输入提示会重复几次。你怎么结束?你知道吗
这是因为您多次调用该函数:
然后在
newraph
内结束其中
f
是nthroot
。你知道吗然后在
derivate
(两次)中称之为agin:可能解
你可以让
nthroot
成为一个类像这样称呼:
尝试在运行中生成Nthroot函数,其中已经包含所需的值。然后,这些值将在newraph中“f”的每个值中重用。你知道吗
此方法允许您继续使用newraph的任意函数(即使是不需要用户输入或完全不同的输入的函数)。你知道吗
相关问题 更多 >
编程相关推荐