I am working on a function for the quadratic formula in java eclipse mars, and when I compile the code it outputs NaN when mathematically this answer is possible and i should get 2.0 please help
import java.util.Scanner;
public class Quadradic1 {
public static void main(String[] args) {
double a;
double b;
double c;
double x;
System.out.print("Input A B C: ");
Scanner input = new Scanner(System.in);
a = input.nextDouble();
b = input.nextDouble();
c = input.nextDouble();
x = (-b + Math.sqrt(b * b + 4 * a * c))/(2 * a);
System.out.println("Quadratic1 " + x);
}
}
Sorry the values I entered are a=1 b=2 and c=-8
For your inputs
b * b + 4 * a * c evaluates to -28. There is not such thing as the square root of a negative number
Related
I'm writing a simple program that solves a quadratic equation. I have to input a b c numbers in one line, but I can't do this.
My solution:
1
2
-4
But I need that input:
1 2 -4
This is my solution with 3 lines input instead one line input. Sorry for my bad english.
package com.sircascado;
import java.util.Scanner;
import java.lang.Math;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double a = sc.nextDouble();
double b = sc.nextDouble();
double c = sc.nextDouble();
double d = (b * b) - (4 * a * c);
double x1 = (-b - Math.sqrt(d)) / (2 * a);
double x2 = (-b + Math.sqrt(d)) / (2 * a);
System.out.println(Math.ceil(x1 + x2) + " " + Math.ceil(x1 * x2));
}
}
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 2 years ago.
This is the problem: Write a program that prompts for the lengths of the sides of a triangle and reports the three angles.
I have written the following code for it:
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please input length of side A: ");
int sideA = console.nextInt();
System.out.print("Please input length of side B: ");
int sideB = console.nextInt();
System.out.print("Please input length of side C: ");
int sideC = console.nextInt();
System.out.println();
System.out.println("The angle between A and B is: " + calculateAngle(sideA, sideB, sideC));
System.out.println("The angle between B and C is: " + calculateAngle(sideB, sideC, sideA));
System.out.println("The angle between C and A is: " + calculateAngle(sideC, sideA, sideB));
}
public static double calculateAngle(int a, int b, int c) {
return Math.toDegrees(Math.acos((a * a + b * b - c * c) / (2 * a * b)));
}
Here is a sample output from my code above:
Please input length of side A: 55
Please input length of side B: 22
Please input length of side C: 76
The angle between A and B is: 90.0
The angle between B and C is: 90.0
The angle between C and A is: 90.0
No matter what values I input for the sides, the only angles I ever get are 90 or 180 degrees, never the actual correct angle that can be calculated from the cosine rule. What is wrong with my code?
Just cast the calculation in Math.acos to double :
return Math.toDegrees(Math.acos((double)(a * a + b * b - c * c) / (2 * a * b)));
As you could see in comments, when computing between multiple int types, the integer arithmetic is used and then casted to double.
Also it's worth noting, that int always round down, meaning:
int i = 0.9999999; // i = 0
According to documentation they are expecting a double value as their parameter for acos method JavaSE7 Math doc
so re-arrange your code like this
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Please input length of side A: ");
double sideA = console.nextDouble();
System.out.print("Please input length of side B: ");
double sideB = console.nextDouble();
System.out.print("Please input length of side C: ");
double sideC = console.nextDouble();
System.out.println();
System.out.println("The angle between A and B is: " + calculateAngle(sideA, sideB, sideC));
System.out.println("The angle between B and C is: " + calculateAngle(sideB, sideC, sideA));
System.out.println("The angle between C and A is: " + calculateAngle(sideC, sideA, sideB));
}
public static double calculateAngle(double a, double b, double c) {
return Math.toDegrees(Math.acos((a * a + b * b - c * c) / (2 * a * b)));
}
Problem:
Write a program that reads the lengths of the sides of a triangle from the user. Compare the area of the triangle using Heron's formula, in which s represents half of the perimeter of the triangle and a,b, and c represent the lengths of the three sides.
import java.util.Scanner;
public class AreaOfTriangle
{
public static void main(String[]args)
{
Scanner scan = new Scanner(System.in);
final double NUM_ONE = 0.5;
int a, b, c;
double s, area;
System.out.print("Enter side a: ");
a = scan.nextInt();
System.out.print("Enter side b: ");
b = scan.nextInt();
System.out.print("Enter side c: ");
c = scan.nextInt();
s = NUM_ONE * (a + b + c);
area = Math.sqrt(s*(s-a)*(s-b)*(s-c));
System.out.println("\nThe area of the triangle = " + area);
}
}
The formula is correct, but s*(s-a)*(s-b)*(s-c) could end up being very slightly negative depending on the inputs (due to floating point imprecision). You should test this prior to taking the sqrt, and return zero in that instance.
Math.sqrt on a negative number will return NaN.
Because in some cases with your code you end up with a negative value in your sqrt call:
a = 1;
b = 2;
c = 5;
s = NUM_ONE * (a + b + c);
Here s = 4.0 and then your sqrt parameter is 4*3*2*-1 which is negative
Should you use Math.sqrt(Math.abs(...)) instead ?
I have yellow squiggly lines under my coeffA = in.nextDouble(); coeffB = in.nextDouble(); and coeffC = in.nextDouble(); in my tester class and can't figure out why? Also, when I run my tester class it always returns 0.0 and -0.0 I can't seem to get any calculations at all other than 0. Any help would be appreciated!
Directions:
I have to write a program that prints all real solutions to the quadratic equation ax^2 + bx + c = 0. Read in a, b, c and use the quadratic formula. If the discriminant b^2 - 4ac is negative, display a message stating that there are no real solutions. Implement a class QuadraticEquation whose constructor receives the coefficients a, b, c of the quadratic equation. Supply methods getSolution1 and getSolution2 that get the solutions, using the quadratic formula, or 0 if no solution exists. The getSolution1 method should return the smaller of the two solutions. Supply a method boolean hasSolutions() that returns false if the discriminant is negative.
public class QuadraticEquation
{
double coeffA;
double coeffB;
double coeffC;
private boolean hasSolutions;
double discriminant;
public QuadraticEquation()
{
coeffA = 0;
coeffB = 0;
coeffC = 0;
}
/**
Constructs a quadratic equation and get 2 solutions
#param coefficientA coefficient a of quadratic equation
#param coefficientB coefficient b of quadratic equation
#param coefficientC coefficient c of quadratic equation
*/
public QuadraticEquation(double coefficientA, double coefficientB, double coefficientC)
{
coeffA = coefficientA;
coeffB = coefficientB;
coeffC = coefficientC;
discriminant = (Math.pow(coeffB, 2) - 4 * coeffA * coeffC);
}
/**
* Checks if there is a solution
* #return true if there is a real solution
*/
public boolean hasSolutions()
{
if(discriminant < 0)
hasSolutions = false;
else
hasSolutions = true;
return hasSolutions;
}
/**
* Returns the first solution to the quadratic equation
* #return the first solution
*/
public double getSolution1()
{
return (-coeffB + Math.sqrt(discriminant) / 2 * coeffA);
}
/**
* Returns the second solution to the quadratic equation
* #return the second solution
*/
public double getSolution2()
{
return (-coeffB - Math.sqrt(discriminant) / 2 * coeffA);
}
}
Here is my tester class:
import java.util.Scanner;
/**
This program tests the QuadraticEquation class.
*/
public class QuadraticEquationTester
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter coefficient a: ");
double coeffA = in.nextDouble();
System.out.print("Please enter coefficient b: ");
double coeffB = in.nextDouble();
System.out.print("Please enter coefficient c: ");
double coeffC = in.nextDouble();
QuadraticEquation equation = new QuadraticEquation(0, 0, 0);
if (equation.hasSolutions())
System.out.println(equation.getSolution1());
if (equation.hasSolutions());
System.out.println(equation.getSolution2());
System.exit(0);
in.close();
}
}
Your problem is that when you create the instance of the class you enter 0, 0, 0. The class creation line should be as follows:
QuadraticFormula form = new
QuadraticFormula(Coefficient A, b,..)
Sorry the formatting is weird I'm doing this on my phone. But basically put the coefficient that the user enters into the scanner input into the arguments.
You have squiggly lines under coeffA = in.nextDouble(); coeffB = in.nextDouble(); and coeffC = in.nextDouble(); because you assign to them but never use them.
You should change QuadraticEquation equation = new QuadraticEquation(0, 0, 0); to QuadraticEquation equation = new QuadraticEquation(coeffA, coeffB, coeffC);.
In the getSolution methods, the expressions have parenthesis in the wrong spots, which is causing calculations to be performed in the wrong order.
It should be
(-coeffB + Math.sqrt(discriminant)) / (2 * coeffA)
and
(-coeffB - Math.sqrt(discriminant)) / (2 * coeffA)
Your if statements are also not correct. If it has real solutions, you want to print both solutions. If not, print that it has no real solutions:
if (equation.hasSolutions()) {
System.out.println(equation.getSolution1());
System.out.println(equation.getSolution2());
}
else {
System.out.println("No real solutions.");
}
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);
}
}