Systems of equations calculator getting "NaN" - java

Here is my code.
import java.util.Scanner;
import java.util.ArrayList;
public class SysQ {
public static void main(String[] args) {
Scanner keyboard = new Scanner (System.in);
System.out.print("Enter A: ");
double a = keyboard.nextDouble();
System.out.print("Enter B: ");
double b = keyboard.nextDouble();
System.out.print("Enter C: ");
double c = keyboard.nextDouble();
System.out.print("Enter X: ");
double x = keyboard.nextDouble();
System.out.print("Enter Y: ");
double y = keyboard.nextDouble();
System.out.print("Enter Z: ");
double z = keyboard.nextDouble();
double fixedequation2 = x * b;
double fixedequation3 = x * c;
double fixedequation5 = a * y;
double fixedequation6 = a * z;
double final1 = fixedequation2 - fixedequation5;
double final2 = fixedequation3 - fixedequation6;
double yanswer = final2/final1;
double x1 = c - (b * yanswer);
double xanswer = x1/a;
System.out.println("X is " + xanswer);
System.out.println("Y is " + yanswer);
So the code works for most numbers for a 2 x 2 equation, but when I put in the values 5,5,5,5,5,5 for a,b,c,x,y,z, I get "NaN" I just want to know does "NaN" mean infinitely many solutions or No Solution..

NaN means "not a number". You get that solution because you are doing
(25-25)/(25-25) = 0/0, the result of which is undefined, or "Not a number"

Related

I think my program is giving an inaccurate result for Riemann Sums

this is my first post here!
So, as an extra credit project for my Calculus course, the professor offered us an opportunity to write a simple program that calculates the area under a user specified curve. I realize this isn't the best way to implement this, but he say's that's fine, but I think this is giving me the wrong answer. Could anyone help?
import java.util.*;
public class RiemannSum2 {
public static void main(String args []) {
System.out.println("This is a Riemann Sum Calculator. This calculator accepts polynomials in the form of a(x)^ex + b(x)^ex2 + c, where c is a constant.");
System.out.print("Enter the first coeffecient of the polynomial: ");
Scanner sc = new Scanner(System.in);
int firstCoe = sc.nextInt();
System.out.print("Enter the exponent of the first term: ");
int firstExp = sc.nextInt();
System.out.print("Enter the second coeffecient of the polynomial: ");
int secondCoe = sc.nextInt();
System.out.print("Enter the exponent of the second term: ");
int secondExp = sc.nextInt();
System.out.print("Enter the third term of the polynomial: ");
int thirdTerm = sc.nextInt();
System.out.print("Enter the x value that you want to start the Riemann Sum: ");
int startX = sc.nextInt();
System.out.print("Enter the x value to stop the Riemann Sum: ");
int endX = sc.nextInt();
String poly = (firstCoe+"x^"+firstExp+"+"+secondCoe+"x^"+secondExp+"+"+thirdTerm);
System.out.println("Your polynomial is: "+poly);
System.out.print("Enter the number of rectangles you want: ");
int rectangles = sc.nextInt();
double numerator = (endX-startX);
double rectanglesD = (double)rectangles;
double constantWidth = numerator/rectanglesD;
System.out.println("This is the constant width: " + constantWidth);
double totalSum = 0;
//System.out.println(totalSum);
for(int i = 0; i < rectangles ; i++) {
totalSum = totalSum+((Math.pow((firstCoe * (i/constantWidth)), firstExp)) + (Math.pow((secondCoe * (i/constantWidth)), secondExp))+thirdTerm);
}
totalSum = totalSum*constantWidth;
System.out.println("The Riemann Sum of your polynomial is roughly equivalent to: "+ totalSum);
}
}
You use (i/constantWidth) to calculate the argument of your function (x). However, it should be
double x = startX + i * constantWidth;
Furthermore, your coefficients should be outside of the pow function. Otherwise, they will get exponentiated too. Removing some of the superfluous parentheses makes the formula a lot easier to read. Like this:
double x = startX + i * constantWidth;
totalSum = totalSum
+ firstCoe * Math.pow(x, firstExp)
+ secondCoe * Math.pow(x, secondExp)
+ thirdTerm;
Unrelated to the code: Since you have a simple polynomial, you can calculate the antiderivative analytically and simply evaluate that function instead.

NaN error in quadratic formula calculator java

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

quadratic equation solver fails to get result in 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.

Java wrong output in (Fahrenheit to celsius conversion program) !

I am a beginner programmer
I have an assignment which is
Write a program that converts a Fahrenheit degree to Celsius using formula:
Celsius = (5/9)(Fahrenheit - 32)
The problem is I am always getting the same value -17.78 whatever I give value in input.
Here down there is my code !!!
package com.temperatureconversion;
import java.util.Scanner;
public class TemperatureConversion {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double F = 0.0; // Temperature in Fahrenheit
double C = 0.0; // Temperature in celsius
C = 5.0 /9 * (F - 32);
System.out.print("Enter temperature in fahrenheit: ");
F = input.nextDouble();
System.out.printf("The celsius value of %10.2f is %2.2f", F, C);
}
}
What's wrong with the above code ?
Your F value is always the same 0.0, because you're asking for its value after your calculations, so you need to move the getting of F value before doing calculation.
double F = 0.0; // Temperature in Fahrenheit
double C = 0.0; // Temperature in celsius
//ASK for value.
System.out.print("Enter temperature in fahrenheit: ");
F = input.nextDouble();
// Do your calculations.
C = 5.0 /9 * (F - 32);
Try this , ask first and then calculate
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double F = 0.0; // Temperature in Fahrenheit
double C = 0.0; // Temperature in celsius
System.out.print("Enter temperature in fahrenheit: ");
F = input.nextDouble();
C = 5.0 /9 * (F - 32);
System.out.printf("The celsius value of %10.2f is %2.2f", F, C);
}

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);
}
}

Categories