-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPolynomial.java
More file actions
46 lines (34 loc) · 853 Bytes
/
Polynomial.java
File metadata and controls
46 lines (34 loc) · 853 Bytes
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 [] coef;
public Polynomial() {
this.coef = new double[1];
}
public Polynomial(double [] coef) {
this.coef = new double[coef.length];
for (int i = 0; i < coef.length; ++i) {
this.coef[i] = coef[i];
}
}
public Polynomial add(Polynomial p) {
double [] x = new double[Math.max(p.coef.length, coef.length)];
for (int i = 0; i < x.length; ++i) {
if (i < Math.min(p.coef.length, coef.length))
x[i] = p.coef[i] + coef [i];
else if (p.coef.length > coef.length)
x[i] = p.coef[i];
else
x[i] = coef[i];
}
Polynomial q = new Polynomial(x);
return q;
}
public double evaluate(double x) {
double val = 0;
for (int i = 0; i < coef.length; ++i)
val += coef[i]*(Math.pow(x, i));
return val;
}
public boolean hasRoot(double x) {
return evaluate(x) == 0;
}
}