简体   繁体   English

Java中的数学表达式“泛型”

[英]Math Expression “generic” in Java

Well, I have a math expression in a string 好吧,我在字符串中有一个数学表达式

String myExpression = "2-3*(cos(x)+sen(x)-exp(-x))*(sen(2x)+1/(cos(x)))";

and I would like to know how to get the expression (in a string): 而且我想知道如何获取表达式(以字符串形式):

2-3*cos(x)*sen(2x)-3*cos(x)/cos(x)-3*sen(x)*sen(2x)-3*sen(x)/cos(x)+3*exp(-x)*sen(2x)+3*exp(-x)/cos(x)

ie, apply the distributive property, but without compute values. 即,应用分配属性,但不计算值。

Can anyone help me? 谁能帮我?

If you looking to convert a mathematically expression to another form, I recommend changing it to a postfix/prefix expressions (< link also tells you how to convert back to 'infix') first, and then try to toy with it (you can treat your functions(eg. sin(x) ) as constants). 如果您希望将数学表达式转换为另一种形式,建议您先将其更改为后缀/前缀表达式 (<链接还告诉您如何转换回“中缀”),然后再尝试用它(可以治疗)您的函数(例如sin(x) )作为常量)。 Hope you can do that yourself, plenty of sources to find references. 希望您能自己做,有大量资料可以找到参考。

Link to a simple Infix/Postfix Calculator so you can try it out if you haven't tried it before. 链接到一个简单的Infix / Postfix计算器,因此如果您以前从未尝试过,可以尝试一下。

Next, you convert back to infix, but this time distributing the multiplication and division 接下来,您转换回infix,但这一次分配乘法和除法

eg. 例如。

   *
  / \
 A   +
    / \
   B   /
      / \
     C   D

Infix: A*(B+C/D)
Postfix: ABCD/+*

ABCD/+*
C and D division first (distribute)                >>> C/D
B and C/D addition(addition,nothing to distribute) >>> B+C/D
A and B + C/D multiplication (distribute)          >>> A*B+A*C/D

So, generally speaking you do nothing but concatenate the addition and subtractions strings. 因此,总的来说,您什么也不做,只能将加法和减法字符串连接起来。
But: 但:

  1. When you have multiply by A then you add a "A*" string to the very beginning and after every '+' or '-' 如果乘以A则在开头和后面的每个'+''-'后面添加一个"A*"字符串

  2. When you have divide by B then you add a "/B" string to the very end and before every '+' or '-' . 如果用B除,则在末尾和每个'+''-'之前添加一个"/B"字符串。

I believe this should cover all simple expressions. 我相信这应该涵盖所有简单的表达方式。 You may (or may not) need a few more cases when the expression branched out extensively, haven't completely thought it through. 当表达式广泛分支时,您可能会(也可能不会)需要更多情况,但还没有完全考虑清楚。 I'll appreciate feedback. 我会很感激的反馈。

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

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