-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPolynomial.java
More file actions
47 lines (38 loc) · 1.32 KB
/
Polynomial.java
File metadata and controls
47 lines (38 loc) · 1.32 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
47
public class Polynomial{
//coefficients of a polynomial
private double[] coefficients;
// implementing a no-argument constructor
public Polynomial(){
this.coefficients = new double[]{0};
}
// Constructor that takes an array of doubles as coefficients
public Polynomial(double[] coefficients){
this.coefficients = coefficients;
}
// Method to add two polynomials
public Polynomial add(Polynomial other){
int len = Math.max(this.coefficients.length, other.coefficients.length);
double[] result = new double[len];
for (int i = 0; i < len; ++i){
double a = 0, b = 0;
if (i < this.coefficients.length) a = this.coefficients[i];
if (i < other.coefficients.length) b = other.coefficients[i];
result[i] = a + b;
}
return new Polynomial(result);
}
// Method to evaluate the polynomial at a given value of x
public double evaluate(double x){
double result = 0;
double term = 1; // Start with x^0
for (double coeff : coefficients){
result += coeff * term;
term *= x;
}
return result;
}
// Method to check if a given value is a root of the polynomial
public boolean hasRoot(double x){
return evaluate(x) == 0;
}
}