繁体   English   中英

如何从多项式字符串中获取系数和指数?

[英]How do I get the coefficients and exponents from a polynomial string?

我正在尝试从多项式字符串中提取系数和指数,然后将它们存储到数组中,以便可以使用这些数组创建一个新项,可以对其进行数学运算(例如,加,减和乘)

List<Term> poly = new ArrayList<>;
String poly = "26x^7+5x^6-8x^3-2";

int[] coeff = // Something like using split method here to get coeffs
int[] expo = // Same here but with exponents

for(int i = 0; i < coeffs.length; i++){
    poly.add(new Term(coeff[i], expo[i]);
}

问题是,我真的不知道该怎么做。 我尝试了很多方法,都导致了错误。

这是一个解决方案,它忽略了x ^ 1和x ^ 0且系数= 1的额外复杂性。

它采用前瞻的正则表达式描述在这里

import java.util.ArrayList;
import java.util.List;

public class MyClass {

    public static void main(String[] args) {
        // expect format ax^n for each term. in particular in the cases a=1, x=1 and x=0.
        String poly = "26x^7+5x^6-8x^3+1x^1-2x^0";

        // remove ^ and then split by x and by + and - keeping the sign
        String[] numbers = poly.replace("^", "").split("((?=\\+)|(?=\\-)|x)");

        List<Integer> coeff = new ArrayList<>();
        List<Integer> expo = new ArrayList<>();

        // we can now assume that for every coefficient there is an exponent
        for (int i = 0; i < numbers.length; i += 2) {
            coeff.add(Integer.parseInt(numbers[i]));
            expo.add(Integer.parseInt(numbers[i + 1]));
        }

        System.out.println(coeff);
        System.out.println(expo);
    }
}

输出:

[26, 5, -8, 1, -2]
[7, 6, 3, 1, 0]

我会尝试使用“ +”或“-”字符分割多边形。 如果Java中有一个regex split方法,那将是合适的。

由该拆分产生的数组是循环中要迭代的内容,以便填充多边形列表。

要注意的另一件事是多项式中的“ -2”项,从技术上讲,它是x ^ 0,而任何“ ax”项则是x ^ 1。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM