1
6 public class P2_2 {
7
8 public static void testi(double a, double b, double c) {
9 Polynomi2 p = new Polynomi2(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
36
41 class Polynomi2 {
42
43 private double a,b,c,x1,x2;
44 private int reaalijuuria;
45
46 public Polynomi2(double a, double b, double c) {
47 this.a = a; this.b = b; this.c = c;
48 reaalijuuria = ratkaise_2_asteen_yhtalo();
49 }
50
51 private int ratkaise_2_asteen_yhtalo() {
52 double D,SD;
53 x1 = x2 = 0;
54 if ( a==0 ) {
55 if ( b==0 ) {
56 if ( c==0 ) {
57 return 1;
58 }
59 else {
60 return 0;
61 }
62 }
63 else {
64 x1 = x2 = -c/b;
65 return 1;
66 }
67 }
68 else {
69 D = b*b - 4*a*c;
70 if ( D>=0 ) {
71 SD = Math.sqrt(D);
72 x1 = (-b-SD)/(2*a);
73 x2 = (-b+SD)/(2*a);
74 return 2;
75 }
76 else {
77 return -1;
78 }
79 }
80 }
81
82 public static double P2(double x, double a, double b, double c) {
83 return (a*x*x + b*x + c);
84 }
85
86 public double f(double x) { return P2(x,a,b,c); }
87 public double getX1() { return x1; }
88 public double getX2() { return x2; }
89 public int getReaalijuuria() { return reaalijuuria; }
90
91 public String toString() { return a + "x^2 + " + b + "x + " + c; }
92
93 }
94