-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPolynomial.java
More file actions
40 lines (40 loc) · 1.29 KB
/
Polynomial.java
File metadata and controls
40 lines (40 loc) · 1.29 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 {
double [] coefficients;
public Polynomial() {
coefficients = new double[1];
coefficients[0] = 0;
}
public Polynomial(double[] arr) {
coefficients = new double[arr.length];
for (int i = 0; i < arr.length; i++) {
coefficients[i] = arr[i];
}
}
public Polynomial add(Polynomial x) {
int arr_len = Math.max(coefficients.length, x.coefficients.length);
int min_arr_len = Math.min(coefficients.length, x.coefficients.length);
double [] new_coefficients = new double[arr_len];
for (int i = 0; i < arr_len; i++) {
if (i < min_arr_len) {
new_coefficients[i] = coefficients[i] + x.coefficients[i];
}
else if (coefficients.length < x.coefficients.length) {
new_coefficients[i] = x.coefficients[i];
}
else {
new_coefficients[i] = coefficients[i];
}
}
return new Polynomial(new_coefficients);
}
public double evaluate(double x) {
double total = 0;
for (int i = 0; i < coefficients.length; i++) {
total += coefficients[i]*Math.pow(x, i);
}
return total;
}
public Boolean hasRoot(double root) {
return (evaluate(root) == 0);
}
}