我必须用PHP创建一个简单的公式解释器。它必须支持4个运算符:exp,ln,加法,减法和括号。
我应该从哪里开始?我听说用户输入的公式必须转换成树,是真的吗?也许口译员已经存在?
是的,更正用户输入的公式必须转换为abstract syntax tree。
数学公式通常使用infix表示法编写。你需要将其转换为postfix
或prefix
表示法。 postfix
符号也被称为reverse polish notation。
您可以使用shunting yard algorithm来完成此任务。 See a detailed example。
这个stackoverflow question链接到PHP中的实现。
您可以使用基本的字符串操作将公式重写为PHP表达式并将其重写为eval
。根据语法,您甚至可以单独保留表达式,只需为exp
和ln
定义PHP函数,因此当您输入eval
时,可以直接评估它。
这比为这样一种简单的语言编写自己的解析器和解释器要简单得多。
如果这是课堂作业,那么你的老师可能会因为这样做而失败。
我创建了这个,看看:Formula Interpreter
首先,使用公式及其参数创建FormulaInterpreter
的实例
$formulaInterpreter = new FormulaInterpreter("x + y", ["x" => 10, "y" => 20]);
使用execute()
方法解释公式。它将返回结果:
echo $formulaInterpreter->execute();
在一条线上
echo (new FormulaInterpreter("x + y", ["x" => 10, "y" => 20]))->execute();
# Formula: speed = distance / time
$speed = (new FormulaInterpreter("distance/time", ["distance" => 338, "time" => 5]))->execute() ;
echo $speed;
#Venezuela night overtime (ordinary_work_day in hours): (normal_salary * days_in_a_work_month)/ordinary_work_day
$parameters = ["normal_salary" => 21000, "days_in_a_work_month" => 30, "ordinary_work_day" => 8];
$venezuelaLOTTTArt118NightOvertime = (new FormulaInterpreter("(normal_salary/days_in_a_work_month)/ordinary_work_day", $parameters))->execute();
echo $venezuelaLOTTTArt118NightOvertime;
#cicle area
$cicleArea = (new FormulaInterpreter("3.1416*(radio*radio)", ["radio" => 10]))->execute();
echo $cicleArea;