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_2 {
007
008 public static void testi(double a, double b, double c) {
009 Polynomi2 p = new Polynomi2(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 /**
037 * Luokka toisen asteen polynomille ja sen nollakohdille
038 * @author Vesa Lappalainen
039 * @version 1.0, 16.02.2003
040 */
041 class Polynomi2 {
042
043 private double a,b,c,x1,x2;
044 private int reaalijuuria;
045
046 public Polynomi2(double a, double b, double c) {
047 this.a = a; this.b = b; this.c = c;
048 reaalijuuria = ratkaise_2_asteen_yhtalo();
049 }
050
051 private int ratkaise_2_asteen_yhtalo() {
052 double D,SD;
053 x1 = x2 = 0;
054 if ( a==0 ) { /* bx + c = 0 */
055 if ( b==0 ) { /* c = 0 */
056 if ( c==0 ) { /* 0 = 0 */
057 return 1; /* id. tosi */
058 } /* c==0 */
059 else { /* c!=0 */ /* 0 != c = 0 */
060 return 0; /* Aina epät. */
061 } /* c!=0 */
062 } /* b==0 */
063 else { /* b!=0 */ /* bx + c = 0 */
064 x1 = x2 = -c/b;
065 return 1;
066 } /* b!=0 */
067 } /* a==0 */
068 else { /* a!=0 */ /* axx + bx + c = 0 */
069 D = b*b - 4*a*c;
070 if ( D>=0 ) { /* Reaaliset juuret */
071 SD = Math.sqrt(D);
072 x1 = (-b-SD)/(2*a);
073 x2 = (-b+SD)/(2*a);
074 return 2;
075 } /* D>=0 */
076 else { /* Imag. juuret */
077 return -1;
078 } /* D<0 */
079 } /* a!=0 */
080 }
081
082 public static double P2(double x, double a, double b, double c) {
083 return (a*x*x + b*x + c);
084 }
085
086 public double f(double x) { return P2(x,a,b,c); }
087 public double getX1() { return x1; }
088 public double getX2() { return x2; }
089 public int getReaalijuuria() { return reaalijuuria; }
090
091 public String toString() { return a + "x^2 + " + b + "x + " + c; }
092
093 }