Solving a quadratic equation using java

Solving a quadratic equation

Write two methods quadraticEquationRoot1 which takes as input 3 doubles, representing a,b,c and returns the larger of the two roots and quadraticEquationRoot 2 which takes as input 3 doubles, representing a,b, and c (in that order) and returns the smaller of the two roots.

Note that if there is a double root (because the square root term is 0), your two methods will return the same thing. Finally note that you may assume that the numbers a,b,c are chosen so that the square root is never the square root of a negative number.

I have the following but I don’t know to the write the second method and how to add a “return”.

**I have below the first method. I am not sure how to write the second method. **

**I am not allowed to use Scanner or have print statements * **

double quadraticEquationRoot1(int a, int b, int c)

{

if(Math.sqrt(Math.pow(b, 2) - 4*a*c) == 0)

{

return -b/(2*a);

}else

{

int root1, root2;

root1 = (-b + Math.sqrt(Math.pow(b, 2) - 4*a*c)) / (2*a);

root2 = (-b - Math.sqrt(Math.pow(b, 2) - 4*a*c)) / (2*a);

return Math.max(root1, root2);

}

}

Re: Solving a quadratic equation using java

The second method could use Math.min(), I suppose. (Once you have them doing what you want you might consider seeing if they can be simplified)

What do you mean by "add a return"? The code you posted has return statements.

Re: Solving a quadratic equation using java

Re: Solving a quadratic equation using java

Due to limitations of floating point math in software you may want to check out Quadratic equation - Wikipedia, the free encyclopedia

Regards,

Jim

Re: Solving a quadratic equation using java

Quote:

Originally Posted by

**jim829**

That tip is written in invisible ink, I'm sure; I tell people the same, all the time but all people do is use that same old formula over and over again (preferably using ints ;-), while it is a terrible formula, numerically speaking that is ...

kind regards,

Jos

Re: Solving a quadratic equation using java

It was because of **your** post within the last few months that I remembered it. I couldn't find the post in which you stated the same thing so I just repeated it and provided a reference.

Regards,

Jim

Re: Solving a quadratic equation using java

I you're interested in this stuff. google for "Jenkins Traub"; that algorithm numerically finds all roots of any polynomial, smallest to largest and is numerically very stable. There exists a faster version of this algorithm for real values only (the general case finds complex roots).

kind regards,

Jos