How do I convert strings to polynomials and add or subtract them?

I have to represent polynomials as arrayslist. How to take input from txt file that looks like this:

P1;5;3;-4;1;8;0
P2;6;5;-2;2;7;1;-4;0

      

and turn it into a polynomial like this

P1(X) = 5X^3 –4X +8
P2(X) = 6X^5 -2X^2 +7X -4.

      

And how can I solve the problem of addition and subtraction between these two polynomials? such as P1 + P2

?

here is what I have:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;


public class PolyProcessor {
    static int polyNum = 0;
public static void main(String[] args) throws FileNotFoundException{

    PolyCalc c = new PolyCalc();
    File polyfile = new File("polyinput.txt");
    Scanner read = new Scanner(polyfile);
    while (read.hasNextLine()){
        String j = read.nextLine();
        c.add(j);
        }


    }
    }


class PolyCalc{
    static int polyCount = 0;

    static ArrayList polynomials = new ArrayList();

     static void add(String j){

         polynomials.add(j);
         polyCount++;}

     static Object get(int i){
         return polynomials.get(i);}


    }

      

+3


source to share


4 answers


How does polynomial addition work?

Answer: - adding coefficients with the same power

SO P1 = 5X ^ 3 - 4X + 8

and P2 = 6X ^ 5 -2X ^ 2 + 7X ^ 1 + -4

becomes

P1 = 0X ^ 5 + 5X ^ 3 + 0X ^ 2 - 4X ^ 1 + 8X ^ 0

P2 = 6X ^ 5 + 0X ^ 3 -2X ^ 2 + 7X ^ 1 - 4X ^ 0

____________________________________



SUM = 6X ^ 5 + 5X ^ 3 -2X ^ 2 + 3X ^ 1 + 4X ^ 0

____________________________________



You can store cardinality as a key and coefficient as a value on the map. Then iterating over the maps and adding coefficients to their value

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

class SumOfPolynomials {

/**
 * @param args
 * @throws FileNotFoundException 
 */
public static void main(String[] args) throws FileNotFoundException {

     List<Map<Integer, Integer>> listOfPolynomials = new ArrayList<Map<Integer, Integer>>();
    File polyfile = new File("polyinput.txt");
    Scanner read = new Scanner(polyfile);
    while (read.hasNextLine()){
        String LINE = read.nextLine();
        String[] lineSpillted =LINE.split(";");
        Map<Integer, Integer> poynomial = new HashMap<Integer, Integer>();
        for(int i =1;i<lineSpillted.length-1;i=i+2){                //i starts from ignores P1,P2 etc

             poynomial.put(Integer.parseInt(lineSpillted[i+1]), Integer.parseInt(lineSpillted[i]));

        }
        listOfPolynomials.add(poynomial);
        }

    read.close();

    Map<Integer, Integer> result = polynomialSum(listOfPolynomials.get(0), listOfPolynomials.get(1));

    if(listOfPolynomials.size()>2){

        for(int i=2;i<listOfPolynomials.size()-1;i++){

            result = polynomialSum(result,listOfPolynomials.get(i));
        }
    }
    // print out the SUM as VALUEX^KEY
    System.out.println();
    int c = 0;
    for (Map.Entry<Integer, Integer> entry : result.entrySet()) {

        System.out.print(entry.getValue() + "X^" + entry.getKey());
        c++;
        if (c != result.size()) {
            System.out.print("+");
        }
    }

}

public static Map<Integer, Integer> polynomialSum(Map<Integer, Integer> arg1,
        Map<Integer, Integer> arg2) {

    Map<Integer, Integer> SUM = new HashMap<Integer, Integer>();

    for (Map.Entry<Integer, Integer> entry : arg1.entrySet()) {

        Integer power = entry.getKey();
        Integer coeff1 = entry.getValue();
        Integer coefficient;
        if (arg2.containsKey(power)) {
            coefficient = arg2.get(power) + coeff1;
        } else {
            coefficient = coeff1;
        }
        SUM.put(power, coefficient);
    }

    for (Map.Entry<Integer, Integer> entry : arg2.entrySet()) {

        if (SUM.containsKey(entry.getKey())) {
            continue;
        } else {
            SUM.put(entry.getKey(), entry.getValue());
        }

    }

    return SUM;
}

      

}

EDITED for multiple polynomials. Numerous polynomials are added to the list and then the sum is calculated by iterating over the list

Output: -

Output

+2


source


Here's an idea on how to implement a polynomial:

Based on the definition of polynomial :

In mathematics, a polynomial is an expression consisting of variables (or undefined) and coefficients, which includes only the operations of addition, subtraction, multiplication and non-negative integers.

So, you can start by shortening the problem to a term:



class Term {
    //making it immutable
    final double power;
    final double coefficient;
    final String variable;
    //constructor
    public Term(double power, double coefficient, String variable) {
        //assign variables and such
        this.power = power;
        //...
    }
    //getters for your class
}

      

Now create a class Polynomial

as List

terms and define the necessary methods to add and remove terms:

class Polynomial {
    final String variable;
    List<Term> terms;
    public Polynomial(String variable) {
        //this will allow you to accept only "X" or "Y" or terms with this variable only
        this.variable = variable;
        terms = new ArrayList<Terms>();
    }
    public void add(Term term) {
        /*
            implement this...
        */
    }
}

      

With this basic model, you can come up with more ideas for better design. For example, it Term

may implement Comparable<Term>

to support comparison between terms similar to Polynomial

other elements.

+1


source


The simplest solution I can think of is to store the coefficients in an array and let the array indices match powers on the member x

. So the array:

{2, 4, -1, 1}

Will translate to:

x^3 - x^2 + 4x + 2

Then addition and subtraction would simply be to add the appropriate indices between the two arrays and store the result in a new array. You would also have to keep track of the highest power term of the polynomial so that you know how big to make the array that represents it. Thus, the order polynomial n

would have an array size n + 1

to represent it.

0


source


Sorry the variable names were not close to math standards and this has not been tested, but that should leave you with some idea.

import java.util.ArrayList;
public class Poly {

    private String[] numbers;
    private ArrayList<Variable> func;

    public Poly(String poly, double valueOfX) {
        numbers = poly.split(";");
        func = new ArrayList<>();
        for (int i = 1; i < numbers.length - 1; i+=2) {
            double exp = (numbers[i+1] == "0") ? 1 : Double.parseDouble(numbers[i++]); 
            double x = (numbers[i+1] == "0") ? 1 : valueOfX; 
            func.add(new Variable(Double.parseDouble(numbers[i]), exp, x));
        }
    }

    public ArrayList<Variable> getFunc() {
        return func;
    }

}
public class Variable {

    private double value;
    private double exponent;
    private double x;

    public Variable(double value, double exponent, double x) {
        this.value = value;
        this.exponent = exponent;
        this.x = x;
    }

    public double getValue() {
        return value;
    }

    public double getExponent() {
        return exponent;
    }

    public double getX() {
        return x;
    }
}

      

Then you can get the variables you want and calculate the values ​​by getting the index of the arraylist and getting some magic.

0


source







All Articles