如何在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_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
输入的提示会重复多次。你是怎么结束的?
答案 0 :(得分:1)
尝试动态生成Nthroot函数,其中包含所需的值。然后,这些值将在每个vall中重复使用到newraph中的“f”。
此方法允许您继续使用newraph的任意函数(即使您不需要用户输入或完全不同的输入)。
def derivative(f, x, h):
return (f(x+h) - f(x-h)) / (2.0*h)
def generateNthrootFunc():
root = int(raw_input("Please Enter a nth root (n) : "))
number = int(raw_input("Please Enter a number (x): "))
def nthroot(x):
return x**(root) - (number)
return nthroot
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
root = newraph(generateNthrootFunc(), 1, 0.000001) # call the solver
print "The root is", root
答案 1 :(得分:0)
输入的提示会重复多次......
因为你多次调用这个函数:
root = newraph(nthroot, 1, 0.000001) # call the solver
然后在newraph
while (abs(Xold - Xnew) > h):
Xold = Xnew
Xnew = Xold - f(Xnew) / derivative(f, Xold, h) #NewtonRaphson formula
其中f
为nthroot
。
然后你在derivate
(两次)中称之为agin:
def derivative(f, x, h):
return (f(x+h) - f(x-h)) / (2.0*h)
你可以让nthroot
成为一个班级
class nthroot_generator:
def __init__(self, number, root):
self.number = number
self.root = root
def __call__(self, x):
return x**(self.root) - (number)
并像这样呼吁:
root = int(input("Please Enter a nth root (n) : "))
number = int(input("Please Enter a number (x): "))
trueroot = newraph(nthroot_generator(root, number), 1, 0.000001)