Finding roots of quadratic equation - java

I have this code so far but every time i run and put the three numbers in a get the roots are NaN can some one please help or point me to where i went wrong.
import java.util.Scanner;
class Quadratic {
public static void main(String[] args) {
System.out.println("Enter three coefficients");
Scanner sc = new Scanner(System.in);
double a = sc.nextDouble();
double b = sc.nextDouble();
double c = sc.nextDouble();
double root1= (-b + Math.sqrt( b*b - 4*a*c ) )/ (2*a);
double root2= (-b - Math.sqrt( b*b - 4*a*c ) )/ (2*a);
System.out.println("The roots1 are: "+ root1);
System.out.println("The roots2 are: " + root2);
}
}

You have to remember that not every quadratic equation has roots that can be expressed in terms of real numbers. More specifically, if b*b - 4*a*c < 0, then the roots will have an imaginary part and NaN will be returned, since Math.sqrt of a negative number returns NaN, as specified in the documentation. This works for coefficients such that b*b - 4*a*c >= 0, however:
Enter three coefficients
1
5
6
The roots1 are: -2.0
The roots2 are: -3.0
If you wanted to account for non-real roots as well, you could do something like
double d = (b * b - 4 * a * c);
double re = -b / (2 * a);
if (d >= 0) { // i.e. "if roots are real"
System.out.println(Math.sqrt(d) / (2 * a) + re);
System.out.println(-Math.sqrt(d) / (2 * a) + re);
} else {
System.out.println(re + " + " + (Math.sqrt(-d) / (2 * a)) + "i");
System.out.println(re + " - " + (Math.sqrt(-d) / (2 * a)) + "i");
}

Hope this helps--
import java.util.Scanner;
class QuadraticCalculator
{
public static void main(String args[])
{
Scanner s=new Scanner(System.in);
double a,b,c,quad_dis,quad_11,quad_1,quad_21,quad_2;
System.out.println("Enter the value of A");
a=s.nextDouble();
System.out.println("\nEnter the value of B");
b=s.nextDouble();
System.out.println("\nEnter the value of C");
c=s.nextDouble();
quad_dis=b*b-4*a*c;
quad_11=(-1*b)+(Math.sqrt(quad_dis));
quad_1=quad_11/(2*a);
quad_21=(-1*b)-(Math.sqrt(quad_dis));
quad_2=quad_21/(2*a);
int choice;
System.out.println("\n\nWhat do you want to do with the numbers you entered ?\n(1) Calculate Discriminant\n(2) Calculate the values\n(3) Find the nature of roots\n(4) All of the above");
choice=s.nextInt();
switch(choice)
{
case 1: System.out.println("\nDiscriminant: "+quad_dis);
break;
case 2: System.out.println("\nValues are: "+quad_1+", "+quad_2);
break;
case 3: if(quad_dis>0)
{
System.out.println("\nThe roots are REAL and DISTINCT");
}
else if(quad_dis==0)
{
System.out.println("\nThe roots are REAL and EQUAL");
}
else
{
System.out.println("\nThe roots are IMAGINARY");
}
break;
case 4: System.out.println("\nDiscriminant: "+quad_dis);
System.out.println("\nValues are: "+quad_1+", "+quad_2);
if(quad_dis>0)
{
System.out.println("\nThe roots are REAL and DISTINCT");
}
else if(quad_dis==0)
{
System.out.println("\nThe roots are REAL and EQUAL");
}
else
{
System.out.println("\nThe roots are IMAGINARY");
}
break;
}
System.out.println("\n\nThank You for using this Calculator");
}
}

You could use the following code. First, it will check whether input equation is quadratic or not. And if input equation is quadratic then it will find roots.
This code is able to find complex roots too.
public static void main(String[] args) {
// Declaration of variables
float a = 0, b = 0, c = 0, disc, sq_dis;
float[] root = new float[2];
StringBuffer number;
Scanner scan = new Scanner(System.in);
// Input equation from user
System.out.println("Enter Equation in form of ax2+bx+c");
String equation = scan.nextLine();
// Regex for quadratic equation
Pattern quadPattern = Pattern.compile("(([+-]?\\d*)[Xx]2)+((([+-]?\\d*)[Xx]2)*([+-]\\d*[Xx])*([+-]\\d+)*)*|((([+-]?\\d*)[Xx]2)*([+-]\\d*[Xx])*([+-]\\d+)*)*(([+-]?\\d*)[Xx]2)+|((([+-]?\\d*)[Xx]2)*([+-]\\d*[Xx])*([+-]\\d+)*)*(([+-]?\\d*)[Xx]2)+((([+-]?\\d*)[Xx]2)*([+-]\\d*[Xx])*([+-]\\d+)*)*");
Matcher quadMatcher = quadPattern.matcher(equation);
scan.close();
// Checking if given equation is quadratic or not
if (!(quadMatcher.matches())) {
System.out.println("Not a quadratic equation");
}
// If input equation is quadratic find roots
else {
// Splitting equation on basis of sign
String[] array = equation.split("(?=[+-])");
for (String term : array) {
int len = term.length();
StringBuffer newTerm = new StringBuffer(term);
// If term ends with x2, then delete x2 and convert remaining term into integer
if (term.endsWith("X2") || (term.endsWith("x2"))) {
number = newTerm.delete(len - 2, len);
a += Integer.parseInt(number.toString());
}
// If term ends with x, then delete x and convert remaining term into integer
else if (term.endsWith("X") || (term.endsWith("x"))) {
number = newTerm.deleteCharAt(len - 1);
b += Integer.parseInt(number.toString());
}
// If constant,then convert it into integer
else {
c += Integer.parseInt(term);
}
}
// Display value of a,b,c and complete equation
System.out.println("Coefficient of x2: " + a);
System.out.println("Coefficient of x: " + b);
System.out.println("Constent term: " + c);
System.out.println("The given equation is: " + a + "x2+(" + b + ")x+(" + c + ")=0");
// Calculate discriminant
disc = (b * b) - (4 * a * c);
System.out.println(" Discriminant= " + disc);
// square root of discriminant
sq_dis = (float) Math.sqrt(Math.abs(disc));
// conditions to find roots
if (disc > 0) {
root[0] = (-b + sq_dis) / (2 * a);
root[1] = (-b - sq_dis) / (2 * a);
System.out.println("Roots are real and unequal");
System.out.println("Root1= " + root[0]);
System.out.println("Root2= " + root[1]);
}
else if (disc == 0) {
root[0] = ((-b) / (2 * a));
System.out.println("Roots are real and equal");
System.out.println("Root1=Root2= " + root[0]);
}
else {
root[0] = -b / (2 * a);
root[1] = Math.abs((sq_dis) / (2 * a));
System.out.println("Roots are complex");
System.out.println("ROOT1= " + root[0] + "+" + root[1] + "+i");
System.out.println("ROOT2= " + root[0] + "-" + root[1] + "+i");
}
}

else {
if ((Math.sqrt(-d) / (2*a)) > 0) {
System.out.println(r + " + " + (Math.sqrt(-d) / (2*a)) + " i");
System.out.println(r + " - " + (Math.sqrt(-d) / (2*a)) + " i");
}
else if ((Math.sqrt(-d) / (2*a)) == 0){
System.out.println(r);
}
else {
System.out.println(r + " - " + (Math.sqrt(-d) / (2*a)) + " i");
System.out.println(r + " + " + (Math.sqrt(-d) / (2*a)) + " i");
}

Related

How to make my code output more decimal places

I have an homework assignment to:
Write a program to calculate the result of one of three operations (minimum, L1 norm, L2 norm) on a vector of three numbers.
All my code is right, I think, but I need my outputs to have 2 decimal places. How would I do this?
import java.io.*;
import java.util.*;
import java.lang.*;
public class LA3a {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter three numbers: ");
double a = sc.nextDouble();
double b = sc.nextDouble();
double c = sc.nextDouble();
System.out.print("Enter operation: ");
String opr = sc.next();
if (opr.equals("min")) {
System.out.print("min(" , a , ", " , b , ", " , c , ")=");
if (a < b) {
if (a < c) {
System.out.print(a);
System.out.println();
}
else {
System.out.print(c);
System.out.println();
}
}
else {
if (b < c) {
System.out.print(b);
System.out.println();
}
else {
System.out.print(c);
System.out.println();
}
}
}
else if (opr.equals("l1")) {
double sum = Math.abs(a) + Math.abs(b) + Math.abs(c);
System.out.println("l1(" + a + ", " + b + ", " + c + ")=" + sum);
}
else if (opr.equals("l2")) {
double sum = a * a + b * b + c * c;
System.out.println("l2(" + a + ", " + b + ", " + c + ")=" + String.format("%.2f", Math.sqrt(sum)));
}
else {
System.out.println("Invalid operation!");
}
}
}
you can use printf to have a formatted print of a decimal number with 2 decimal places.
System.out.printf("%.2f", b);
the %.2f syntax tells Java to return your variable (b) with 2 decimal places. if you want more decimal places just increase it like: %.3f for 3 decimal places or %.4f for 4 decimal places.
I updated my code to:
if (a < b) {
if (a < c) {
System.out.printf("%.2f", a);
System.out.println();
}
else {
System.out.printf("%.2f", c);
System.out.println();
}
}
else {
if (b < c) {
System.out.printf("%.2f", b);
System.out.println();
}
else {
System.out.printf("%.2f", c);
System.out.println();
}
}
}
and my output is still only coming out as:
Enter three numbers: 1 2 3
Enter operation: min
min(1.0, 2.0, 3.0) = 1.00 - I still need this line to come out with 2 decimal places for each number.
For this part, there is an error:
System.out.print("min(" , a , ", " , b , ", " , c , ")=");
You put a bunch of commas instead of addition operators, your code should look like this:
System.out.print("min(" + a + ", " + b + ", " + c + ")=");
Also you have a common print statement in the following if/else statement:
if (a < c) {
System.out.print(a);
System.out.println();
}
else {
System.out.print(c);
System.out.println();
}
You should extract the print statement and use a call to Math.min() instead of an if statement to make it look something like this:
System.out.print(Math.min(a, c));
System.out.println();
As for having your output display two decimal places, Java has a class called DecimalFormat which can be imported with java.text.DecimalFormat; Create a new DecimalFormat like this:
DecimalFormat df = new DecimalFormat("#0.00"); //#0.00 means that we have two zeros after the decimal place
This makes a new DecimalFormat object that we can use to convert our numbers to Strings. For example, your print statement for the l1 operation should look something like this:
System.out.println("l1(" + df.format(a) + ", " + df.format(b) + ", " + df.format(c) + ")=" + df.format(sum));

I am trying to build a basic calculator using if statements

I am trying to make a basic calculator for class.
I came up with the code below but all it does it addition.
Even if I use -, *, or /.
Any tips?
Scanner input = new Scanner(System.in);
String num1, num2, operation, function;
System.out.println("Enter a simple equation: ");
function = input.nextLine();
int firstspace = function.indexOf(" ");
num1 = (function.substring(0,firstspace));
int lastspace = function.lastIndexOf(" ");
operation = (function.substring(firstspace,lastspace));
num2= (function.substring(lastspace+1,function.length()));
double n1 = Double.parseDouble(num1);
double n2 = Double.parseDouble(num2);
if (operation.equals(" + "));
{
System.out.println("your answer is " + (n1 + n2));
}
if (operation.equals(" - "))
{
System.out.println("your answer is " + (n1 - n2));
}
if (operation.equals(" / "))
{
System.out.println("your answer is " + (n1 / n2));
}
if (operation.equals(" * "))
{
System.out.println("your answer is " + ( n1*n2));
}
}
}
From what I see your code has this issue
if (operation.equals(" + "));
{
System.out.println("your answer is " + (n1 + n2));
}
Here you are putting a semi colon, which means when you run the code,it will execute this condition by default, so that means addition will always execute whether you like it or not.
So basically your code should be like this
if (operation.equals("+" ))
{
System.out.println("your answer is " + (n1 + n2));
}
if (operation.equals("-"))
{
System.out.println("your answer is " + (n1 - n2));
}
if (operation.equals("/"))
{
System.out.println("your answer is " + (n1 / n2));
}
if (operation.equals("*"))
{
System.out.println("your answer is " + ( n1*n2));
}
Hope this helps

How can I change this if-statement to switch?

//is the following code about quadratic formulas convertible to switch method?
Public class blah blah
Public static void main(String[] args) {
System.out.println("enter letter a");
New Scanner= System.in
Int a = input.nextint()
//same thing repeated for letters b and c.
//int d is for discriminant.
Int d= math.pow(b^2 -4ac, 0.5);
Int r1= (-(b) - (d))/2(a)
Int r2= (-(b) + (d))/2(a)
If(d>0){
System.out.println("2 solutions: r1; " + r1+ " and r2" + r2);
}else if(d=0){
System.out.println("1 solutions: r1; " + r1+ " and r2" + r2);
}else{
System.out.println("no real solution");
}
If you really really really wanna use a switch case
private static void switchOnIntegerPolarity() {
int a = 1;
int b = 2;
int c = 3;
int d = (int) Math.pow(b ^ 2 - 4 * a * c, 0.5);
int r1 = (-(b) - (d)) / 2 * (a);
int r2 = (-(b) + (d)) / 2 * (a);
switch ((int) Math.signum(d)) {
case 0: // Zero
System.out.println("1 solutions: r1; " + r1 + " and r2" + r2);
break;
case 1: // 'd' is Positive
System.out.println("2 solutions: r1; " + r1 + " and r2" + r2);
break;
case -1: // 'd' is Negative
System.out.println("no real solution");
break;
}
}

Solving quadratic equation USING METHODS, java

I have a java program written for solving the quadratic equation but the assignment requires me to have methods for each of the tasks: displaying the equation, determining if the equation has real solutions, calculating a solution, and displaying the solutions if they exist. I have methods for everything except for checking if the solutions are real except my methods are saying that they are undefined. Can someone please help me format my methods, I don't quite know how to implement them? here is the code I have thus far:
import java.util.Scanner;
public class QuadraticFormula {
public static void main(String[] args)
{
//Creating scanner and variables
Scanner s = new Scanner(System.in);
System.out.println("Insert value for a: ");
double a = Double.parseDouble(s.nextLine());
System.out.println("Insert value for b: ");
double b = Double.parseDouble(s.nextLine());
System.out.println("Insert value for c: ");
double c = Double.parseDouble(s.nextLine());
//Display format for negatives
displayEquation(double a, double b, double c);{
if (b > 0 && c > 0 ){
System.out.println(a + "x^2 + " + b + "x + " + c + " =0");}
if (b < 0 && c > 0 ){
System.out.println(a + "x^2 " + b + "x + " + c + " =0");}
if (b > 0 && c < 0 ){
System.out.println(a + "x^2 + " + b + "x " + c + " =0");}
if (b < 0 && c < 0 ){
System.out.println(a + "x^2 " + b + "x " + c + " =0");}
s.close();
}
//The work/formula
private static double calculateSolution(double a, double b, double c);
{
double answer1 = (-b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
return answer1;
}
private static double calculateSolution(double a, double b, double c);
{
double answer2 = (-b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
return answer2;
}
//Display results and check if the solution is imaginary (real or not)
private static void displaySolutions(double answer1, double answer2); {
if (Double.isNaN(answer1) || Double.isNaN(answer2))
{
System.out.println("Answer contains imaginary numbers");
} else System.out.println("The values are: " + answer1 + ", " + answer2);
}
}
}
Your methods need to be defined outside your main method. You can then call them in your main method like this:
displayEquation(a, b, c);
You also should remove the semicolons after your method definitions. It should look like this:
public class QuadraticFormula {
public static void main(String[] args)
{
//Creating scanner and variables
Scanner s = new Scanner(System.in);
System.out.println("Insert value for a: ");
double a = Double.parseDouble(s.nextLine());
System.out.println("Insert value for b: ");
double b = Double.parseDouble(s.nextLine());
System.out.println("Insert value for c: ");
double c = Double.parseDouble(s.nextLine());
s.close();
}
//Display format for negatives
public static void displayEquation(double a, double b, double c) {
if (b > 0 && c > 0 ){
System.out.println(a + "x^2 + " + b + "x + " + c + " =0");}
if (b < 0 && c > 0 ){
System.out.println(a + "x^2 " + b + "x + " + c + " =0");}
if (b > 0 && c < 0 ){
System.out.println(a + "x^2 + " + b + "x " + c + " =0");}
if (b < 0 && c < 0 ){
System.out.println(a + "x^2 " + b + "x " + c + " =0");}
}
private static double calculateSolution(double a, double b, double c) {
double answer2 = (-b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
return answer2;
}
//Display results and check if the solution is imaginary (real or not)
private static void displaySolutions(double answer1, double answer2) {
if (Double.isNaN(answer1) || Double.isNaN(answer2))
{
System.out.println("Answer contains imaginary numbers");
}
else System.out.println("The values are: " + answer1 + ", " + answer2);
}
}

Java clarification on += assignment operator

I'm a bit confused about how += assignment operator works. I know that x += 1 is x = x+1. However, in this code there is a string variable called 'String output' and initialized with an empty string. My confusion is that that there are 5 different outputs for the variable 'output' but I don't see where it's being stored. Help clarify my misunderstanding. I can't seem to figure it out.
import java.util.Scanner;
public class SubtractionQuiz {
public static void main(String[] args) {
final int NUMBER_OF_QUESTIONS = 5; //number of questions
int correctCount = 0; // Count the number of correct answer
int count = 0; // Count the number of questions
long startTime = System.currentTimeMillis();
String output = " "; // Output string is initially empty
Scanner input = new Scanner(System.in);
while (count < NUMBER_OF_QUESTIONS) {
// 1. Generate two random single-digit integers
int number1 = (int)(Math.random() * 10);
int number2 = (int)(Math.random() * 10);
// 2. if number1 < number2, swap number1 with number2
if (number1 < number2) {
int temp = number1;
number1 = number2;
number2 = temp;
}
// 3. Prompt the student to answer "What is number1 - number2?"
System.out.print(
"What is " + number1 + " - " + number2 + "? ");
int answer = input.nextInt();
// 4. Grade the answer and display the result
if (number1 - number2 == answer) {
System.out.println("You are correct!");
correctCount++; // Increase the correct answer count
}
else
System.out.println("Your answer is wrong.\n" + number1
+ " - " + number2 + " should be " + (number1 - number2));
// Increase the question count
count++;
output += "\n" + number1 + "-" + number2 + "=" + answer +
((number1 - number2 == answer) ? " correct" : "
wrong");
}
long endTime = System.currentTimeMillis();
long testTime = endTime = startTime;
System.out.println("Correct count is " + correctCount +
"\nTest time is " + testTime / 1000 + " seconds\n" + output);
}
}
Answer given by Badshah is appreciable for your program and if you want to know more about operator' usability, jst check out this question i came across
+ operator for String in Java
The answers posted have very good reasoning of the operator
Its Add AND assignment operator.
It adds right operand to the left operand and assign the result to left operand.
In your case
output += someString // output becomes output content +somestring content.
`
Maybe the proper answer was written but if I understand your question correctly, you want some clarification instead of meaning of +=
Change the code;
// Increase the question count
count++;
output += "\n" + number1 + "-" + number2 + "=" + answer +
((number1 - number2 == answer) ? " correct" : "wrong");
as this:
output += "\nCount: " + count + " and the others: " +
number1 + "-" + number2 + "=" + answer +
((number1 - number2 == answer) ? " correct" : "wrong");
// Increase the question count
count++;
So you can see the line and the count together. Then increase as your wish.
In Java, Strings are immutable. So output += somethingNew makes something like this:
String temp = output;
output = temp + somethingNew;
At the end, it becomes something like concat/merge

Categories

Resources