Single Variable Polynomial (from text file)

后端 未结 1 1295
走了就别回头了
走了就别回头了 2020-12-22 03:07

I want to modify the below code to read the nodes from a text file (vs. hard-coded values)

Furthermore, read data from text file in the format:

P1 = 3 5 1 -1

相关标签:
1条回答
  • 2020-12-22 03:48

    Unless your data is already in binary form, I wouldn't use DataInputStream. The example below uses BufferedReader to compose org.jscience.mathematics.function.Polynomial.

    Note that the highest order coefficient is first for convenience in applying Horner's scheme, as shown in this example.

    1 2 3 4
    4 3 2 1
    
    Coefficient: 1 2 3 4
    Polynomial:  [1]x³ + [2]x² + [3]x + [4]
    Coefficient: 4 3 2 1
    Polynomial:  [4]x³ + [3]x² + [2]x + [1]
    

    Code:

    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import org.jscience.mathematics.function.Polynomial;
    import org.jscience.mathematics.function.Term;
    import org.jscience.mathematics.function.Variable;
    import org.jscience.mathematics.number.Integer64;
    
    /** @see http://stackoverflow.com/questions/8276150 */
    public class ReadPoly {
    
        public static void main(String[] args) throws IOException {
            BufferedReader r = new BufferedReader(new FileReader("test.txt"));
            String s;
            while ((s = r.readLine()) != null) {
                System.out.println("Coefficient: " + s);
                Polynomial<Integer64> p = create(s.split(" "));
                System.out.println("Polynomial:  " + p);
            }
        }
    
        public static Polynomial<Integer64> create(String... a) {
            Variable<Integer64> x = new Variable.Local<Integer64>("x");
            Polynomial<Integer64> px = Polynomial.valueOf(Integer64.ZERO, x);
            for (int i = 0, e = a.length - 1; i < a.length; i++, e--) {
                px = px.plus(Polynomial.valueOf(
                    Integer64.valueOf(a[i]), Term.valueOf(x, e)));
            }
            return px;
        }
    }
    
    0 讨论(0)
提交回复
热议问题