-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPolynomial.java
More file actions
67 lines (53 loc) · 1.18 KB
/
Polynomial.java
File metadata and controls
67 lines (53 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
public class Polynomial{
double[] coefficients;
public Polynomial() {
coefficients = new double[1];
coefficients[0] = 0;
}
public Polynomial(double[] coefficients) {
this.coefficients = new double[coefficients.length];
for(int i = 0; i < coefficients.length; i++) {
this.coefficients[i] = coefficients[i];
}
}
public Polynomial add(Polynomial p) {
int length = 0;
if(coefficients.length > p.coefficients.length) {
length = coefficients.length;
}else {
length = p.coefficients.length;
}
double[] result = new double[length];
for(int i = 0; i < length; i++) {
double x, y = 0;
try {
x = coefficients[i];
} catch (Exception e) {
x = 0;
}
try {
y = p.coefficients[i];
} catch (Exception e) {
y = 0;
}
result[i] = x + y;
}
Polynomial q = new Polynomial(result);
return q;
}
public double evaluate(double x) {
double result = 0;
for(int i = 0; i < coefficients.length; i++) {
result += coefficients[i] * (Math.pow(x, i));
}
return result;
}
public boolean hasRoot(double x) {
double result = 0;
result = evaluate(x);
if(result == 0) {
return true;
}
return false;
}
}