在Java中评估数学表达式的方法 [英] Method for evaluating math expressions in Java

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

问题描述

在我的一个项目中,我想添加一个用户可以在公式中提供的功能,例如

In one of my projects I want to add a feature where the user can provide in a formula, for example

sin (x + pi)/2 + 1

我在我的Java应用程序中使用

which I use in my Java app

/**
 * The formula provided by the user
 */
private String formula; // = "sin (x + pi)/2 + 1"

/*
 * Evaluates the formula and computes the result by using the
 * given value for x
 */
public double calc(double x) {
    Formula f = new Formula(formula);
    f.setVar("x", x);
    return f.calc();
    // or something similar
}

我如何评估数学表达式?

How can I evaluate math expressions?

推荐答案

还有 exp4j ,一个基于 Dijkstra的Shunting Yard 。它可以在 Apache License 2.0 下免费获得并可再发行,大小只有 25KB ,非常容易使用:

There's also exp4j, an expression evaluator based on Dijkstra's Shunting Yard. It's freely available and redistributable under the Apache License 2.0, only about 25KB in size and quite easy to use:

Calculable calc = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
        .withVariable("x", varX)
        .withVariable("y", varY)
        .build()
double result1=calc.calculate();

使用较新的API版本,如 0.4.8

When using a newer API version like 0.4.8:

Expression calc = new ExpressionBuilder("3 * sin(y) - 2 / (x - 2)")
    .variable("x", x)
    .variable("y", y)
    .build();
double result1 = calc.evaluate();

exp4j

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

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