Why write out
The roots are NaN and NaN in console?
I've read about NaN, but I don't find the right solution how can I repair the mistakes...
I've tried casting to double the discriminant and the roots but doesn't work.
Can somebody help me, where and what I need to rewrite?
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
Pattern newlineOrSpace = Pattern.compile(System
.getProperty("line.separator")
+ "|\\s");
sc.useDelimiter(newlineOrSpace);
System.out.print("Enter a, b, c: ");
double a = sc.nextDouble();
double b = sc.nextDouble();
double c = sc.nextDouble();
// System.out.format("a = %f, b = %f, c = %f", a, b, c);
double root1;
double root2;
double discriminant;
discriminant = Math.sqrt(b * b - 4 * a * c);
if (discriminant > 0) {
System.out.println("There are no real roots ");
} else {
root1 = (-b + discriminant) / (2 * a);
root2 = (-b - discriminant) / (2 * a);
System.out.println("The roots are " + root1 + " and " + root2);
}
Math.sqrt(x) returns NaN when x is negative, which then propagates through the rest of your code. You'll want to test for negative numbers before taking the square root:
discriminant = b * b - 4 * a * c;
if (discriminant < 0) {
System.out.println("There are no real roots ");
} else {
root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("The roots are " + root1 + " and " + root2);
}
Firstly, let's get rid of user input as a cause for this - it's much easier if the short but complete program contains all the data we need:
public class Test {
public static void main(String args[]) {
showRoots(2.0, 10.0, 2.0);
showRoots(10.0, 1.0, 1.0);
}
private static void showRoots(double a, double b, double c) {
double discriminant = Math.sqrt(b * b - 4 * a * c);
if (discriminant > 0) {
System.out.println("There are no real roots ");
} else {
double root1 = (-b + discriminant) / (2 * a);
double root2 = (-b - discriminant) / (2 * a);
System.out.println("The roots are " + root1 + " and " + root2);
}
}
}
This shows two cases - one where there really are roots - but the program claims there aren't - and one where there really aren't real roots, but the program prints them out as NaN. When you take the square root of a negative number, the result is NaN, which is why that's being displayed.
So, the problem is how you're dealing with the discriminant. There are real roots if b2 - 4ac is non-negative - but you've already taken the square root at that point and reversed the nature of the condition.
So, it should be:
private static void showRoots(double a, double b, double c) {
double discriminant = b * b - 4 * a * c;
if (discriminant < 0) {
System.out.println("There are no real roots ");
} else {
double discriminantRoot = Math.sqrt(discriminant);
double root1 = (-b + discriminantRoot) / (2 * a);
double root2 = (-b - discriminantRoot) / (2 * a);
System.out.println("The roots are " + root1 + " and " + root2);
}
}
Lessons to learn:
When you want to demonstrate a problem, it helps to keep it minimal; using hard-coded values is a good way of doing this
Be careful about the order of operations - in this case, you were trying to judge something using the wrong value because you'd taken the square root too early
Be careful with conditions and whether or not you're getting them the right way round
EDIT: As noted in comments, there are various special cases to consider too, including when a is 0 which would otherwise lead to a division by 0 issue.
Do
double discriminant = b * b - 4 * a * c;
if (discriminant >= 0) {
discriminant = Math.sqrt(discriminant);
root1 = (-b + discriminant) / (2 * a);
root2 = (-b - discriminant) / (2 * a);
System.out.println("The roots are " + root1 + " and " + root2);
}
else {
System.out.println("There are no real roots ");
}
You get that when your discriminant is negative. Like for a=1,b=2,c=3. Delta = 2*2 -4*1*3 = 4 - 12 = -8
Java can't calculate square root of negative number, it doesn't know about imaginary number i.
Related
So I try to make a program using java.
its input is integers, the integers are considered as the sum of 3 integers a, b and c (a^2 + b^2 = c^2), its output is c^2. To do this, I expand the equation combine a^2 + b^2 - c^2 = 0 and c = sum - a - b, get Math.pow(sum, 2) - 2 * sum * (a + b) + 2 * a * b. Then I get a + b <= sum*2/3 then I substitute all the combination of a, b into the equation to see when it is zero.
Here is my code:
/** Pythagorean Triples
* test case for small numbers
* Tony
*/
import java.util.*;
public class Solution54 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int times = sc.nextInt();
for (int i = 0; i < times; i++) {
/* prompt the sum and get the equation:
* Math.pow(sum, 2) - 24 * (a + b) + 2a*b = 0;
* we consider b >= a;
*/
double sum = sc.nextDouble();
double ablimits = Math.floor(sum / 3 * 2); // a + b <= ablimits
double alimits = Math.floor(ablimits / 2); // a <= alimits
//System.out.println("another round");
//System.out.print(alimits + " " + blimits);
A: for (double a = 1; a <= alimits; a++) {
B: for (double b = a; b <= sum - a; b++) {
double result = Math.pow((sum-a-b),2)-a*a-b*b;
//System.out.print("when a is " + a + " " + "when b is " + b + ":" + result + ";");
if (Math.pow(sum, 2) - 2 * sum * (a + b) + 2 * a * b == 0) {
double answer = a*a + b*b;
int output = (int)answer;
System.out.print(output + " ");
break A;
}
}
}
}
}
}
When I input 1 12 , it gives 25(because a,b,c=3,4,5; c^2 = 25), but it can't handle big inputs like 14808286 because my algorithm is not efficient enough. What is the efficient way to do this? Plz!
Let me preface this by saying I don't have intimate knowledge of Pythagorean triples or the math behind them. I just thought this was an interesting problem, so I gave it a stab.
I believe the key to this problem is knowing what you're looking for as you scan through possible values of a. Given
a + b + c = sum
and
a^2 + b^2 = c^2
you'll find that
b = (sum / 2) * (1 - (a / (sum - a)))
= (sum / 2) - ((a * sum) / (2 * (sum - a)))
You know that b must be a whole number. An interesting property of Pythagorean triples is that their sums are always even. That means that
(sum / 2) % 1 = 0
So all we really need to check to make sure b is valid (i.e. a whole number) is that
((a * sum) / (2 * (sum - a))) % 1 = 0
or, put more simply,
(a * sum) % (sum - a) = 0
Some other key points that simplify this problem, at least as you've stated it:
Once you have a, b can be computed using the third equation in this answer.
Once you have a and b, c follows easily from either of the Pythagorean triple equations.
You only need to print c^2 as your output. Once this is done you can break.
The code ends up being pretty simple:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Get the sum from System.in.
int sum = sc.nextInt();
// If the given sum is odd, return immediately.
// No Pythagorean triple will have an odd sum.
if ((sum ^ 1) == 1) {
return;
}
// Try all values of a within the expected bounds.
int aBound = sum / 2;
for (int a = 1; a < aBound; a++) {
// Check whether b would be a whole number with this value of a.
if ((a * sum) % (a - sum) == 0) {
int b = (sum * (2 * a - sum)) / (2 * a - 2 * sum);
int c = sum - a - b;
System.out.println((int)Math.pow(c, 2));
break;
}
}
}
It's worth noting that because I lack deep mathematical understanding of Pythagorean triples, there's very likely some further optimization that can be done in deciding which values of a actually need to be checked. I imagine there's some mathematical criteria for that.
I hope this helps!
How to make the method roots check imaginary roots and real one then return their values?
package warmup;
import java.util.HashSet;
import java.util.Set;
public class Quadratic {
/**
* Find the integer roots of a quadratic equation, ax^2 + bx + c = 0.
* #param a coefficient of x^2
* #param b coefficient of x
* #param c constant term. Requires that a, b, and c are not ALL zero.
* #return all integers x such that ax^2 + bx + c = 0.
*/
public static Set<Integer> roots(int a, int b, int c) {
Set<Integer> z = new HashSet<>();
int temp1 = (int)(Math.sqrt(b*b - 4*a*c));
if(a !=0){
if(temp1 >= 0){
Integer x1 = (int) ((-b + temp1) / (2*a));
Integer x2 = (int) ((-b - temp1) / (2*a));
z.add(x1);
z.add(x2);
} else if (temp1 < 0){
Integer x1 = (int) ((-b + temp1) / (2*a));
Integer x2 = (int) ((-b - temp1) / (2*a));
z.add(x1);
z.add(x2);
}
}else{
System.out.println("Error: division by zero.");
}
return z;
}
/**
* Main function of program.
* #param args command-line arguments
*/
public static void main(String[] args) {
System.out.println("For the equation x^2 - 4x + 3 = 0, the possible solutions are:");
Set<Integer> result = roots(1, -4, 3);
System.out.println(result);
}
trying to assign a negative square root number value to java is not allowed in JDK.
what you can do is, you can create a complex number class of your own and do your own operations there. Here is the example which i found online:
http://introcs.cs.princeton.edu/java/97data/Complex.java.html
I also looked at SO for similar questions like yours and i got this link
Hope this helps
This question already has answers here:
What does the ^ operator do in Java?
(19 answers)
Closed 7 years ago.
So I'm new to Java and I have an assignment to do for class, but I'm stuck. The class is supposed to find the intersection of two lines using the quadratic equation. I was told to have specific inputs for class, so d = 5, f = -3, g = 2, m = 1 and b = 3 and the two intersections are supposed to be (1,4) and (-.20,2.8). The problem I'm running into is that the output returns (NaN,NaN) and (NaN,NaN) instead of the right answer. Is there anything wrong with my code that is making me get this answer?
public class Intersect{
public static void main(String args[]){
//prompt user for parabola vars d f g
System.out.println("Enter the constant d:");
int d = IO.readInt();
System.out.println("Enter the constant f:");
int f = IO.readInt();
System.out.println("Enter the constant g:");
int g = IO.readInt();
// y = dx^2 + fx + g
//promt user for line vars m b
System.out.println("Enter the constant m:");
int m = IO.readInt();
System.out.println("Enter the constant b:");
int b = IO.readInt();
// y = mx + b
//compute intersection
// dx^2 + fx + g = mx + b
// x^2 * (d) + x * (f-m) + (g-b) = 0
int a = d;
int z = (f-m);
int c = (g-b);
double x1 = -z + (Math.sqrt (z^2 - 4 * a * c) / (2 * a));
double x2 = -z - (Math.sqrt (z^2 - 4 * a * c) / (2 * a));
double y1 = m * x1 + b;
double y2 = m * x2 - b;
//output each intersection on its own line, System.out.println() is ok for this answer submission
System.out.println("The intersection(s) are:");
System.out.println("(" + x1 + "," + y1 + ")");
System.out.println("(" + x2 + "," + y2 + ")");
}
}
^ is the xor operator in java and not the exponentiation operator. Therefore, the expresson z ^ 2 - 4 * a * c computes to something negative.
From the input you provide, z = -4, a = 5, c = -1. The expression translates to -4 ^ 2 - 4 * 5 * -1. Note that * and + have a higher precedence than ^, i.e. the order of evaluation is (-4 ^ (2 - ((4 * 5) * -1))) = -22.
Then you're trying to find the square root of -22, which, according to Math.sqrt(), is NaN.
Use Math.pow(z, 2), or simply use z * z instead:
Math.sqrt(z * z - 4 * a * c); // Note: This time operator precedence works,
// But you should use parentheses wherever
// the expression seems ambiguous.
First of all ^ is not an exponentiation operator, what causes Nan is the fact that you pass in a negative argument to Math.sqrt.
From java reference ( http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html ):
public static double sqrt(double a)
Returns the correctly rounded positive square root of a double value. Special cases:
If the argument is NaN or less than zero, then the result is NaN.
If the argument is positive infinity, then the result is positive infinity.
If the argument is positive zero or negative zero, then the result is the same as the argument.
Otherwise, the result is the double value closest to the true mathematical square root of the argument value.
Parameters:
a - a value.
Returns:
the positive square root of a. If the argument is NaN or less than zero, the result is NaN.
Its your order of operations that is causing you to get NaN results.
Try this(added variables for convenience):
int a = d;
int z = f - m;
int negZ = -z;
int c = g - b;
double sq = Math.sqrt((z * z) - (4 * a * c));
double a2 = 2 * a;
double x1 = (negZ + sq) / a2;
double x2 = (negZ - sq) / a2;
double y1 = (m * x1) + b;
double y2 = (m * x2) - b;
I saw someone else posted this problem but didn't word it properly so he didn't end up receiving any help, so I figured I would try and be more direct.
Here is the problem proposed to us :
// Write and submit your code in a file called Intersect.java. Use the IO module to read inputs. Use System.out.println() to print your answer.
Write a program that calculates the intersection between 2 equations:
a degree-2 (quadratic) polynomial i.e.
y = dx^2 + fx + g
where d, f, and g are constants
and a degree-1 (linear) equation i.e.
y = mx + b
where m is the slope and b is a constant
The above is just text, not code that could appear in a Java program.
Ask the user for the constant values in each equation. Output the intersection(s) as ordered pair(s) (x,y), or "none" if none exists. Below is an example run.
java Intersect
Enter the constant d:
5
Enter the constant f:
-3
Enter the constant g:
2
Enter the constant m:
1
Enter the constant b:
3
The intersection(s) is/are:
(1,4)
(-0.20,2.8)
//
The main problem is essentially asking us to write a code that asks the user to imput the individual constants and the slope of the two equations, one being a quadratic polynomial and the other being a linear equation in point-slope.
I understand that we have to use the quadratic equation in the code, however I have no idea how to actually code this in.
Once we have had the user imput the constants, in this case 5 (d,f,g,m,b; with m being slope) we need to have the code run the calculations to imput those constants into the above example ( y = dx^2 + fx + g | y = mx + b) and return either "none" if there is no intersection, or if it does intersect, the ordered pair at which it does intersect (x,y).
I know already that if 0 is entered as the constants it returns (NaN,NaN) which I also know needs to be re-written to None.
so far I only have the following:
public class Intersect {
public static void main(String[] args) {
System.out.println("Enter the constant d:");
int d = IO.readInt();
System.out.println("Enter the constant f:");
int f = IO.readInt();
System.out.println("Enter the constant g:");
int g = IO.readInt();
System.out.println("Enter the constant m:");
int m = IO.readInt();
System.out.println("Enter the constant b:");
int b = IO.readInt();
If anyone can shed some light on this that would be fantastic, thanks!
EDIT1 :
So far i've changed the code to the following, however, I still don't know how to get it to return to me an answer:
public class Intersect {
public static void main(String[] args) {
System.out.println("Enter the constant d:");
int d = IO.readInt();
System.out.println("Enter the constant f:");
int f = IO.readInt();
System.out.println("Enter the constant g:");
int g = IO.readInt();
System.out.println("Enter the constant m:");
int m = IO.readInt();
System.out.println("Enter the constant b:");
int b = IO.readInt();
//y = dx^2 + fx + g
//y = mx + b
//mx + b = dx^2 + fx + g
//x^2 * (d) + x * ( f - m ) + ( g - b )
int A = d;
int B = f - m;
int C = g - b;
double x1 = - B + Math.sqrt( B^2 - 4 * A * C ) / (2 * A);
double x2 = - B - Math.sqrt( B^2 - 4 * A * C ) / (2 * A);
double y1 = m * x1 + b;
double y2 = m * x1 + b;
}
Also, eclipse is telling me that x2,y1, and y2 aren't used at all.
I know I need to use System.out.println() however I don't understand what I can put there to make the answer an ordered pair. Also, I tried setting an If statement to have the answer return None instead of NaN however it instead returns, NaN None.
There are a lot of special cases you have to take into account.
I hope I've got them all right.
So after the initialization of the values you can put this:
// calculating some useful values.
double t = -(f - m) / (2.0 * d);
double u = t * t - (g - b) / (double) d;
// the first polynomial is linear, so both terms are.
if (d == 0) {
// both linear functions have the same slope.
if (f == m) {
// both functions are shifted the same amount along the y-Axis.
if (g == b)
// the functions lie on top of each other.
System.out.println("There is an infinite amount intersections");
// the functions are shifted different amounts along the y-Axis.
else
// the lines are parallel.
System.out.println("There are no intersections");
}
// both linear functions have different slopes.
else {
// solve linear equation.
double x = (b - g) / (double) (f - m);
double y = m * x + b;
System.out.println("The intersection is: (" + x + "," + y + ")");
}
}
// the functions do not cross each other.
else if (u < 0)
System.out.println("There are no intersections");
// the linear function is a tangent to the quadratic function.
else if (u == 0) {
// solve equation.
double x = t;
double y = m * x + b;
System.out.println("The intersection is: (" + x + "," + y + ")");
}
// the linear function intersects the quadratic function at two points.
else {
// solve quadratic equation.
double x1 = t + Math.sqrt(u);
double x2 = t - Math.sqrt(u);
double y1 = m * x1 + b;
double y2 = m * x2 + b;
System.out.println("The intersections are: (" + x1 + "," + y1 + ") (" + x2 + "," + y2 + ")");
}
i guess....
//y = dx^2 + fx + g
//y = mx + b
//mx + b = dx^2 + fx + g
//x^2 * (d) + x * ( f - m ) + ( g - b )
A = d
B = f - m
C = g - b
x1 = - B + sqr( B^2 - 4 * A * C ) / (2 * A)
x2 = - B - sqr( B^2 - 4 * A * C ) / (2 * A)
y1 = m * x1 + b
y2 = m * x1 + b
This quadratic equation will not return negative numbers in the string that I've determined it to return.
Here's the equation:
public class QuadraticEquation {
String final0;
public String calculate(int a, int b, int c) {
double done1 = ((-1 * b) + Math.sqrt((b * b) - (4 * a * c))) / (2 * a);
double done2 = ((-1 * b) - Math.sqrt((b * b) - (4 * a * c))) / (2 * a);
final0 = "x = " + (done1) + " or x = " + (done2);
return final0;
}
}
imagine an equation with a, b, and c values like -3, 13, and -4. The returning value of this would be -0.3(repeating) and -4. But this equation only returns positives, so in this case it would return 0.3(repeating) and 4. Why is this, and what can I do to fix it?
Note: I do believe that this is a Java error and not a math error. If it is a math error, let me know in the comments and I will promptly put it in the proper forums. Thanks.
public static void main(String[] args) {
String final0 = calculate(-3, 13, -4);
System.out.println(final0);
}
public static String calculate(int a, int b, int c) {
String final0 ;
int i = -1 * b; // -1 * 13 = -13
System.out.println(i);
int j = 4 * a * c; // 4 * -3 * -4 = 4 * 12 = 48
System.out.println(j);
double sqrt = Math.sqrt((b * b) - j); // sqrt ((13 * 13) - 48) = sqrt(169 - 48) = sqrt(121) = 11
System.out.println(sqrt);
double d = i + sqrt; // -13 + 11 = -2
System.out.println(d);
int k = 2 * a; // 2* -3 = -6
System.out.println(k);
double done1 = d / k; // -2 / -6 = 1/3 = 0.3333333333
System.out.println(done1);
double done2 = (i - sqrt) / k;
final0 = "x = " + (done1) + " or x = " + (done2);
return final0;
}
If you decompose your method to more local variables, you will see that math in java works correctly.
I would have thought
-3*x^2 + 13 *x + -4 = -3 * (x - 0.33333) * (x - 4) = 0
so two positive answers is correct.
Try instead
1 * x^2 + 0 * x -1 = (x - 1) * (x + 1) = 0
i.e. x = -1 or +1
Here is how I would write it.
public static String calculate(int a, int b, int c) {
double sqrt = Math.sqrt((b * b) - (4 * a * c));
double done1 = (-b + sqrt) / (2 * a);
double done2 = (-b - sqrt) / (2 * a);
return "x = " + (done1) + " or x = " + (done2);
}
The code is working correctly with your input. If you changed b to be -13 for example, you would get
x = -4.0 or x = -0.3333333333333333
Math.sqrt will always return a positive number ignoring complex numbers. But that is somewhat besides the point.