Need Help Finding the intersection of two equations in Java - java

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

Related

Math.sqrt showing an unexplained error in eclipse when trying to solve a second degree equation

I'm trying to create a program that solves second degree equations (ax 2 + bx + c = 0). It works fine when I remove Math.sqrt(delta) but having it is a very important part of the process and I can't figure out why it doesnt work.
When I run the program it gives me X1 = Nan X2 = Nan at the end.
public static void main(String[] args) {
double a, b, c, x1, delta;
Scanner sc = new Scanner(System.in);
System.out.println("Entrez Les Valeurs De a, b et c: ");
a = sc.nextInt();
b = sc.nextInt();
c = sc.nextInt();
delta = (b * b) - 4 * ( a * c );
x1 = (-b + Math.sqrt( delta ) )/(2 * a);
System.out.println("X1= " + x1);
}
If delta turns out to be negative, sqrt will return NaN

efficient algorithm for Pythagorean Triples in java

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!

Why is the output (Nan,Nan)? [duplicate]

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;

Why Quadratic equation's root result is NaN ? (Java)

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.

Modular inverse - java coding

Please help. I've been working on this non stop and can't get it right. The issue I'm having is that the output I'm getting for the inverse is always 1.
This is the code that I have (it computes GCD and trying to modify so it also computes a^-1):
import java.util.Scanner;
public class scratchwork
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
long n, a, on, oa;
long gcd = 0;
System.out.println("Please enter your dividend:");
n= keyboard.nextLong();
System.out.println("Please enter your divisor:");
a= keyboard.nextLong();
on= n;
oa= a;
while (a!= 0)
{gcd=a;
a= n% a;
n= gcd;
}
System.out.println("Results: GCD(" + odd + ", " + odr + ") = " + gcd);
long vX; vS; vT; vY; q; vR; vZ; m; b;
vX = n; vY=a;
vS = 0; vT = 1; m=0; b=0;
while (a != 0)
{
m=vT;;
b=vX;
q = n / a;
vR = vS - q*vT;
tZ = n - q*a;
vS = vT; n = da;
vT = tY; dY = vZ;
}
if (d>1) System.out.println("Inverse does not exist.");
else System.out.println("The inverse of "+oa+" mod "+on+" is "+vT);
}
}
The code you've posted does not declare most of the variables it uses and thus dues not compile. Most importantly, the variable v it uses to output the result is neither defined nor assigned to anywhere in the posted code - whatever it contains has nothing to do with the calculation.
Can we see the variables declaration? If you mix integer with double, your numbers can be rounded. Anyway, if you only want the inverse, juste use Math.pow(a, -1);
Also, in the second loop, you never set "a" so it will loop forever:
while (a != 0)
{
m=vT;;
b=vX;
q = n / a;
vR = vS - q*vT;
tZ = n - q*a;
vS = vT; n = da;
vT = tY; dY = vZ;
}
#Justin,
Thanks. I was able to figure out how to print out the variables in each loop. I basically had to put my loop up with the GCD loop...that was it. 2 weeks worth of work and I had just to move where the loop was.
It works! I'm sorry but I'm doing a happy dance over here.
Here's a solution in Python that should be easily translatable into Java:
def euclid(x, y):
"""Given x < y, find a and b such that a * x + b * y = g where, g is the
gcd of x and y. Returns (a,b,g)."""
assert x < y
assert x >= 0
assert y > 0
if x == 0:
# gcd(0,y) = y
return (0, 1, y)
else:
# Write y as y = dx + r
d = y/x
r = y - d*x
# Compute for the simpler problem.
(a, b, g) = euclid(r, x)
# Then ar + bx = g -->
# a(y-dx) + bx = g -->
# ay - adx + bx = g -->
# (b-ad)x + ay = g
return (b-a*d, a, g)
def modinv(x, n):
(a, b, g) = euclid(x%n, n)
assert g == 1
# a * x + b * n = 1 therefore
# a * x = 1 (mod n)
return a%n
It uses the stack, but Euclid's algorithm takes O(log n) steps so you won't have a stack overflow unless your numbers are astronomically high. One could also translate it into a non-recursive version with some effort.

Categories

Resources