fromrandomimportrandomdefgradient_decent(fn,partial_derivatives,n_variables,lr=0.1,max_iter=10000,tolerance=1e-5):theta=[random()for_inrange(n_variables)]y_cur=fn(*theta)foriinrange(max_iter):# Calculate gradient of current theta.gradient=[f(*theta)forfinpartial_derivatives]# Update the theta by the gradient.forjinrange(n_variables):theta[j]-=gradient[j]*lr# Check if converged or not.y_cur,y_pre=fn(*theta),y_curifabs(y_pre-y_cur)<tolerance:breakreturntheta,y_cur
defmain():print("Solve the minimum value of quadratic function:")n_variables=2theta,f_theta=gradient_decent(f,[df_dx,df_dy],n_variables)theta=[round(x,3)forxintheta]print("The solution is: theta %s, f(theta) %.2f.\n"%(theta,f_theta))