1
6 public class P2_2n {
7
8 public static void testi(double a, double b, double c) {
9 Polynomi2n p = new Polynomi2n(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 Polynomi2n {
41
42 private double a,b,c,x1,x2;
43 private int reaalijuuria;
44
45 public Polynomi2n(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 D = b*b - 4*a*c;
55 if ( D >= 0 ) {
56 SD = Math.sqrt(D);
57 x1 = (-b-SD)/(2*a);
58 x2 = (-b+SD)/(2*a);
59 return 2;
60 }
61 else return -1;
62 }
63 else
64 if ( b != 0 ) {
65 x1 = x2 = c/b;
66 return 1;
67 }
68 else {
69 if ( c == 0 ) return 1;
70 else return 0;
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