Run
# Write a program to find roots of a quadratic equation in Python
import math
def findRoots(a, b, c):
if a == 0:
print("Invalid")
return -1
d = b * b - 4 * a * c
sqrt_val = math.sqrt(abs(d))
if d > 0:
print("Roots are real and different ")
print((-b + sqrt_val)/(2 * a))
print((-b - sqrt_val)/(2 * a))
elif d == 0:
print("Roots are real and same")
print(-b / (2*a))
else: # d<0
print("Roots are complex")
print(- b / (2*a), " + i", sqrt_val)
print(- b / (2*a), " - i", sqrt_val)
# Driver Program
a = 1
b = 4
c = 4
# Function call
findRoots(a, b, c)
#quadratic equation: x^2 -2x -15
a = 1
b = -2
c = -15
x1 = (-b + (b ** 2 – 4 * a * c) ** 0.5)/ 2 * a
x2 = (-b – (b ** 2 – 4 * a * c) ** 0.5)/2 * a
print(x1)
print(x2)
#more clearly
#quadratic equation: x^2 -2x -15
a = 1
b = -2
c = -15
x1 = (-b + (b ** 2 – 4 * a * c) ** 0.5)/ 2 * a
x2 = (-b – (b ** 2 – 4 * a * c) ** 0.5)/2 * a
print(x1)
print(x2)
Code in Java :
import java.util.Scanner;
public class Quadratic_equation
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print(“Enter a:”);
int a = sc.nextInt();
System.out.print(“Enter b:”);
int b = sc.nextInt();
System.out.print(“Enter c:”);
int c = sc.nextInt();
int determinant = b*b – 4*a*c;
if(determinant > 0)
{
System.out.println(“Real roots: “);
double root1 = (-b + Math.sqrt(determinant) )/(2*a);
System.out.println(root1);
double root2 = (-b – Math.sqrt(determinant) )/(2*a);
System.out.println(root2);
}
else if(determinant < 0)
{
System.out.println("Imaginary roots: ");
double root1 = -b/(2*a);
double rootImg1 = Math.abs(Math.sqrt(determinant));
System.out.println(root1 +"+i"+rootImg1);
System.out.println(root1 +"-i"+rootImg1); // Imaginary root2
}
else
{
System.out.println("Equal roots: ");
System.out.println(-b/2*a);
System.out.println(-b/2*a);
}
}
}