001 /**
002 * Ohjelmalla testataan 2. asteen polynomin juurien etsimistä
003 * @author Vesa Lappalainen
004 * @version 1.0, 16.02.2003
005 */
006 public class P2_21 {
007
008 public static void testi(double a, double b, double c) {
009 Polynomi21 p = new Polynomi21(a,b,c);
010 System.out.print("Polynomi: " + p);
011 if ( p.getReaalijuuria() <= 0 ) {
012 System.out.println(" Ei yhtään reaalijuuria! ");
013 return;
014 }
015 System.out.print(" juuret: ");
016 System.out.print("x1 = " + p.getX1() + " => P(x1) = " + p.f(p.getX1()) );
017 System.out.print(" ja ");
018 System.out.print("x2 = " + p.getX2() + " => P(x2) = " + p.f(p.getX2()) );
019 System.out.println();
020 }
021
022 public static void main(String[] args) {
023 testi(1,2,1);
024 testi(2,1,0);
025 testi(1,-2,1);
026 testi(2,-1,0);
027 testi(2,1,1);
028 testi(2,0,0);
029 testi(0,2,1);
030 testi(0,0,1);
031 }
032 }
033
034
035 /**
036 * Luokka toisen asteen polynomille ja sen nollakohdille
037 * @author Vesa Lappalainen
038 * @version 1.0, 16.02.2003
039 */
040 class Polynomi21 {
041
042 private double a,b,c,x1,x2;
043 private int reaalijuuria;
044
045 public Polynomi21(double a, double b, double c) {
046 this.a = a; this.b = b; this.c = c;
047 reaalijuuria = ratkaise_2_asteen_yhtalo();
048 }
049
050 private int ratkaise_2_asteen_yhtalo() {
051 double D,SD;
052 x1 = x2 = 0;
053 if ( a == 0 )
054 if ( b == 0 ) {
055 if ( c == 0 ) return 1;
056 else return 0;
057 }
058 else {
059 x1 = x2 = -c/b;
060 return 1;
061 }
062 else {
063 D = b*b - 4*a*c;
064 if ( D >= 0 ) {
065 SD = Math.sqrt(D);
066 x1 = (-b-SD)/(2*a);
067 x2 = (-b+SD)/(2*a);
068 return 2;
069 }
070 else return -1;
071 }
072 }
073
074 public static double P2(double x, double a, double b, double c) {
075 return (a*x*x + b*x + c);
076 }
077
078 public double f(double x) { return P2(x,a,b,c); }
079 public double getX1() { return x1; }
080 public double getX2() { return x2; }
081 public int getReaalijuuria() { return reaalijuuria; }
082
083 public String toString() { return a + "x^2 + " + b + "x + " + c; }
084
085 }