-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPolynomial.java
More file actions
40 lines (32 loc) · 1.14 KB
/
Polynomial.java
File metadata and controls
40 lines (32 loc) · 1.14 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
public class Polynomial {
public double[] coefficients;
public Polynomial() {
this.coefficients = new double[]{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 other) {
int maxLength = Math.max(this.coefficients.length, other.coefficients.length);
double[] result = new double[maxLength];
for (int i = 0; i < maxLength; i++) {
double a = (i < this.coefficients.length) ? this.coefficients[i] : 0;
double b = (i < other.coefficients.length) ? other.coefficients[i] : 0;
result[i] = a + b;
}
return new Polynomial(result);
}
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) {
return Math.abs(evaluate(x)) < 1e-9;
}
}