- Java Program to Find all Roots of a Quadratic Equation
- Algorithm
- Example 1
- Output
- Example 2
- Output
- Java Program to Find the Roots of a Quadratic Equation
- 1. Overview
- 2. The Solutions of a Quadratic Equation
- 2.1. The Roots of a Polynomial
- 2.2. Complex Number System
- 3. Calculate the Discriminant
- 4. Get the Solutions
- 4.1. With a Strictly Positive Discriminant
- 4.2. With a Discriminant Equal to Zero
- 4.3. With a Strictly Negative Discriminant
- 4.4. Gather the Results
- 5. Conclusion
- Java: Solve quadratic equations
- Java Conditional Statement: Exercise-2 with Solution
- Java: Tips of the Day
- Java solve quadratic equation
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
Java Program to Find all Roots of a Quadratic Equation
In this article, we will understand how to calculate the roots of a quadratic equation in Java. A quadratic equation is an algebraic expression of the second degree or in other words, it has two results i.e. real number and an imaginary number.
Below is a demonstration of the same −
Given a quadratic equation of the form ax2 + bx + c −
There are three cases: b2 < 4*a*c - The roots are not real i.e. they are complex b2 = 4*a*c - The roots are real and both roots are the same. b2 >4*a*c - The roots are real and both roots are different
The desired output would be −
The roots of the quadratic equation are root_1 = -1.00+1.41i root_2 = -1.00-1.41i
Algorithm
Step1- Start Step 2- Declare 6 double values: a, b, c, root_1, root_2, quadratic_equation Step 3- Prompt the user to enter a,b,c double values/ define the double values Step 4- Read the values Step 5- In a for loop, check if the value of quadratic_equation variable is greater than 0, and if true, use quadric formula to find the value, and assign it to a variable. Step 6- Display the result Step 7- Stop
Example 1
Here, the input is being entered by the user based on a prompt. You can try this example live in ourcoding ground tool .
import java.util.Scanner; public class QuadraticEquation < public static void main(String[] args) < double a, b, c, root_1, root_2, quadratic_equation; double real_number, imaginary_number; System.out.println("Required packages have been imported"); Scanner my_scanner = new Scanner(System.in); System.out.println("A scanner object has been defined "); System.out.print("Enter the value of a : "); a = my_scanner.nextDouble(); System.out.print("Enter the value of b : "); b = my_scanner.nextDouble(); System.out.print("Enter the value of c : "); c = my_scanner.nextDouble(); quadratic_equation = b*b - 4*a*c ; if (quadratic_equation >0) < root_1 = (-b + Math.sqrt(quadratic_equation)) / (2 * a); root_2 = (-b - Math.sqrt(quadratic_equation)) / (2 * a); System.out.format("root_1 = %.2f and root_2 = %.2f", root_1, root_2); >else if (quadratic_equation == 0) < root_1 = root_2 = -b / (2 * a); System.out.format("root_1 = root_2 = %.2f;", root_1); >else < real_number = -b / (2 * a); imaginary_number = Math.sqrt(-quadratic_equation) / (2 * a); System.out.println("The roots of the quadratic equation are"); System.out.printf("root_1 = %.2f+%.2fi", real_number, imaginary_number); System.out.printf("\nroot_2 = %.2f-%.2fi", real_number, imaginary_number); >> >
Output
Required packages have been imported A scanner object has been defined Enter the value of a : 1 Enter the value of b : 2 Enter the value of c : 3 The roots of the quadratic equation are root_1 = -1.00+1.41i root_2 = -1.00-1.41i
Example 2
Here, the integer has been previously defined, and its value is accessed and displayed on the console.
public class QuadraticEquation < public static void main(String[] args) < double a, b, c, root_1, root_2, quadratic_equation; double real_number, imaginary_number; a = 1; b = 2; c = 3; System.out.println("The three numbers are defined as " +a +", " +b +" and " +c); quadratic_equation = b*b - 4*a*c ; if (quadratic_equation >0) < root_1 = (-b + Math.sqrt(quadratic_equation)) / (2 * a); root_2 = (-b - Math.sqrt(quadratic_equation)) / (2 * a); System.out.format("root_1 = %.2f and root_2 = %.2f", root_1, root_2); >else if (quadratic_equation == 0) < root_1 = root_2 = -b / (2 * a); System.out.format("root_1 = root_2 = %.2f;", root_1); >else < real_number = -b / (2 * a); imaginary_number = Math.sqrt(-quadratic_equation) / (2 * a); System.out.println("The roots of the quadratic equation are"); System.out.printf("root_1 = %.2f+%.2fi", real_number, imaginary_number); System.out.printf("\nroot_2 = %.2f-%.2fi", real_number, imaginary_number); >> >
Output
The three numbers are defined as 1.0, 2.0 and 3.0 The roots of the quadratic equation are root_1 = -1.00+1.41i root_2 = -1.00-1.41i
Java Program to Find the Roots of a Quadratic Equation
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.
The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.
To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.
Connect your cluster and start monitoring your K8s costs right away:
We’re looking for a new Java technical editor to help review new articles for the site.
1. Overview
In this article, we’ll see how to compute the solutions of a quadratic equation in Java. We’ll start by defining what a quadratic equation is, and then we’ll compute its solutions whether we work in the real or the complex number system.
2. The Solutions of a Quadratic Equation
Given real numbers a ≠ 0, b and c, let’s consider the following quadratic equation: ax² + bx + c = 0.
2.1. The Roots of a Polynomial
The solutions of this equation are also called the roots of the polynomial ax² + bx + c. Thus, let’s define a Polynom class. We’ll throw an IllegalArgumentException if the a coefficient is equal to 0:
public class Polynom < private double a; private double b; private double c; public Polynom(double a, double b, double c) < if (a==0) < throw new IllegalArgumentException("a can not be equal to 0"); >this.a = a; this.b = b; this.c = c; > // getters and setters >
We’ll solve this equation in the real number system: for this, we’ll look for some Double solutions.
2.2. Complex Number System
We’ll also show how to solve this equation in the complex number system. There is no default representation of a complex number in Java, so we’ll create our own. Let’s give it a static method ofReal to easily convert real numbers. This will be helpful in the following steps:
public class Complex < private double realPart; private double imaginaryPart; public Complex(double realPart, double imaginaryPart) < this.realPart = realPart; this.imaginaryPart = imaginaryPart; >public static Complex ofReal(double realPart) < return new Complex(realPart, 0); >// getters and setters >
3. Calculate the Discriminant
The quantity Δ = b² – 4ac is called the discriminant of the quadratic equation. To calculate b squared in java, we have two solutions:
Let’s stick with the first method and add a getDiscriminant method to the Polynom class:
public double getDiscriminant()
4. Get the Solutions
Depending on the value of the discriminant, we’re able to know how many solutions exist and compute them.
4.1. With a Strictly Positive Discriminant
If the discriminant is strictly positive, the equation has two real solutions, (-b – √Δ) / 2a and (-b + √Δ) / 2a:
Double solution1 = (-polynom.getB() - Math.sqrt(polynom.getDiscriminant())) / (2 * polynom.getA()); Double solution2 = (-polynom.getB() + Math.sqrt(polynom.getDiscriminant())) / (2 * polynom.getA());
If we work in the complex number system, we then just need to make the conversion:
Complex solution1 = Complex.ofReal((-polynom.getB() - Math.sqrt(polynom.getDiscriminant())) / (2 * polynom.getA())); Complex solution2 = Complex.ofReal((-polynom.getB() + Math.sqrt(polynom.getDiscriminant())) / (2 * polynom.getA()));
4.2. With a Discriminant Equal to Zero
If the discriminant is equal to zero, the equation has a unique real solution -b / 2a:
Double solution = (double) -polynom.getB() / (2 * polynom.getA());
Similarly, if we work in a complex number system, we’ll transform the solution in the following way:
Complex solution = Complex.ofReal(-polynom.getB() / (2 * polynom.getA()));
4.3. With a Strictly Negative Discriminant
If the discriminant is strictly negative, the equation has no solution in the real number system. However, it can be solved in the complex number system: the solutions are (-b – i√-Δ) / 2a and its conjugate (-b + i√-Δ) / 2a:
Complex solution1 = new Complex(-polynom.getB() / (2* polynom.getA()), -Math.sqrt(-polynom.getDiscriminant()) / 2* polynom.getA()); Complex solution2 = new Complex(-polynom.getB() / (2* polynom.getA()), Math.sqrt(-polynom.getDiscriminant()) / 2* polynom.getA());
4.4. Gather the Results
To sum up, let’s build a method that will fill in a List with the solutions of the equation when they exist. In the real number system, this method looks like this:
public static List getPolynomRoots(Polynom polynom) < Listroots = new ArrayList<>(); double discriminant = polynom.getDiscriminant(); if (discriminant > 0) < roots.add((-polynom.getB() - Math.sqrt(discriminant)) / (2 * polynom.getA())); roots.add((-polynom.getB() + Math.sqrt(discriminant)) / (2 * polynom.getA())); >else if (discriminant == 0) < roots.add(-polynom.getB() / (2 * polynom.getA())); >return roots; >
If we work in a complex number system, we’ll rather write:
public static List getPolynomRoots(Polynom polynom) < Listroots = new ArrayList<>(); double discriminant = polynom.getDiscriminant(); if (discriminant > 0) < roots.add(Complex.ofReal((-polynom.getB() - Math.sqrt(discriminant)) / (2 * polynom.getA()))); roots.add(Complex.ofReal((-polynom.getB() + Math.sqrt(discriminant)) / (2 * polynom.getA()))); >else if (discriminant == 0) < roots.add(Complex.ofReal(-polynom.getB() / (2 * polynom.getA()))); >else < roots.add(new Complex(-polynom.getB() / (2* polynom.getA()), -Math.sqrt(-discriminant) / 2* polynom.getA())); roots.add(new Complex(-polynom.getB() / (2* polynom.getA()), Math.sqrt(-discriminant) / 2* polynom.getA())); >return roots; >
5. Conclusion
In this tutorial, we’ve seen how to solve a quadratic equation in Java, whether we work with real or complex numbers.
As always, the code can be found over on GitHub.
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
Java: Solve quadratic equations
Java Conditional Statement: Exercise-2 with Solution
Write a Java program to solve quadratic equations (use if, else if and else).
Test Data
Input a: 1
Input b: 5
Input c: 1
Pictorial Presentation:
Sample Solution:
import java.util.Scanner; public class Exercise2 < public static void main(String[] Strings) < Scanner input = new Scanner(System.in); System.out.print("Input a: "); double a = input.nextDouble(); System.out.print("Input b: "); double b = input.nextDouble(); System.out.print("Input c: "); double c = input.nextDouble(); double result = b * b - 4.0 * a * c; if (result >0.0) < double r1 = (-b + Math.pow(result, 0.5)) / (2.0 * a); double r2 = (-b - Math.pow(result, 0.5)) / (2.0 * a); System.out.println("The roots are " + r1 + " and " + r2); >else if (result == 0.0) < double r1 = -b / (2.0 * a); System.out.println("The root is " + r1); >else < System.out.println("The equation has no real roots."); >> >
Input a: 1 Input b: 5 Input c: 2 The roots are -0.4384471871911697 and -4.561552812808831
Java Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource’s quiz.
Follow us on Facebook and Twitter for latest update.
Java: Tips of the Day
Convert boolean to int in Java
int myInt = myBoolean ? 1 : 0;
Note : true = 1 and false = 0
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook
Java solve quadratic equation
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter