Define the equals method for QuadraticExp class, which overrides the method inhe
ID: 3889384 • Letter: D
Question
Define the equals method for QuadraticExp class, which overrides the method inherited from Object
public class QuadraticExp
{
private double a;
private double b;
private double c;
// equals method
}
2.For Polynomial class
public class Polynomial
private int degree;
private double[] coeff;
// coeff[i] stores the coefficient for term x^i, for 0 <= i <= degree
// (1) Define a copy constructor for
public Polynomial( Polynomial p)
(2) add which return a polynomial that is the sum of p and this polynomial
// make sure the degree is set properly, which can be smaller than both
// the degree of this polynomial and the degree of p
public Polynomial add(Polynomial p)
// (3) write a simple main method to test your code
// assuming the following methods are already defined
public Polynomial()// Creates a polynomial represents 0
{ …}
public Polynomial(double a0)
// Creates a polynomial has a single x^0 term with coefficient a0
{ …}
public void add_to_coef(double amount, int exponent)
//Adds the given amount to the coefficient of the specified exponent.
public void assign_coef(double coefficient, int exponent)
// Sets the coefficient for the specified exponent.
Explanation / Answer
class QuadraticExp
{
private double a;
private double b;
private double c;
// equals method
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final QuadraticExp other = (QuadraticExp) obj;
if (Double.doubleToLongBits(this.a) != Double.doubleToLongBits(other.a)) {
return false;
}
if (Double.doubleToLongBits(this.b) != Double.doubleToLongBits(other.b)) {
return false;
}
if (Double.doubleToLongBits(this.c) != Double.doubleToLongBits(other.c)) {
return false;
}
return true;
}
}
class Polynomial {
private int degree;
private double[] coeff;
// coeff[i] stores the coefficient for term x^i, for 0 <= i <= degree
// (1) Define a copy constructor for
public Polynomial( Polynomial p) {
degree = p.degree;
Arrays.copyOf(coeff, degree + 1);
}
public Polynomial add(Polynomial p) {
Polynomial result = new Polynomial(0);
result.degree = max(p.degree, degree);
result.coeff = new double[result.degree + 1];
for (int i = 0; i < result.degree; i++) {
result.coeff[i] = 0;
if (i < this.degree)
result.coeff[i] += this.coeff[i];
if ( i < p.degree)
result.coeff[i] += p.coeff[i];
}
while (result.degree > 0) {
if (result.coeff[result.degree] == 0)
result.degree--;
else
break;
}
return result;
}
public void add_to_coef(double amount, int exponent) {
coeff[exponent] += amount;
}
public void assign_coef(double amount, int exponent) {
coeff[exponent] = amount;
}
public Polynomial(double a0) {
degree = 1;
coeff = new double[1];
coeff[0] = a0;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.