How to find quadratic equation roots with gradient descent? I wrote a code to find argmin of given equation but I can not understand how to find exactly roots.
# x**2 + 5 * x + 6 = 0 roots: -3, -2
def grad(x):
return 2 * x + 5
def grad_desc():
x_old = float('inf')
epsilon = 0.000001
lr = 0.01
x_new = 0
while abs(x_new - x_old) > epsilon:
x_old = x_new
x_new -= lr * grad(x_new)
return x_new
x = grad_desc()
x – argmin of given equation. How can I now find roots approximately right. Thank you in advance.
>Solution :
To find the roots of a quadratic equation using gradient descent, you need to understand that gradient descent is typically used to find the minimum or maximum of a function, not its roots. However, with some adjustments, it can be adapted to find roots.
The quadratic equation you have is x^2 + 5x + 6 = 0. The roots of this equation are the values of x for which the equation equals zero.
To adapt gradient descent for finding roots, you can consider finding the minimum of the function f(x) = (x^2 + 5x + 6)^2. The rationale is that the square of the quadratic will have its minimum where the original quadratic is zero, since the square of zero is zero.
Here’s how you can modify your gradient descent function:
-
Gradient Function: The gradient of
f(x) = (x^2 + 5x + 6)^2isf'(x) = 2(x^2 + 5x + 6)(2x + 5). -
Stopping Condition: You might want to include a condition to stop the iteration if the function value
f(x)is sufficiently close to zero, as this would indicate thatxis near a root.
Here’s the modified code:
def grad(x):
return 2 * (x**2 + 5 * x + 6) * (2 * x + 5)
def grad_desc():
x_old = float('inf')
epsilon = 0.000001
lr = 0.01
x_new = 0
while abs(x_new - x_old) > epsilon:
x_old = x_new
x_new -= lr * grad(x_new)
if abs(x_new**2 + 5 * x_new + 6) < epsilon:
break
return x_new
x = grad_desc()
print(x)