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_2r {
007
008 public static void testi(double a, double b, double c) {
009 Polynomi2r p = new Polynomi2r(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 Polynomi2r {
041
042 private double a,b,c,x1,x2;
043 private int reaalijuuria;
044
045 public Polynomi2r(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 return 0;
057 }
058 x1 = x2 = -c/b;
059 return 1;
060 }
061
062 D = b*b - 4*a*c;
063 if ( D < 0 ) return -1;
064
065 SD = Math.sqrt(D);
066 x1 = (-b-SD)/(2*a);
067 x2 = (-b+SD)/(2*a);
068 return 2;
069 }
070
071 public static double P2(double x, double a, double b, double c) {
072 return (a*x*x + b*x + c);
073 }
074
075 public double f(double x) { return P2(x,a,b,c); }
076 public double getX1() { return x1; }
077 public double getX2() { return x2; }
078 public int getReaalijuuria() { return reaalijuuria; }
079
080 public String toString() { return a + "x^2 + " + b + "x + " + c; }
081
082 }