1
6 public class P2_21 {
7
8 public static void testi(double a, double b, double c) {
9 Polynomi21 p = new Polynomi21(a,b,c);
10 System.out.print("Polynomi: " + p);
11 if ( p.getReaalijuuria() <= 0 ) {
12 System.out.println(" Ei yhtään reaalijuuria! ");
13 return;
14 }
15 System.out.print(" juuret: ");
16 System.out.print("x1 = " + p.getX1() + " => P(x1) = " + p.f(p.getX1()) );
17 System.out.print(" ja ");
18 System.out.print("x2 = " + p.getX2() + " => P(x2) = " + p.f(p.getX2()) );
19 System.out.println();
20 }
21
22 public static void main(String[] args) {
23 testi(1,2,1);
24 testi(2,1,0);
25 testi(1,-2,1);
26 testi(2,-1,0);
27 testi(2,1,1);
28 testi(2,0,0);
29 testi(0,2,1);
30 testi(0,0,1);
31 }
32 }
33
34
35
40 class Polynomi21 {
41
42 private double a,b,c,x1,x2;
43 private int reaalijuuria;
44
45 public Polynomi21(double a, double b, double c) {
46 this.a = a; this.b = b; this.c = c;
47 reaalijuuria = ratkaise_2_asteen_yhtalo();
48 }
49
50 private int ratkaise_2_asteen_yhtalo() {
51 double D,SD;
52 x1 = x2 = 0;
53 if ( a == 0 )
54 if ( b == 0 ) {
55 if ( c == 0 ) return 1;
56 else return 0;
57 }
58 else {
59 x1 = x2 = -c/b;
60 return 1;
61 }
62 else {
63 D = b*b - 4*a*c;
64 if ( D >= 0 ) {
65 SD = Math.sqrt(D);
66 x1 = (-b-SD)/(2*a);
67 x2 = (-b+SD)/(2*a);
68 return 2;
69 }
70 else return -1;
71 }
72 }
73
74 public static double P2(double x, double a, double b, double c) {
75 return (a*x*x + b*x + c);
76 }
77
78 public double f(double x) { return P2(x,a,b,c); }
79 public double getX1() { return x1; }
80 public double getX2() { return x2; }
81 public int getReaalijuuria() { return reaalijuuria; }
82
83 public String toString() { return a + "x^2 + " + b + "x + " + c; }
84
85 }
86