简体   繁体   English

如何将数学方程式分解为系数和指数?

[英]How to split a mathematical equation into coefficients and exponents?

I am computing some equations in java. 我正在用Java计算一些方程式。 I want to use single linked list. 我想使用单个链表。 Nodes should have two integer data: coefficient and exponent. 节点应具有两个整数数据:系数和指数。

Here an example: equation = 18x^75-4x^56+18x^37+18x^19-18x^9-12 这里是一个示例:公式= 18x ^ 75-4x ^ 56 + 18x ^ 37 + 18x ^ 19-18x ^ 9-12

linked list= node1(18, 75)->node2(-4, 56)... it should be like that. 链表= node1(18,75)-> node2(-4,56)...应该是这样的。

I am asking just splitting. 我要分裂。

String equation = "18x^75-4x^56+18x^37+18x^19-18x^9-12";
String[] terms = equation.split("[0-9]+(?<=[-+*/()])|(?=[-+*/()])");
for (String term : terms) {
     System.out.println(term);
}
  • You can first split your equation with +- delimiter so that you get an array of each individual term. 您可以先使用+-分隔符来拆分方程式,以便获得每个单独项的数组。 Note that you will want to retain the sign if the term is negative. 请注意,如果该术语为负数,则您将希望保留该符号。
  • Then you can stream through the array of terms and for each term, split it further with the delimiter "x^". 然后,您可以流式传输术语数组,并为每个术语用定界符“ x ^”进一步拆分。 With this you will get two split items - one to the left of x^ is your coefficient and to the right is the exponent. 这样,您将获得两个拆分项-x ^左边的一项是您的系数,右边是指数。
  • Store the coefficient and exponent in an entry . 将系数和指数存储在entry
  • Store the entry in your linked list. 将条目存储在链接列表中。

Here's a working sample: 这是一个工作示例:

String equation = "18x^75-4x^56+18x^37+18x^19-18x^9-12";
String[] terms = equation.split("\\+|(?=\\-)");
Arrays.stream(terms).forEach(System.out::println);
List list = new LinkedList<Map.Entry<Integer, Integer>>();
Arrays.stream(terms).filter(t -> t.contains("x^")).forEach(
        s -> list.add(new AbstractMap.SimpleEntry(Integer.parseInt(s.split("x\\^")[0]), Integer.parseInt(s.split("x\\^")[1]))));
//Finally, add the constant term.
list.add(new AbstractMap.SimpleEntry(Integer.parseInt(terms[terms.length - 1]), 0));

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

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