-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPolynomial.java
More file actions
46 lines (37 loc) · 1.12 KB
/
Polynomial.java
File metadata and controls
46 lines (37 loc) · 1.12 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
public class Polynomial {
double[] coefficients;
public Polynomial() {
coefficients = new double[1];
}
public Polynomial(double[] coefficients) {
this.coefficients = coefficients;
}
public Polynomial add(Polynomial p2) {
int total_len = Math.max(this.coefficients.length, p2.coefficients.length);
double[] result = new double[total_len];
for (int i = 0; i < total_len; i++) {
if (i < this.coefficients.length) {
result[i] += this.coefficients[i];
}
if (i < p2.coefficients.length) {
result[i] += p2.coefficients[i];
}
}
Polynomial tmp = new Polynomial(result);
return tmp;
}
public double evaluate(double x) {
double result = 0;
for (int i = 0; i < this.coefficients.length; i++) {
result += this.coefficients[i] * Math.pow(x, i);
}
return result;
}
public boolean hasRoot(double x) {
double result = evaluate(x);
if (result == 0) {
return true;
}
return false;
}
}