quadratic equation solver fails to get result in Java - java

I have code that is supposed to solve a quadratic equation but yields NaN as a result.
I've looked around for 2 days now and I can't find a solution. Any and all advice will be more than appreciated!
package quadratic;
import java.util.Scanner;
public class Formlua {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter value of A ");
double a = input.nextDouble();
System.out.println("enter value of B ");
double b = input.nextDouble();
System.out.println("enter value of C ");
double c = input.nextDouble();
double four = 4;
double square = Math.sqrt(b* b - 4 * a * c );
double root1 = (-b + square) / (2*a);
double root2 = (-b - square) / (2*a);
System.out.println("The answer is " + root1 + "and" + root2);
System.out.println("Do you want to continue? y/n");
String user = input.toString();
if(user.equalsIgnoreCase("y"));
}
}

This code:
Math.sqrt(b* b - 4 * a * c );
can result in NaN ("not a number").
If the value of b* b - 4 * a * c is negative, there are solutions only in complex numbers (but not in double data type)
There should be a condition
if (b* b - 4 * a * c<0) {
System.out.println("There is no solution in real numbers");
return;
}

The most likely cause of the problem is Math.sqrt(b*b - 4 * a * c). or one of your input values is NaN (probably not the cause in this situation).
There are two special cases:
b *b < 4 * a * c
and a = 0
if b * b < 4 * a * c your answer is in the complex plane (specifically, not a real number).
if a = 0 then you actually just have a linear equation.
you could try the following code:
package quadratic;
import java.util.Scanner;
public class Formlua {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("enter value of A ");
double a = input.nextDouble();
System.out.println("enter value of B ");
double b = input.nextDouble();
System.out.println("enter value of C ");
double c = input.nextDouble();
if (a == 0){
// 0 = 0*x*x + b*x + c ==> x = -c/b
System.out.println("X = " + Double.toString(-c/b));
} else {
double inner = b * b - 4 * a * c;
if (inner < 0){
inner = -inner;
inner = Math.sqrt(inner);
System.out.println("X = " + Double.toString(-b) + " + " + Double.toString(inner) + "i")
System.out.println(" = " + Double.toString(-b) + " - " + Double.toString(inner) + "i");
} else {
inner = Math.sqrt(inner);
System.out.println("X = " + Double.toString(-b));
if (inner == 0){
} else {
System.out.println("X = " + Double.toString(-b + inner));
System.out.println("X = " + Double.toString(-b - inner));
}
}
}
}
This lets your user input any double values and recieve an answer.

Related

Correcting a formula in java

My first assignment requires me to write a program that expresses a formula. The formula as written in the assignment :
y = 4x^3 + 8x^2 - 31x - 35 / (3x2 + 1)^1/2 + 2 * | x - 1.5 |
| means absolute value; (...)1/2 means square root
Also how should I create a code that prints how many times the formula prints out a positive or negative number or zero?
Here is how I created my assignment's program:
import java.io.*;
public class hw1 {
public static void main(String[] args) throws IOException
{
System.out.println("My name is Jibran Khan and this is the output of my first program.");
double x; double y;
PrintWriter outFile = new PrintWriter("testfile.txt");
for(x=-3.00; x <= 3.0; x = x + 0.50)
{
y=((4*(x*x*x))) + (8*(x*x))-(31*x)-35/Math.sqrt(3*x*x+1)+2* Math.abs(x-1.5);
System.out.println("X = " + x + "Y = " + y );
if (y<=0.0) System.out.println("Y is negative");
if (y>=0.0) System.out.println("Y is positive");
if (y == 0.0) System.out.println("Y is zero");
}
System.out.println();
System.out.println("My first program is complete");
outFile.close();
}
}
OK, you want to make a test on a simple math formula. You have to test the results and define how many results are positive, negative or equal to 0 ...
You have to update your tests... It result is equal to 0, your test returns positive, negative and null results.
You also have to count results. So implement counters for each type of results and increment them in the if statement.
public static void main(String[] args) throws IOException {
double x; double y;
int positive = 0;
int negative = 0;
int equalZero = 0;
PrintWriter outFile = new PrintWriter("testfile.txt");
for(x=-3.00; x <= 3.0; x = x + 0.50) {
y = Math.pow(4,3) + ... ( your formula)
System.out.println("X = " + x + "Y = " + y );
if (y < 0.0) {
System.out.println("Y is negative");
negative++;
} else if (y > 0.0) {
System.out.println("Y is positive");
positive++;
} else {
System.out.println("Y is zero");
equalZero++;
}
}
System.out.println();
System.out.println("Positive results : " + positive);
System.out.println("Negative results : " + negative);
System.out.println("Equal to zero : " + equalZero);
outFile.close();
}
Calculate the Denominator and Numerator in different variables, that will give more readability and you will be able to spot the mistakes easily.
Also, the conditions you gave for y: (y <= 0.0) and (y >= 0.0) will be true for zero so the last condition y == 0.0 is not reachable.

I can't figure out how to find the two imaginary numbers

So, I wrote a Java program that finds the solutions to a quadratic equation and my problem is I can't seem to write the right code to find the "imaginary numbers" when it prints out I just get "NaN". Any solutions?
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the value for a: ");
double a = scan.nextDouble();
System.out.print("Enter the value for b: ");
double b = scan.nextDouble();
System.out.print("Enter the value for c: ");
double c = scan.nextDouble();
double result = b * b - 4.0 * a * c;
if(result > 0.0){
//to find two real solutions
double x1 = (-b + Math.pow(result, 0.5)) / (2.0 * a);
double x2 = (-b - Math.pow(result, 0.5)) / (2.0 * a);
System.out.println("There are two real solutions.");
System.out.println("x1 = " + x1);
System.out.println("x2 = " + x2);
//to find one real solution
} else if(result == 0.0){
double x1 = (-b / (2.0 * a));
System.out.println("There is one real solution");
System.out.println("x = " + x1);
//to find the imaginary numbers
} else if(result < 0.0){
double x1 = (-b + Math.pow(result, 0.5)) / (2.0 * a);
double x2 = (-b - Math.pow(result, 0.5)) / (2.0 * a);
System.out.println("There are two imaginary solutions.");
System.out.println("x1 = " + x1 + " + " + x2);
System.out.println("x2 = " + x1 + " - " + x2);
}
}
}
There are a couple of incorrect things in your code when handling complex roots (when result < 0):
You are attempting to evaluate the square root of result which is negative. This is will result in a NaN. The correct approach is to get the square root of -result to get your answer.
The way you are calculating the roots is incorrect. Both roots will have the same real part which is -b/(2*a) and the same value for imaginary part, differing only in its sign.
I fixed your code below to give a correct output. The real part is calculated and then the imaginary part is calculated. Roots are then printed with the imaginary parts suffixed with an 'i' to denote the imaginary part.
double real = -b / (2*a);
double imag = Math.pow(-result, 0.5) / (2.0 * a);
System.out.println("There are two imaginary solutions.");
System.out.println("x1 = " + real + " + " + imag + "i");
System.out.println("x2 = " + real + " - " + imag + "i");

factorable trinomial / polynomial

so I want to create a program that prints out a factorable quadratic equation when the user enters a value, c, and a = 1,. The program should determine all the possible Integer values of b so that the trinomial prints out in the form x^2 + bx + c
An example would be if the user entered -4 for c the program should print out:
x^2 - 4
x^2 - 3x - 4
So far this is what I have done with my code, I am trying to figure out how to execute the program but I really am having trouble of where to go from here. If anyone can offer some help that would be much appreciated!
public class FactorableTrinomials
{
public static void main (String [] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("A trinomial in standard form is ax^2 + bx +
c. \nIf a = 1, this program will output all factorable trinomials
given the entered c value.");
System.out.print("\nEnter an integer ā€œcā€ value: ");
int numC = scan.nextInt();
final int NUMA= 1;
int numB;
if (numC > 0)
{
int factors;
System.out.print("\nThe factors of " + numC + " are: ");
for(factors = 1; factors <= numC; factors++) //determines
factors and how many there are
{
if(numC % factors == 0)
{
System.out.print(factors + " ");
}
}
First, find the pairs of integer which multiplies to c.
all possible values of b will then be the sum of the pair of integer.
A simple way to find the pairs of integer is to loop 2 variables from -c to c and check if the product is c. eg:
for(int i = -1 * numC; i <= numC; i++) {
for(int j = -1* numC; j<= numC;j++) {
if(i * j == numC) {
int b = i + j;
//print solution, if b == 0 then don't print the second term
}
}
}

quadratic formula with scanner inputs

Okay so I am a complete Java noob, and I'm trying to create a program for class that runs a quadratic equation using scanner inputs. So far what I've got is this:
import java.util.*;
public class QuadraticFormulaSCN {
public static void main(String[]args) {
System.out.println("insert value for a:");
Scanner scan1 = new Scanner(System.in);
double a = scan1.nextDouble();
System.out.println("insert value for b:");
Scanner scan2 = new Scanner(System.in);
double b = scan2.nextDouble();
System.out.println("insert value for C:");
Scanner scan3 = new Scanner(System.in);
double c = scan3.nextDouble();
double answer =((Math.sqrt(Math.pow(b,2)-(4*a*c))-b)/2);
double final2 =(-b + Math.sqrt(Math.pow(b,2)-(4*a*c)))/2;
System.out.println("The x values are:" + answer + final2);
}
}
But I get a weird output, specifically NaNaN... What do I do to fix this? What am I doing wrong?
I'm a little late to answer, but I corrected your problems (described in the other answers), fixed one of your calculations, and cleaned up your code.
import java.util.*;
public class Test {
public static void main(String[] args)
{
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();
double answer1 = (-b + Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
double answer2 = (-b - Math.sqrt(Math.pow(b, 2) - (4 * a * c))) / (2 * a);
if (Double.isNaN(answer1) || Double.isNaN(answer2))
{
System.out.println("Answer contains imaginary numbers");
} else System.out.println("The values are: " + answer1 + ", " + answer2);
}
}
NaN is something you get when the calculation is invalid. Such as dividing by 0 or taking the squareroot of -1.
When I test your code with a = 1, b = 0 and c = -4 the answers is 2.02.0
The formatting is not right and the calculation of final2 is not negated.
Otherwise the code is right.
To improve you could check whether the discriminant is negative.
double d = b*b -4 * a * c;
if (d < 0){
System.out.println("Discriminant < 0, no real solutions" );
return;
}
double x1 = (-b -sqrt(d))/(2*a);
double x2 = (-b +sqrt(d))/(2*a);
System.out.format("The roots of your quadratic formula are %5.3f and %5.3f\n",x1,x2);
Or, if you prefer support for solutions from the complex domain:
if (d < 0) {
System.out.println("Discriminant < 0, only imaginary solutions");
double r = -b / (2 * a);
double i1 = -sqrt(-d) / (2 / a);
double i2 = sqrt(-d) / (2 / a);
System.out.format("The roots of your quadratic formula are (%5.3f + %5.3fi) and (%5.3f + %5.3fi)\n",r, i1, r, i2);
return;
}
You are getting NaN because you are attempting to take the square root of a negative number. In math that's not allowed unless you are allowing complex numbers, e.g. 1 +/- 2i.
This can happen in quadratic formulas when the discriminant (the thing in the square root) is negative, e.g. x^2 + 6*x + 100: b^2 - 4ac = 36 - 400 = -364. Taking the square root of a negative number in Java leads to NaN. (not a number)
To test for NaN, use Double.isNaN and handle the NaN appropriately.
In addition, your calculations are incorrect even if NaN isn't being encountered:
$ java QuadraticFormulaSCN
insert value for a:
1
insert value for b:
5
insert value for C:
6
The x values are:-2.0-2.0
This should have outputted 2.0 and 3.0
You should only do the calculation when
discriminant is equal or greater than zero
if(((Math.pow(b,2)-(4*a*c))>= 0){ /* Calculation here */ }
else {/*error message or complex number calculus*/};
One thing I always try to do is put all my math in appropriate parenthesis to avoid an, all too easy, Order of Operations mistake. The NaN is saying "Not a number." You would also get that message if the user input numbers that could not produce a result, such as a trying to get the square root of a negative number. Also, just as a note, you can save sometime by only using on Scanner for a,b, and c.
public class QuadraticFormula{
public static void main(String[] args){
java.util.Scanner input = new java.util.Scanner(System.in);
double a = input.nextDouble();
double b = input.nextDouble();
double c = input.nextDouble();
double quadPos = (-b + Math.sqrt(Math.pow(b,2)-(4*a*c)))/(2*a);
double quadNeg = (-b - Math.sqrt(Math.pow(b,2)-(4*a*c)))/(2*a);
System.out.println("-b - = " + quadNeg + "\n-b + = " + quadPos);
}
}

Getting accurate roots of quadratic equation

This is the code that I have thus far. The goal of the project is to have the user enter any integers for a, b, c for the ax^2+bx+c equation. For some reason I am not getting the correct roots for any numbers that are input into the program. Can anyone point out my wrong doings?
import java.util.*;
public class Quad_Form {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
double a = 0;
double b = 0;
double c = 0;
double discrim = 0;
double d = 0;
System.out.println("Enter value for 'a'");
String str_a = sc.nextLine();
a = Integer.parseInt(str_a);
System.out.println("Enter value for 'b'");
String str_b = sc.nextLine();
b = Integer.parseInt(str_b);
System.out.println("Enter value for 'c'");
String str_c = sc.nextLine();
c = Integer.parseInt(str_c);
double x1 = 0, x2 = 0;
discrim = (Math.pow(b, 2.0)) - (4 * a * c);
d = Math.sqrt(discrim);
if(discrim == 0){
x1 = (-b + d) / (2* a);
String root_1 = Double.toString(x1);
System.out.println("There is one root at: " + root_1);
}
else {
if (discrim > 0)
x1 = (-b + d) / (2 * a);
x2 = (-b - d) / (2 * a);
String root_1 = Double.toString(x1);
String root_2 = Double.toString(x2);
System.out.println("There are two real roots at:" + root_1 + "and" + root_2);
}
if (discrim < 0){
x1 = (-b + d) / (2 * a);
x2 = (-b - d) / (2 * a);
String root_1 = Double.toString(x1);
String root_2 = Double.toString(x2);
System.out.println("There are two imaginary roots at:" + root_1 + "and" + root_2);
}
}
}
#Smit is right about one of the issues, but there's a second one as well.
Math.sqrt(discrim) won't work when discrim is negative. You should be taking Math.sqrt(Math.abs(discrim)) instead.
a, b, c, d are double and you are parsing them as Integer. So this could be one of problem.
Use
Double.parseDouble();
Another problem is you can not make square root of negative numbers. This will result in NaN. For that use following, but you should handle that properly to get exact result.
Math.sqrt(Math.abs());
Moreover you should use following formula for getting roots
Taken from Wikipedia Quadratic equation
Class Double
Class Math

Categories