函数输入

2024-09-30 22:18:15 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在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

输入提示会重复几次。你怎么结束?你知道吗


Tags: 函数numberinputrawreturndefrootint
2条回答

The prompt for the input repeats several times...

这是因为您多次调用该函数:

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

其中fnthroot。你知道吗

然后在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)    

尝试在运行中生成Nthroot函数,其中已经包含所需的值。然后,这些值将在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

相关问题 更多 >