重写公式字符串以用Math.pow(a,b)替换a ^ b [英] Rewrite formula string to replace a^b with Math.pow(a, b)

查看:156
本文介绍了重写公式字符串以用Math.pow(a,b)替换a ^ b的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此刻,我正在尝试通过让用户输入公式来在HTML5 <canvas>上绘制公式.通过eval()可以很好地工作;但是,^在Javascript中表示按位XOR,而在公式中应表示至...的幂".

I'm at the moment trying to plot formulas on HTML5 <canvas> by letting the user put in a formula. This works great through eval(); however, the ^ means bitwise XOR in Javascript, while it should mean 'to the power of' in a formula.

所以基本上我必须将类似x^4的内容重写为Math.pow(x, 4).我想出了使用正则表达式的方法.但是,这一操作仅在一定程度上起作用:

So basically I'd have to rewrite something like x^4 to Math.pow(x, 4). I came up with using regular expressions. This one however only works to a certain extent:

"x^4".replace(/(.*)\^(.*)/g, "Math.pow($1, $2)")

它确实将x^4重写为Math.pow(x, 4),但是对于更高级的公式,这是错误的.例如,2 + x^4被重写为Math.pow(2 + x, 4),而它当然应该是2 + Math.pow(x, 4).此外,如果指数周围有括号,例如2^(x+1) + 3,当然应该将其重写为Math.pow(2, x+1) + 3而不是Math.pow(2, x+1 + 3).

It does rewrite x^4 to Math.pow(x, 4), but for more advanced formulas this goes wrong. For example, 2 + x^4 is rewritten as Math.pow(2 + x, 4), while it should of course be 2 + Math.pow(x, 4). Moreover, if the exponent has brackets around it, e.g. 2^(x+1) + 3, it should be rewritten to Math.pow(2, x+1) + 3 instead of Math.pow(2, x+1 + 3), of course.

我该如何重写它,以便仅将正确的部分放入pow函数中?我真的不知道从哪里开始,所以任何提示将不胜感激.

How would I go about rewriting this so that only the correct parts are put into the pow function? I really do not see where to start, so any tips would be greatly appreciated.

推荐答案

这是一个棘手的问题.您在这里所说的是一个表达式解析器.

This is a tricky one. What you're talking about here is an expression parser.

您可能想看看 Jison ,它旨在帮助人们解决此类问题问题.

You might want to take a look at Jison, which is designed to help people solve this type of problem.

正则表达式并不是解析标记化字符串的最佳方法. Jison的一个演示精确就表达式解析而言,这使您可以从事有趣的函数绘图工作.

Regular expressions aren't really the best way to do parsing of tokenized strings. One of Jison's demos is precisely what you're looking for, in terms of expression parsing, leaving you to work on the fun stuff of function graphing.

这篇关于重写公式字符串以用Math.pow(a,b)替换a ^ b的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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