Single Variable Polynomial (from text file)

陌路散爱 提交于 2019-11-29 16:50:11

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;
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!