integration by java - java

I designing a polynomial class for one of my com sci courses , I have a problem of getting the integration method right
can some one help me with that
/** The polynomial class includes the methods: evaluate , add, multiply,
* Differentiate , integrate and square root.
*/
public class polynomial {
private int degree;
private double[] coefficients;
// a constructor that creates a polynomial of degree degMax with all the coefficients are zeroes
public polynomial(int degMax) {
degree= degMax;
coefficients = new double[degree + 1];
}
// a setter method that let the users set the coefficients for the polynomial they constructed
public void setCoefficient(int d , double v ){
if (d > degree)
{
System.out.println("Erorr Message: the degree you specified is larger than the polynomial's degree that you have created ");
}
else {
coefficients[d]=v;
}
}
// a getter method to return the coefficient for the specified degree
public double getCoefficient(int i){
return coefficients[i];
}
// private method that counts the degree of the polynomial by searching for the last element in the coefficient array that
// does not contain zero
private int getDegree() {
int deg = 0;
for (int i = 0; i < coefficients.length; i++)
if (coefficients[i] != 0) deg = i;
return deg;
}
// a method that print out the polynomial as a string
public String print(){
if (degree == 0) return "" + coefficients[0];
if (degree == 1) return coefficients[1] + "x + " + coefficients[0];
String s = coefficients[degree] + "x^" + degree;
for (int i = degree-1; i >= 0; i--) {
if (coefficients[i] == 0) continue;
else if (coefficients[i] > 0) s = s + " + " + ( coefficients[i]);
else if (coefficients[i] < 0) s = s + " - " + (-coefficients[i]);
if (i == 1) s = s + "x";
else if (i > 1) s = s + "x^" + i;
}
return s;
}
// a method that evaluate the polynomial at specified value x
public double evaluate(double x) {
double result = 0;
for (int i = degree; i >= 0; i--)
result = coefficients[i] + (x * result);
return result;
}
// a method that perform symbolic addition of two polynomial
public polynomial addition(polynomial p2) {
polynomial p1 = this;
polynomial p3 = new polynomial(Math.max(p1.degree, p2.degree));
for (int i = 0; i <= p1.degree; i++) p3.coefficients[i] += p1.coefficients[i];
for (int i = 0; i <= p2.degree; i++) p3.coefficients[i] += p2.coefficients[i];
p3.degree = p3.getDegree();
return p3;
}
// a method that performs a symbolic multiplication
public polynomial multiply(polynomial p2) {
polynomial p1 = this;
polynomial p3 = new polynomial(p1.degree + p2.degree);
for (int i = 0; i <= p1.degree; i++)
for (int j = 0; j <= p2.degree; j++)
p3.coefficients[i+j] += (p1.coefficients[i] * p2.coefficients[j]);
p3.degree = p3.getDegree();
return p3;
}
// a method that apply differentiation to polynomial
public polynomial differentiate() {
if (degree == 0) return new polynomial(0);
polynomial derivative = new polynomial(degree - 1);
derivative.degree = degree - 1;
for (int i = 0; i < degree; i++){
derivative.coefficients[i] = (i + 1) * coefficients[i + 1];
}
return derivative;
}
// a method that find a polynomial integral over the interval a to b
public double integration(double a , double b) {
polynomial integral= new polynomial (degree+1);
integral.degree= degree+1;
for (int i=0 ; i<= degree+1 ; i++){
if (i==0) {
integral.coefficients[i]= 0;
}
else {
integral.coefficients[i]= (coefficients[i-1]/i);
}
}
return (evaluate(b)- evaluate(a));
}
public static void main(String[] args) {
polynomial p1 = new polynomial(3);
p1.setCoefficient(0, 3.0);
p1.setCoefficient(3, 5.0);
String r = p1.print(); //3.0 + 5.0 x^3
polynomial p2 = new polynomial(2);
p2.setCoefficient(1, 4.0);
p2.setCoefficient(2, 2.0);
polynomial n = p1.addition(p2);
String po = n.print();
polynomial t = p1.multiply(p2);
String tr = t.print();
polynomial di = p2.differentiate();
String dir = di.print();
double ev = p2.evaluate(5.0);
double inte = p1.integration(3.0, 7.0);
System.out.println("p1(x) = " + r );
System.out.println("p1(x) + p2(x) = " + po);
System.out.println("p1(x) * p2(x) = " + tr);
System.out.println("p2'(x) = " + dir);
System.out.println("p1(x) integration over [3.0, 7.0] = " + inte);
System.out.println("p2(5.0) = " + ev);
}
}

If I were you, I would split the methods :
public Polynomial integrate()
{
Polynomial integral = new Polynomial(this.degree + 1);
for (int i = 1; i <= this.degree+1; i++)
{
integral.coefficients[i] = (this.coefficients[i - 1] / i);
}
return integral;
}
// a method that find a Polynomial integral over the interval a to b
public double integration(double a, double b)
{
Polynomial integral = integrate();
return (integral.evaluate(b) - integral.evaluate(a));
}
Ok now why it didn't work as you expected :
public double integration(double a , double b) {
polynomial integral= new polynomial (degree+1);
integral.degree= degree+1;
for (int i=0 ; i<= degree+1 ; i++){
if (i==0) {
integral.coefficients[i]= 0;
}
else {
integral.coefficients[i]= (coefficients[i-1]/i);
}
}
return (evaluate(b)- evaluate(a));
}
you messed up your "integral" object with the current instance "this", clean your code first :
public double integration(double a , double b) {
polynomial integral= new polynomial (this.degree+1);
integral.degree= this.degree+1;
for (int i=0 ; i<= this.degree+1 ; i++){
if (i==0) {
integral.coefficients[i]= 0;
}
else {
integral.coefficients[i]= (this.coefficients[i-1]/i);
}
}
return (this.evaluate(b)- this.evaluate(a));
}
Here you can see that you evaluate on your instance object instead of "integral" object. That's why it messed up the result.

You almost got it correct. The only problem is that you should call:
return (integral.evaluate(b) - integral.evaluate(a));
instead of:
return (evaluate(b)- evaluate(a));
Otherwise the code seems ok.

Adding to Boris' answer, you could simplify the integrate method like this:
public double integration(double a, double b) {
polynomial integral = new polynomial(degree + 1);
for (int i = 1; i <= degree + 1; i++) {
integral.coefficients[i] = coefficients[i - 1] / i;
}
return integral.evaluate(b) - integral.evaluate(a);
}

Related

reducing using instance variable to decrease the use of memory

I'm trying to do the Algorithm programming assignment of Princeton , and I met a problem about the memory test. The assignment requires us run the percolation program N times and find the medium of the result, and I write a percolationtest.java and for each time, I create an instance variable, it worked, but use too much memory, and the instructor suggests me to use local variable, but I don't know how. Can some one help me and give me some advice, I really appreciate it.
public class PercolationStats {
private int N, T, totalSum;
private double []fraction;
private int []count;
public PercolationStats(int N, int T) {
if (N <= 0 || T <= 0)
throw new IllegalArgumentException();
else {
this.N = N;
this.T = T;
count = new int [T];
totalSum = N*N;
fraction = new double[T];
int randomX, randomY;
for (int i = 0; i < T; i++) {
Percolation perc = new Percolation(N);
while (true) {
if (perc.percolates()) {
fraction[i] = (double) count[i]/totalSum;
break;
}
randomX = StdRandom.uniform(1, N+1);
randomY = StdRandom.uniform(1, N+1);
if (perc.isOpen(randomX, randomY)) continue;
else {
perc.open(randomX, randomY);
count[i]++;
}
}
}
}
} // perform T independent experiments on an N-by-N grid
public double mean() {
double totalFraction = 0;
for (int i = 0; i < T; i++) {
totalFraction += fraction[i];
}
return totalFraction/T;
} // sample mean of percolation threshold
public double stddev() {
double u = this.mean();
double sum = 0;
for (int i = 0; i < T; i++) {
sum += (fraction[i] - u) * (fraction[i] - u);
}
return Math.sqrt(sum/(T-1));
} // sample standard deviation of percolation threshold
public double confidenceLo() {
double u = this.mean();
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u-1.96*theta/sqrtT;
} // low endpoint of 95% confidence interval
public double confidenceHi() {
double u = this.mean();
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u+1.96*theta/sqrtT;
} // high endpoint of 95% confidence interval
public static void main(String[] args) {
int N = 200;
int T = 100;
if (args.length == 1) N = Integer.parseInt(args[0]);
else if (args.length == 2) {
N = Integer.parseInt(args[0]);
T = Integer.parseInt(args[1]); }
PercolationStats a = new PercolationStats(N, T);
System.out.print("mean = ");
System.out.println(a.mean());
System.out.print("stddev = ");
System.out.println(a.stddev());
System.out.print("95% confidence interval = ");
System.out.print(a.confidenceLo());
System.out.print(", ");
System.out.println(a.confidenceHi());
}
}
public class Percolation {
private boolean[][] site;
private WeightedQuickUnionUF uf;
private int N;
public Percolation(int N) {
if (N < 1)
throw new IllegalArgumentException();
else {
site = new boolean[N + 2][N + 2];
for (int j = 1; j <= N; j++) {
site[0][j] = true;
site[N + 1][j] = true;
}
uf = new WeightedQuickUnionUF((N + 2) * (N + 2));
for (int i = 1; i <= N; i++) {
uf.union(0, i);
}
this.N = N;
}
}
public void open(int i, int j) {
if (i > N || i < 1 || j > N || j < 1)
throw new IndexOutOfBoundsException();
else {
if (!site[i][j]) {
site[i][j] = true;
if (site[i - 1][j]) {
uf.union((N + 2) * (i - 1) + j, (N + 2) * i + j);
}
if (site[i + 1][j]) {
uf.union((N + 2) * i + j, (N + 2) * (i + 1) + j);
}
if (site[i][j + 1]) {
uf.union((N + 2) * i + (j + 1), (N + 2) * i + j);
}
if (site[i][j - 1]) {
uf.union((N + 2) * i + (j - 1), (N + 2) * i + j);
}
}
}
}
public boolean isOpen(int i, int j) {
if (i > N || i < 1 || j > N || j < 1)
throw new IndexOutOfBoundsException();
else
return site[i][j];
}
public boolean isFull(int i, int j) {
if (i > N || i < 1 || j > N || j < 1)
throw new IndexOutOfBoundsException();
else
return site[i][j] && (i == 1 || uf.connected((N + 2) * i + j, 0));
}
public boolean percolates() {
for (int i = 1; i <= N; i++) {
if (this.isFull(N, i)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
}
}
Added meanValue instance variable to keep mean value and replaced it in multiple places where you used to call mean() method which was over head to calculate again and again. Also modified "int[] count" as local variable which you were not using outside the constructor. post your "Percolation" and "StdRandom" classes for more optimization of code. you can run this code and test, it should reduce the runtime than yours.
public class PercolationStats {
private int N, T, totalSum;
private double []fraction;
private double meanValue;
public PercolationStats(int N, int T) {
if (N <= 0 || T <= 0)
throw new IllegalArgumentException();
else {
this.N = N;
this.T = T;
int [] count = new int [T];
totalSum = N*N;
fraction = new double[T];
int randomX, randomY;
for (int i = 0; i < T; i++) {
Percolation perc = new Percolation(N);
while (true) {
if (perc.percolates()) {
fraction[i] = (double) count[i]/totalSum;
break;
}
randomX = StdRandom.uniform(1, N+1);
randomY = StdRandom.uniform(1, N+1);
if (perc.isOpen(randomX, randomY)) continue;
else {
perc.open(randomX, randomY);
count[i]++;
}
}
}
}
}
// perform T independent experiments on an N-by-N grid
public double mean() {
double totalFraction = 0;
for (int i = 0; i < T; i++) {
totalFraction += fraction[i];
}
meanValue = totalFraction/T;
return meanValue;
} // sample mean of percolation threshold
public double stddev() {
double u = meanValue;
double sum = 0;
for (int i = 0; i < T; i++) {
sum += (fraction[i] - u) * (fraction[i] - u);
}
return Math.sqrt(sum/(T-1));
} // sample standard deviation of percolation threshold
public double confidenceLo() {
double u = meanValue;
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u-1.96*theta/sqrtT;
} // low endpoint of 95% confidence interval
public double confidenceHi() {
double u = meanValue;
double theta = this.stddev();
double sqrtT = Math.sqrt(T);
return u+1.96*theta/sqrtT;
} // high endpoint of 95% confidence interval
public static void main(String[] args) {
int N = 200;
int T = 100;
if (args.length == 1) N = Integer.parseInt(args[0]);
else if (args.length == 2) {
N = Integer.parseInt(args[0]);
T = Integer.parseInt(args[1]); }
PercolationStats a = new PercolationStats(N, T);
System.out.print("mean = ");
System.out.println(a.mean());
System.out.print("stddev = ");
System.out.println(a.stddev());
System.out.print("95% confidence interval = ");
System.out.print(a.confidenceLo());
System.out.print(", ");
System.out.println(a.confidenceHi());
}
}

java toString representation

I'm new to java and I'm trying to see if the method public String toString() is representing correctly the polynomial function. I don't know how to give the coefficients from main so that the class Func receives them.
package ro.utcluj.poo.lab04;
import java.util.Scanner;
class Func {
public double[] coef; //the coefficients
public int nrCoef; //coefficients number
public Func(double[] input)
{
nrCoef = input.length;
this.coef = new double[nrCoef];
for (int counter = 0; counter < input.length; counter++)
coef[counter] = input[counter];
}
public double getFuncValue(double x)
{
double exponent = nrCoef;
double y = 0;
double sum = 0;
for(int i = nrCoef; i >= 0; i--)
{
y = coef[i]*Math.pow(x, exponent-1); //n grade polynomial function
exponent--;
sum += y; //the sume for each member
}
return sum;
}
public double getDerivValue(double x)
{
double deriv = 0;
double rezDeriv = 0;
for(int i = 0; i < nrCoef - 1; i++)
{
deriv = coef[i]*(nrCoef - i)*Math.pow(x, nrCoef - i -1);
rezDeriv += deriv;
}
return rezDeriv;
}
public String toString()
{
String s = new String(" ");
int exp = nrCoef-1;
for(int i = 0; i < nrCoef; i++)
{
if(exp == 0 && coef[i] > 0)
s +="+" + coef[i];
else if(exp == 0 && coef[i] < 0)
s +=coef[i];
else if(exp == 1 && coef[i] > 0 && i == 0)
s +="+" + coef[i] + "x";
else if(exp == 1 && coef[i] >0)
s +="+" + coef[i];
else if(exp == 1 && coef[i] < 0)
s+=coef[i];
else if(coef[i] == 0)
s += "";
else if(coef[i] > 0 && i!=0)
s +="+" + coef[i]+"x^" + exp;
else
s +=coef[i] + "x^" + exp;
exp--;
System.out.println(s);
}
return s;
}
}
.
public class Main04 {
public static void main(String[] args) {
double[] v = new double[]{3,5,4};
Func f = new Func(v);
}
}
If you want to see what toString() does on your object f in main, all you need to do is
System.out.println(f);
f already has the coefficients that you passed into its constructor. println will call the object's toString() method and output the resulting string for you to see.
Also, as Steven pointed out in the comments, you don't need to put:
System.out.println(s);
in your toString() method itself. toString is supposed to produce and return the string. Your main method can deal with printing it out.
It's pretty simple to see what toString() does on object f in main...
You only have to yo use :
System.out.println(f);
This method will print the result of toString() to the command line.
That's all ;)
That worked but if I give the values {-3, -5, -4} I receive this:
-3.0x^2-5.0-4.0
It's missing the x from the second term(-5.0x). That is happining only if the second value is a negative one. For positive values it's working fine.
Try this way.
class Func {
public double[] coef; // the coefficients
public int nrCoef; // coefficients number
private StringBuilder sbl = new StringBuilder();
private StringBuilder tsbl = new StringBuilder();
public Func(double[] input) {
nrCoef = input.length;
this.coef = new double[nrCoef];
sbl.append("\nF(x) = ");
int exp = 0;
for (int counter = 0; counter < nrCoef; counter++) {
coef[counter] = input[counter];
if (coef[counter] != 0) {
if (counter != 0) {
sbl.append(coef[counter] < 0 ? " - " : " + ");
} else if (coef[counter] < 0) {
sbl.append(" - ");
}
exp = nrCoef - counter - 1;
sbl.append(Math.abs(coef[counter])+(exp == 0 ? "" : exp == 1 ? "*x" : "*x^"+exp));
}
}
}
public String toString() {
return tsbl.toString().isEmpty() ? sbl.toString() : tsbl.toString();
}
public double getFuncValue(double x) {
double sum = 0;
for (int index = 0; index < nrCoef; index++) {
sum += coef[index] * Math.pow(x, nrCoef - index - 1); // n grade polynomial
}
tsbl = new StringBuilder();
tsbl.append(sbl.toString());
tsbl.append("\nF(");
tsbl.append(x);
tsbl.append(") = "+sum);
return sum;
}
...

I have to modify a Polynomial implemented with integers, so that it can hold BigIntegers as well [duplicate]

This question already has an answer here:
How can I fix this "plus" method in Polynomial class using BigInteger
(1 answer)
Closed 8 years ago.
I have to modify a Polynomial implemented with integers, so that it can hold BigIntegers as well. I'm getting null pointer exception error. Please help!
Exception at Graph.Polynomial.plus(Polynomial.java:59) and at Graph.Polynomial.main(Polynomial.java:189)
package Graph;
import java.math.BigInteger;
public class Polynomial {
private BigInteger[] coef; // coefficients
private int deg; // degree of polynomial (0 for the zero polynomial)
/** Creates the constant polynomial P(x) = 1.
*/
public Polynomial(){
coef = new BigInteger[1];
coef[0] = new BigInteger("1");
deg = 0;
}
/** Creates the linear polynomial of the form P(x) = x + a.
*/
public Polynomial(BigInteger a){
coef = new BigInteger[2];
coef[1] = new BigInteger("1");
coef[0] = a;
deg = 1;
}
/** Creates the polynomial P(x) = a * x^b.
*/
public Polynomial(BigInteger a, BigInteger b) {
coef = new BigInteger[b.intValue()+1];
coef[b.intValue()] = a;
deg = degree();
}
/** Return the degree of this polynomial (0 for the constant polynomial).
*/
public int degree() {
int d = 0;
for (int i = 0; i < coef.length; i++)
if (coef[i]!= new BigInteger("0")) d = i;
return d;
}
/** Return the sum of this polynomial and b, i.e., return c = this + b.
*/
public Polynomial plus(Polynomial b) {
Polynomial a = this;
Polynomial c = new Polynomial(new BigInteger(("0"), Math.max(a.deg, b.deg)));
for (int i = 0; i <= a.deg; i++) c.coef[i] = c.coef[i].add(a.coef[i]);
for (int i = 0; i <= b.deg; i++) c.coef[i] = c.coef[i].add(b.coef[i]);
c.deg = c.degree();
return c;
}
/** Return the difference of this polynomial and b, i.e., return (this - b).
*/
public Polynomial minus(Polynomial b) {
Polynomial a = this;
Polynomial c = new Polynomial(new BigInteger("0", Math.max(a.deg, b.deg)));
for (int i = 0; i <= a.deg; i++) c.coef[i] = c.coef[i].add(a.coef[i]);
for (int i = 0; i <= b.deg; i++) c.coef[i] = c.coef[i].subtract(b.coef[i]);
c.deg = c.degree();
return c;
}
/** Return the product of this polynomial and b, i.e., return (this * b).
*/
public Polynomial times(Polynomial b) {
Polynomial a = this;
Polynomial c = new Polynomial(new BigInteger("0"), new BigInteger("a.deg").add(new BigInteger("b.deg")));
for (int i = 0; i <= a.deg; i++)
for (int j = 0; j <= b.deg; j++)
c.coef[i+j] = c.coef[i+j].add((a.coef[i].multiply(b.coef[j])));
c.deg = c.degree();
return c;
}
/** Return the composite of this polynomial and b, i.e., return this(b(x)) - compute using Horner's method.
*/
public Polynomial compose(Polynomial b) {
Polynomial a = this;
Polynomial c = new Polynomial(new BigInteger("0"), new BigInteger("0"));
for (int i = a.deg; i >= 0; i--) {
Polynomial term = new Polynomial(a.coef[i], new BigInteger("0"));
c = term.plus(b.times(c));
}
return c;
}
/** Return true whenever this polynomial and b are identical to one another.
*/
public boolean equals(Polynomial b) {
Polynomial a = this;
if (a.deg != b.deg) return false;
for (int i = a.deg; i >= 0; i--)
if (a.coef[i] != b.coef[i]) return false;
return true;
}
/** Evaluate this polynomial at x, i.e., return this(x).
*/
public BigInteger evaluate(BigInteger x) {
BigInteger p = new BigInteger("0");
for (int i = deg; i >= 0; i--)
p = coef[i].add((new BigInteger("x").multiply(new BigInteger("p"))));
return p;
}
/** Return the derivative of this polynomial.
*/
public Polynomial differentiate() {
if (deg == 0) return new Polynomial(new BigInteger("0"), new BigInteger("0"));
Polynomial deriv = new Polynomial(new BigInteger("0"), new BigInteger("deg").subtract(new BigInteger("1")));
deriv.deg = deg - 1;
for (int i = 0; i < deg; i++)
deriv.coef[i] = new BigInteger("i + 1").multiply(coef[i + 1]);
return deriv;
}
/** Return a textual representation of this polynomial.
*/
public String toString() {
if (deg == 0) return "" + coef[0];
if (deg == 1) return coef[1] + "x + " + coef[0];
String s = coef[deg] + "x^" + deg;
for (int i = deg-1; i >= 0; i--) {
if (coef[i] == new BigInteger("0")) continue;
else if (coef[i].signum()==1) s = s + " + " + ( coef[i]);
else if (coef[i].signum()== -1) s = s + " - " + (coef[i].multiply(new BigInteger("-1")));
if (i == 1) s = s + "x";
else if (i > 1) s = s + "x^" + i;
}
return s;
}
public static void main(String[] args) {
Polynomial zero = new Polynomial(new BigInteger("0"), new BigInteger("0"));
Polynomial p1 = new Polynomial(new BigInteger("476867"), new BigInteger("8"));
Polynomial p2 = new Polynomial(new BigInteger("3"), new BigInteger("2"));
Polynomial p3 = new Polynomial(new BigInteger("-1"), new BigInteger("0"));
Polynomial p4 = new Polynomial(new BigInteger("-2"), new BigInteger("1"));
Polynomial p = p1.plus(p2).plus(p3).plus(p4);
Polynomial q1 = new Polynomial(new BigInteger("3"), new BigInteger("2"));
Polynomial q2 = new Polynomial(new BigInteger("5"), new BigInteger("0"));
Polynomial q = q1.minus(q2);
Polynomial r = p.plus(q);
Polynomial s = p.times(q);
Polynomial t = p.compose(q);
System.out.println("zero(x) = " + zero);
System.out.println("p(x) = " + p);
System.out.println("q(x) = " + q);
System.out.println("p(x) + q(x) = " + r);
System.out.println("p(x) * q(x) = " + s);
System.out.println("p(q(x)) = " + t);
System.out.println("0 - p(x) = " + zero.minus(p));
System.out.println("p(3) = " + p.evaluate(new BigInteger("3")));
System.out.println("p'(x) = " + p.differentiate());
System.out.println("p''(x) = " + p.differentiate().differentiate());
Polynomial poly = new Polynomial();
for(int k=0; k<=3; k++){
poly = poly.times(new Polynomial(new BigInteger("-k")));
}
System.out.println(poly);
}
}
When you create a polynomial with this constructor:
public Polynomial(BigInteger a, BigInteger b) {
coef = new BigInteger[b.intValue()+1];
coef[b.intValue()] = a;
deg = degree();
}
most of the entries in the coef array will be null. This leads to a NPE when you later add two such polynomials with plus
On line 58 you have
Polynomial c = new Polynomial(new BigInteger(("0"), Math.max(a.deg, b.deg)));
I think you have a bug here.
This seems to create polynomial c of degree 0.
Basically you're calling this constructor.
BigInteger(String val, int radix)
I don't think this was your intention here,
maybe you put some brackets at some wrong places.

How can I fix this "plus" method in Polynomial class using BigInteger

I appreciate the help. I was able to finish modifying everything in this class into BigInteger format except for the compose method. Can anyone help me with this last part as to why it is not working correctly? I really appreciate it, thanks.
import java.math.BigInteger;
public class Polynomial {
private BigInteger[] coef; // coefficients
private int deg; // degree of polynomial (0 for the zero polynomial)
/** Creates the constant polynomial P(x) = 1.
*/
public Polynomial(){
coef = new BigInteger[1];
coef[0] = new BigInteger("1");
deg = 0;
}
/** Creates the linear polynomial of the form P(x) = x + a.
*/
public Polynomial(int a){
coef = new BigInteger[2];
coef[1] = new BigInteger("1");
coef[0] = new BigInteger(Integer.toString(a));
deg = 1;
}
/** Creates the polynomial P(x) = a * x^b.
*/
public Polynomial(int a, int b) {
coef = new BigInteger[b+1];
for(int i = 0; i < b; i++){
if(coef[i] == null)
coef[i] = new BigInteger("0");
}
coef[b] = new BigInteger(Integer.toString(a));
deg = degree();
}
/** Return the degree of this polynomial (0 for the constant polynomial).
*/
public int degree() {
int d = 0;
for (int i = 0; i < coef.length; i++)
if (coef[i] != null) d = i; // check to make sure this works
return d;
}
/** Return the composite of this polynomial and b, i.e., return this(b(x)) - compute using Horner's method.
*/
public Polynomial compose(Polynomial b) {
Polynomial a = this;
Polynomial c = new Polynomial(0, 0);
for (int i = a.deg; i >= 0; i--) {
Polynomial term = new Polynomial(a.coef[i].intValue(), 0);
c = term.plus(b.times(c));
}
return c;
}
public Polynomial times(Polynomial b) {
Polynomial a = this;
Polynomial c = new Polynomial(0, a.deg + b.deg);
for (int i = 0; i <= a.deg; i++)
for (int j = 0; j <= b.deg; j++)
c.coef[i+j] = c.coef[i+j].add((a.coef[i].multiply(b.coef[j])));
c.deg = c.degree();
return c;
}
/** Return a textual representation of this polynomial.
*/
public String toString() {
if (deg == 0) return "" + coef[0];
if (deg == 1) return coef[1] + "x + " + coef[0];
String s = coef[deg] + "x^" + deg;
for (int i = deg-1; i >= 0; i--) {
if (coef[i] == null) continue;
else if (coef[i].intValue() > 0) s = s + " + " + ( coef[i]);
else if (coef[i].intValue() < 0) s = s + " - " + (coef[i].negate());
if(coef[i].intValue() != 0)
if (i == 1) s = s + "x";
else if (i > 1) s = s + "x^" + i;
}
return s;
}
public static void main(String[] args) {
Polynomial p = new Polynomial(1,2);
Polynomial q = new Polynomial(2,3);
Polynomial t = p.compose(q); // incorrect
System.out.println("p(q(x)) = " + t); // incorrect
}
}
What I think is the problem is with your toString() itself as it does not align to your defaulting mechanism. Meaning, you assign default value of '0's but do not check for 0 values in the following lines:
if (i == 1) s = s + "x";
else if (i > 1) s = s + "x^" + i;
It gets piled up even for 0 coefficient values. Add a condition of checking non-zero coefficient only:
if (coef[i].intValue() != 0)
if (i == 1) s = s + "x";
else if (i > 1) s = s + "x^" + i;
This should work, I haven't tested it but you can try testing and post the results.
EDIT:
Well, i just tried your code and seems to give the correct information with the above condition in place:
6x^7 + 2x^3

Converting whole program from Int to BigInteger [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
So I already have this whole entire class done in Int and now I had to convert it to BigInteger. Main objective is so I can store the coefficients as the BigIntegers for large coefficients. I am getting a null pointer error with the code but I knew that BigInteger was immutable and needed that format. Just maybe another eye or maybe I'm just not doing this correctly.
public class Polynomial {
private BigInteger[] coef; // coefficients
private int deg; // degree of polynomial (0 for the zero polynomial)
/** Creates the constant polynomial P(x) = 1.
*/
public Polynomial(){
coef = new BigInteger[1];
coef[0] = BigInteger.valueOf(1);
deg = 0;
}
/** Creates the linear polynomial of the form P(x) = x + a.
*/
public Polynomial(int a){
coef = new BigInteger[2];
coef[1] = BigInteger.valueOf(1);
coef[0] = BigInteger.valueOf(a);
deg = 1;
}
/** Creates the polynomial P(x) = a * x^b.
*/
public Polynomial(int a, int b) {
coef = new BigInteger[b+1];
coef[b] = BigInteger.valueOf(a);
deg = degree();
}
public Polynomial(BigInteger a, int b) {
coef = new BigInteger[b+1];
coef[b] = a;
deg = degree();
}
/** Return the degree of this polynomial (0 for the constant polynomial).
*/
public int degree() {
int d = 0;
for (int i = 0; i < coef.length; i++)
if (coef[i] != BigInteger.valueOf(0)) d = i;
return d;
}
/** Return the sum of this polynomial and b, i.e., return c = this + b.
*/
public Polynomial plus(Polynomial b) {
Polynomial a = this;
Polynomial c = new Polynomial(0, Math.max(a.deg, b.deg));
for (int i = 0; i <= a.deg; i++) c.coef[i] = c.coef[i].add(a.coef[i]);
for (int i = 0; i <= b.deg; i++) c.coef[i] = c.coef[i].add(b.coef[i]);
c.deg = c.degree();
return c;
}
/** Return the difference of this polynomial and b, i.e., return (this - b).
*/
public Polynomial minus(Polynomial b) {
Polynomial a = this;
Polynomial c = new Polynomial(0, Math.max(a.deg, b.deg));
for (int i = 0; i <= a.deg; i++) c.coef[i] = c.coef[i].add(a.coef[i]);
for (int i = 0; i <= b.deg; i++) c.coef[i] = c.coef[i].subtract(b.coef[i]);
c.deg = c.degree();
return c;
}
/** Return the product of this polynomial and b, i.e., return (this * b).
*/
public Polynomial times(Polynomial b) {
Polynomial a = this;
Polynomial c = new Polynomial(0, a.deg + b.deg);
for (int i = 0; i <= a.deg; i++)
for (int j = 0; j <= b.deg; j++)
c.coef[i+j] = c.coef[i+j].add(a.coef[i].multiply(b.coef[j]));
c.deg = c.degree();
return c;
}
/** Return the composite of this polynomial and b, i.e., return this(b(x)) - compute using Horner's method.
*/
public Polynomial compose(Polynomial b) {
Polynomial a = this;
Polynomial c = new Polynomial(0, 0);
for (int i = a.deg; i >= 0; i--) {
Polynomial term = new Polynomial(a.coef[i], 0);
c = term.plus(b.times(c));
}
return c;
}
/** Return true whenever this polynomial and b are identical to one another.
*/
public boolean equals(Polynomial b) {
Polynomial a = this;
if (a.deg != b.deg) return false;
for (int i = a.deg; i >= 0; i--)
if (a.coef[i] != b.coef[i]) return false;
return true;
}
/** Evaluate this polynomial at x, i.e., return this(x).
*/
public int evaluate(int x) {
int p = 0;
for (int i = deg; i >= 0; i--){
coef[i] = coef[i].add(BigInteger.valueOf(x * p));
p = coef[i].intValue();
}
return p;
}
/** Return the derivative of this polynomial.
*/
public Polynomial differentiate() {
if (deg == 0) return new Polynomial(0, 0);
Polynomial deriv = new Polynomial(0, deg - 1);
deriv.deg = deg - 1;
for (int i = 0; i < deg; i++)
deriv.coef[i] = coef[i + 1].multiply(BigInteger.valueOf(i+1));
return deriv;
}
/** Return a textual representationof this polynomial.
*/
public String toString() {
if (deg == 0) return "" + coef[0];
if (deg == 1) return String.valueOf(coef[1]) + "x + " + String.valueOf(coef[0]);
String s = String.valueOf(coef[deg]) + "x^" + deg;
for (int i = deg-1; i > 0; i--) {
if (coef[i].intValue() == 0) continue;
else if (coef[i].intValue() > 0) s = s + " + " + ( coef[i].intValue());
else if (coef[i].intValue() < 0) s = s + " - " + (-coef[i].intValue());
if (i == 1) s = s + "x";
else if (i > 1) s = s + "x^" + i;
}
return s;
}
public static void main(String[] args) {
Polynomial zero = new Polynomial(1, 0);
Polynomial p1 = new Polynomial(4, 3);
Polynomial p2 = new Polynomial(3, 2);
Polynomial p3 = new Polynomial(-1, 0);
Polynomial p4 = new Polynomial(-2, 1);
Polynomial p = p1.plus(p2).plus(p3).plus(p4); // 4x^3 + 3x^2 - 2x - 1
Polynomial q1 = new Polynomial(3, 2);
Polynomial q2 = new Polynomial(5, 0);
Polynomial q = q1.minus(q2); // 3x^2 - 5
Polynomial r = p.plus(q);
Polynomial s = p.times(q);
Polynomial t = p.compose(q);
System.out.println("zero(x) = " + zero);
System.out.println("p(x) = " + p);
System.out.println("q(x) = " + q);
System.out.println("p(x) + q(x) = " + r);
System.out.println("p(x) * q(x) = " + s);
System.out.println("p(q(x)) = " + t);
System.out.println("0 - p(x) = " + zero.minus(p));
System.out.println("p(3) = " + p.evaluate(3));
System.out.println("p'(x) = " + p.differentiate());
System.out.println("p''(x) = " + p.differentiate().differentiate());
Polynomial poly = new Polynomial();
for(int k=0; k<=4; k++){
poly = poly.times(new Polynomial(-k));
}
System.out.println(poly);
}
}
So when you initialize your array of BigInteger, the values are null because you have specified an array of objects (if it was int[] then initial values are 0).
As you can see from your constructor:
public Polynomial(int a, int b) {
coef = new BigInteger[b+1];
coef[b] = BigInteger.valueOf(a);
deg = degree();
}
You have only assigned coef[b], the other values remain null.
Hence in first iteration of loop in method plus(Polynomial b), c.coef[0] is null hence NullPointerException when your loop tries to call c.coef[0].add(a.coef[0]).
Suggestion: define a method to initialize all the BigInteger values in an array to 0 to be consistent with declaration of int[] and call in your constructors. Example:
private static void initializeBigIntegerArray(BigInteger[] bigIntegers) {
for (int i=0; i<bigIntegers.length; i++) {
// So you don't overwrite anything you assign explicitly
if (bigInteger[i] == null) {
bigIntegers[i] = BigInteger.ZERO;
}
}
}
Recall that in Java an array of objects is actually an array of references to objects. So you need to create a BigInteger object for every array element. The entries you don't assign are not 0, they are null.
So in the plus method, you create this polynomial c whose backing array contains one zero, and several nulls. Then you go ahead and try to operate on all the coefficients in that polynomial, including all those nulls. So you're calling methods on variables for which an object hasn't been created yet, and that's what makes your null pointer problem.
When you create each polynomial, make sure you have a BigInteger created for every entry in the backing array.

Categories