-
Notifications
You must be signed in to change notification settings - Fork 0
/
Polynomial.java
38 lines (30 loc) · 1.02 KB
/
Polynomial.java
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
public class Polynomial {
private double[] coefficients;
public Polynomial() {
this.coefficients = new double[]{0};
}
public Polynomial(double[] coefficients) {
this.coefficients = coefficients;
}
public Polynomial add(Polynomial poly) {
int maxDegree = Math.max(this.coefficients.length, poly.coefficients.length);
double[] total = new double[maxDegree];
for (int i = 0; i < this.coefficients.length; i++) {
total[i] += this.coefficients[i];
}
for (int i = 0; i < poly.coefficients.length; i++) {
total[i] += poly.coefficients[i];
}
return new Polynomial(total);
}
public double evaluate(double x) {
double total = 0;
for (int i = 0; i < this.coefficients.length; i++) {
total += this.coefficients[i] * Math.pow(x, i);
}
return total;
}
public boolean hasRoot(double x) {
return evaluate(x) == 0;
}
}