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_2n {
007
008 public static void testi(double a, double b, double c) {
009 Polynomi2n p = new Polynomi2n(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 Polynomi2n {
041
042 private double a,b,c,x1,x2;
043 private int reaalijuuria;
044
045 public Polynomi2n(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 D = b*b - 4*a*c;
055 if ( D >= 0 ) {
056 SD = Math.sqrt(D);
057 x1 = (-b-SD)/(2*a);
058 x2 = (-b+SD)/(2*a);
059 return 2;
060 }
061 else return -1;
062 }
063 else /* a==0 */
064 if ( b != 0 ) {
065 x1 = x2 = c/b;
066 return 1;
067 }
068 else { /* a==0, b==0 */
069 if ( c == 0 ) return 1;
070 else return 0;
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 }