在Java中评估三角函数表达式 [英] Evaluating trigonometric expressions in Java

查看:157
本文介绍了在Java中评估三角函数表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在控制台中插入三角函数以进一步处理它?例如,sin(x)= 2x + 3log(y)或类似的东西。我想..我需要输入一个表达式作为字符串,然后它被处理为。但怎么样?

/index.htmlrel =nofollow> exp4j



我们已经在我们的一个项目中广泛使用这个库来解决与您完全相同的问题正面临着。

 表达式e =新的ExpressionBuilder(3 * sin(y) -  2 /(x  -  2))
.variables(x,y)
.build()
.setVariable(x,2.3)
.setVariable(y,3.14);
double result = e.evaluate();

在您的特定情况下,您可以要求用户在控制台中输入以下内容并构建表达式使用这些输入:


  1. 输入要评估的表达式。这将成为ExpressionBuilder构造函数的参数。

  2. 输入代表表达式中变量的字符串。这将成为变量方法的输入。您可以将这些字符串作为键添加到可用于下一步的Map。

  3. 输入每个变量的值。这将成为setVariable方法的输入。您可以收集所有变量值作为上述步骤中创建的地图中的值。您可以迭代地图并调用setVariable(key,value),这样您就不需要事先知道表达式中有多少个变量。


How to insert a trigonometric function in the console for further work with it?? For example, sin(x) = 2x + 3log (y) or something like this.I think.. I need to enter an expression as a string, and then it is processed as. But how?

解决方案

Take a look at exp4j

We have used this library extensively in one of our projects for solving the exact same problem that you are facing.

Expression e = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
                .variables("x", "y")
                .build()
                .setVariable("x", 2.3)
                .setVariable("y", 3.14);
        double result = e.evaluate();

In your particular case, you can ask the user for the following inputs in the console and build your expression using these inputs :

  1. Enter the expression to evaluate. This will become the argument to the ExpressionBuilder constructor.
  2. Enter the Strings that represent the variables in the expression. This will become the input to the variables method. You can add these Strings as keys to a Map which can be used in the next step.
  3. Enter the value of each variable. This will become the input to the setVariable methods. You could collect all the variable values as values in the Map created in the above step. You can iterate over the map and call setVariable(key,value) so that you don't need to know how many variables are present in an expression before hand.

这篇关于在Java中评估三角函数表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆