1
6 public class P2_2r {
7
8 public static void testi(double a, double b, double c) {
9 Polynomi2r p = new Polynomi2r(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 Polynomi2r {
41
42 private double a,b,c,x1,x2;
43 private int reaalijuuria;
44
45 public Polynomi2r(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 return 0;
57 }
58 x1 = x2 = -c/b;
59 return 1;
60 }
61
62 D = b*b - 4*a*c;
63 if ( D < 0 ) return -1;
64
65 SD = Math.sqrt(D);
66 x1 = (-b-SD)/(2*a);
67 x2 = (-b+SD)/(2*a);
68 return 2;
69 }
70
71 public static double P2(double x, double a, double b, double c) {
72 return (a*x*x + b*x + c);
73 }
74
75 public double f(double x) { return P2(x,a,b,c); }
76 public double getX1() { return x1; }
77 public double getX2() { return x2; }
78 public int getReaalijuuria() { return reaalijuuria; }
79
80 public String toString() { return a + "x^2 + " + b + "x + " + c; }
81
82 }
83