class GD():
def __init__(self, objFunction, GDFunction, accurate):
self.objFunction = objFunction
self.GDFuction = GDFunction
self.accurate = accurate
self.lamta = 0.01
def GDFunction(self):
x = 1
self.objFunction_value = eval(self.objFunction)
while eval(self.GDFuction) > self.accurate:
x = x - self.lamta * eval(self.GDFuction)
self.objFunction_current_value = eval(self.objFunction)
if abs(self.objFunction_current_value - self.objFunction_value) < self.accurate:
break
else:
self.objFunction_value = self.objFunction_current_value
return x, self.objFunction_value
if __name__ == "__main__":
objFunction = input('Please input object Function:')
GDFunction = input('Please input gradient descent:')
# accurate = float(input('Please input accurate.'))
# objFunction = "(x-1) ** 2 + 1"
# GDFunction = "2 * (x - 1)"
accurate = 0.00000001
GD = GD(objFunction, GDFunction, accurate)
print("x = %.2f, min_value = %.2f" % GD.GDFunction())