Java中的数学表达式“通用”(Math Expression “generic” in Java)

编程入门 行业动态 更新时间:2024-10-09 13:25:34
Java中的数学表达式“通用”(Math Expression “generic” in Java)

好吧,我在一个字符串中有一个数学表达式

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

我想知道如何获取表达式(在一个字符串中):

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)

即,应用分配属性,但没有计算值。

谁能帮我?

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?

最满意答案

如果您希望将数学表达式转换为另一种形式,我建议首先将其更改为后缀/前缀表达式 (<link还告诉您如何转换回'中缀'),然后尝试用它玩具(您可以对待你的函数(例如sin(x) )作为常量)。 希望你能自己做,有很多资源可以找到参考资料。

链接到一个简单的中缀/后缀计算器,以便您可以尝试它,如果您以前没有尝试过。

接下来,您将转换回中缀,但这次分配乘法和除法

例如。

* / \ 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

所以,一般来说,除了连接加法和减法字符串之外什么都不做。 但:

当你乘以A然后你在最开始和每个'+'或'-'之后添加一个"A*"字符串

如果除以B则在最后和每个'+'或'-'之前添加一个"/B"字符串。

我相信这应该涵盖所有简单的表达方式。 当表达式广泛扩展时,您可能(或可能不)需要更多案例,但尚未完全考虑过。 我会很感激反馈。

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). 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.

Next, you convert back to infix, but this time distributing the multiplication and division

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:

When you have multiply by A then you add a "A*" string to the very beginning and after every '+' or '-'

When you have divide by B then you add a "/B" string to the very end and before every '+' or '-'.

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.

更多推荐

本文发布于:2023-07-27 04:00:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1284857.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表达式   数学   Java   generic   Expression

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!