Solving 2nd degree equations • Write the following Java methods • boolean real-s
ID: 3825428 • Letter: S
Question
Solving 2nd degree equations
• Write the following Java methods
• boolean real-sols(double a, double b, double c): it returns true if the 2nd degree equation ax2 + bx + c has real solutions • double solution1(double a, double b, double c): If the equation ax2 + bx + c has real solutions it return the smallest of the two. If it doesn’t have real solutions it should return the value 0 and an error message.
• double solution2(double a, double b, double c): If the equation ax2 + bx + c has real solutions it return the biggest of the two. If it doesn’t have real solutions it should return the value 0 and an error message.
• Test your methods within a class and check that they work properly. Use the method real-sols(double a, double b, double c) in the implementation of the other 2 methods.
Explanation / Answer
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
static boolean real_sols(double a, double b, double c){
return (b*b)-(4*a*c)>=0;
}
static double solution1(double a, double b, double c){
double det = (b*b)-(4*a*c);
if(det<0){
System.out.println("Roots are imaginary");
return 0;
}
double s1 = (-b+Math.sqrt(det))/(2*a);
double s2 = (-b-Math.sqrt(det))/(2*a);
return Math.min(s1,s2);
}
static double solution2(double a, double b, double c){
double det = b*b-4*a*c;
if(det<0){
System.out.println("Roots are imaginary");
return 0;
}
double s1 = (-b+Math.sqrt(det))/(2*a);
double s2 = (-b-Math.sqrt(det))/(2*a);
return Math.max(s1,s2);
}
public static void main (String[] args) throws java.lang.Exception
{
double a, b, c;
a = 1;
b = 1;
c = 1;
System.out.println("Roots are real "+real_sols(a,b,c));
a = 1;
b = -3;
c = 2;
System.out.println("Roots are real "+real_sols(a,b,c));
System.out.println("Smallest soln is "+solution1(a,b,c));
System.out.println("Largest soln is "+solution2(a,b,c));
}
}
Output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.